diff --git a/AGENT_WORKFLOW.md b/AGENT_WORKFLOW.md new file mode 120000 index 000000000000..9435572ad7bf --- /dev/null +++ b/AGENT_WORKFLOW.md @@ -0,0 +1 @@ +../../../knowledge/agent_workflow.md \ No newline at end of file diff --git a/librarian.yaml b/librarian.yaml index 0d0abe910e5a..5fa92f3c6c4f 100644 --- a/librarian.yaml +++ b/librarian.yaml @@ -16,8 +16,8 @@ version: v0.22.0 repo: googleapis/google-cloud-python sources: googleapis: - commit: e57bae6efbd075a925978a79bb9b997beb4ecc19 - sha256: 762523e55a4cd9f57c7e5a952dd76ca6041c0e1dd405c14b1d6cfb165e4730b1 + commit: 73a8001701e1d3a668dbfb72e9ab66c97d107ff6 + sha256: 16b606051acfea9e3d2871a844e1106459294c540c5089fdcf7d306092e27813 default: output: packages tag_format: '{name}-v{version}' @@ -718,6 +718,7 @@ libraries: apis: - path: google/cloud/ces/v1 - path: google/cloud/ces/v1beta + skip_generate: true python: default_version: v1 - name: google-cloud-channel diff --git a/packages/google-cloud-biglake-hive/.repo-metadata.json b/packages/google-cloud-biglake-hive/.repo-metadata.json index 9a159cebba95..47dd8a7e06b8 100644 --- a/packages/google-cloud-biglake-hive/.repo-metadata.json +++ b/packages/google-cloud-biglake-hive/.repo-metadata.json @@ -1,5 +1,5 @@ { - "api_description": "The BigLake API provides access to BigLake Metastore, a serverless, fully\nmanaged, and highly available metastore for open-source data that can be\nused for querying Apache Iceberg tables in BigQuery.", + "api_description": "The Lakehouse API (formerly BigLake API) provides access to a serverless,\nfully managed, and highly available metastore that provides a single\nsource of truth for your data lakehouse. It lets multiple\nengines—including Apache Spark, Google Managed Spark, Apache Flink, Trino\nand BigQuery—share tables and metadata for key open formats (Apache\nIceberg, Apache Hive), and query the same copy of data. Plus, through the\nLakehouse runtime catalog federation seamlessly unite your lakehouse\necosystem, letting Iceberg compatible engines on Google Cloud (BigQuery,\nGoogle Managed Spark) discover and analyze enterprise data across\nSnowflake, Databricks, and AWS Glue.", "api_id": "biglake.googleapis.com", "api_shortname": "biglake", "client_documentation": "https://cloud.google.com/python/docs/reference/google-cloud-biglake-hive/latest", @@ -9,7 +9,7 @@ "language": "python", "library_type": "GAPIC_AUTO", "name": "google-cloud-biglake-hive", - "name_pretty": "BigLake", + "name_pretty": "Lakehouse", "product_documentation": "https://cloud.google.com/bigquery/", "release_level": "preview", "repo": "googleapis/google-cloud-python" diff --git a/packages/google-cloud-biglake-hive/README.rst b/packages/google-cloud-biglake-hive/README.rst index 579563ac2f80..7be4c1fe288d 100644 --- a/packages/google-cloud-biglake-hive/README.rst +++ b/packages/google-cloud-biglake-hive/README.rst @@ -1,11 +1,18 @@ -Python Client for BigLake -========================= +Python Client for Lakehouse +=========================== |preview| |pypi| |versions| -`BigLake`_: The BigLake API provides access to BigLake Metastore, a serverless, fully -managed, and highly available metastore for open-source data that can be -used for querying Apache Iceberg tables in BigQuery. +`Lakehouse`_: The Lakehouse API (formerly BigLake API) provides access to a serverless, +fully managed, and highly available metastore that provides a single +source of truth for your data lakehouse. It lets multiple +engines—including Apache Spark, Google Managed Spark, Apache Flink, Trino +and BigQuery—share tables and metadata for key open formats (Apache +Iceberg, Apache Hive), and query the same copy of data. Plus, through the +Lakehouse runtime catalog federation seamlessly unite your lakehouse +ecosystem, letting Iceberg compatible engines on Google Cloud (BigQuery, +Google Managed Spark) discover and analyze enterprise data across +Snowflake, Databricks, and AWS Glue. - `Client Library Documentation`_ - `Product Documentation`_ @@ -16,7 +23,7 @@ used for querying Apache Iceberg tables in BigQuery. :target: https://pypi.org/project/google-cloud-biglake-hive/ .. |versions| image:: https://img.shields.io/pypi/pyversions/google-cloud-biglake-hive.svg :target: https://pypi.org/project/google-cloud-biglake-hive/ -.. _BigLake: https://cloud.google.com/bigquery/ +.. _Lakehouse: https://cloud.google.com/bigquery/ .. _Client Library Documentation: https://cloud.google.com/python/docs/reference/google-cloud-biglake-hive/latest/summary_overview .. _Product Documentation: https://cloud.google.com/bigquery/ @@ -27,12 +34,12 @@ 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 BigLake.`_ +3. `Enable the Lakehouse.`_ 4. `Set up 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 -.. _Enable the BigLake.: https://cloud.google.com/bigquery/ +.. _Enable the Lakehouse.: https://cloud.google.com/bigquery/ .. _Set up Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html Installation @@ -100,14 +107,14 @@ Windows Next Steps ~~~~~~~~~~ -- Read the `Client Library Documentation`_ for BigLake +- Read the `Client Library Documentation`_ for Lakehouse to see other available methods on the client. -- Read the `BigLake Product documentation`_ to learn +- Read the `Lakehouse Product documentation`_ to learn more about the product and see How-to Guides. - View this `README`_ to see the full list of Cloud APIs that we cover. -.. _BigLake Product documentation: https://cloud.google.com/bigquery/ +.. _Lakehouse Product documentation: https://cloud.google.com/bigquery/ .. _README: https://github.com/googleapis/google-cloud-python/blob/main/README.rst Logging diff --git a/packages/google-cloud-biglake-hive/docs/README.rst b/packages/google-cloud-biglake-hive/docs/README.rst index 579563ac2f80..7be4c1fe288d 100644 --- a/packages/google-cloud-biglake-hive/docs/README.rst +++ b/packages/google-cloud-biglake-hive/docs/README.rst @@ -1,11 +1,18 @@ -Python Client for BigLake -========================= +Python Client for Lakehouse +=========================== |preview| |pypi| |versions| -`BigLake`_: The BigLake API provides access to BigLake Metastore, a serverless, fully -managed, and highly available metastore for open-source data that can be -used for querying Apache Iceberg tables in BigQuery. +`Lakehouse`_: The Lakehouse API (formerly BigLake API) provides access to a serverless, +fully managed, and highly available metastore that provides a single +source of truth for your data lakehouse. It lets multiple +engines—including Apache Spark, Google Managed Spark, Apache Flink, Trino +and BigQuery—share tables and metadata for key open formats (Apache +Iceberg, Apache Hive), and query the same copy of data. Plus, through the +Lakehouse runtime catalog federation seamlessly unite your lakehouse +ecosystem, letting Iceberg compatible engines on Google Cloud (BigQuery, +Google Managed Spark) discover and analyze enterprise data across +Snowflake, Databricks, and AWS Glue. - `Client Library Documentation`_ - `Product Documentation`_ @@ -16,7 +23,7 @@ used for querying Apache Iceberg tables in BigQuery. :target: https://pypi.org/project/google-cloud-biglake-hive/ .. |versions| image:: https://img.shields.io/pypi/pyversions/google-cloud-biglake-hive.svg :target: https://pypi.org/project/google-cloud-biglake-hive/ -.. _BigLake: https://cloud.google.com/bigquery/ +.. _Lakehouse: https://cloud.google.com/bigquery/ .. _Client Library Documentation: https://cloud.google.com/python/docs/reference/google-cloud-biglake-hive/latest/summary_overview .. _Product Documentation: https://cloud.google.com/bigquery/ @@ -27,12 +34,12 @@ 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 BigLake.`_ +3. `Enable the Lakehouse.`_ 4. `Set up 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 -.. _Enable the BigLake.: https://cloud.google.com/bigquery/ +.. _Enable the Lakehouse.: https://cloud.google.com/bigquery/ .. _Set up Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html Installation @@ -100,14 +107,14 @@ Windows Next Steps ~~~~~~~~~~ -- Read the `Client Library Documentation`_ for BigLake +- Read the `Client Library Documentation`_ for Lakehouse to see other available methods on the client. -- Read the `BigLake Product documentation`_ to learn +- Read the `Lakehouse Product documentation`_ to learn more about the product and see How-to Guides. - View this `README`_ to see the full list of Cloud APIs that we cover. -.. _BigLake Product documentation: https://cloud.google.com/bigquery/ +.. _Lakehouse Product documentation: https://cloud.google.com/bigquery/ .. _README: https://github.com/googleapis/google-cloud-python/blob/main/README.rst Logging diff --git a/packages/google-cloud-biglake-hive/docs/summary_overview.md b/packages/google-cloud-biglake-hive/docs/summary_overview.md index 9f7fc1da1b35..3f539b57d9cb 100644 --- a/packages/google-cloud-biglake-hive/docs/summary_overview.md +++ b/packages/google-cloud-biglake-hive/docs/summary_overview.md @@ -5,14 +5,14 @@ reverted. Instead, if you want to place additional content, create an pick up on the content and merge the content. ]: # -# BigLake API +# Lakehouse API -Overview of the APIs available for BigLake API. +Overview of the APIs available for Lakehouse API. ## All entries Classes, methods and properties & attributes for -BigLake API. +Lakehouse API. [classes](https://cloud.google.com/python/docs/reference/google-cloud-biglake-hive/latest/summary_class.html) diff --git a/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1beta/types/hive_metastore.py b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1beta/types/hive_metastore.py index ac2e68f75a45..171de8ca68c2 100644 --- a/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1beta/types/hive_metastore.py +++ b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1beta/types/hive_metastore.py @@ -73,7 +73,7 @@ class HiveCatalog(proto.Message): Attributes: name (str): - Output only. The resource name. Format: + Identifier. The resource name. Format: projects/{project_id_or_number}/catalogs/{catalog_id} description (str): Optional. Stores the catalog description. @@ -86,6 +86,11 @@ class HiveCatalog(proto.Message): replicas (MutableSequence[google.cloud.biglake_hive_v1beta.types.HiveCatalog.Replica]): Output only. The replicas for the catalog metadata. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time of the + catalog. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update time of the catalog. """ class Replica(proto.Message): @@ -151,6 +156,16 @@ class State(proto.Enum): number=4, message=Replica, ) + 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, + ) class CreateHiveCatalogRequest(proto.Message): @@ -322,7 +337,7 @@ class HiveDatabase(proto.Message): Attributes: name (str): - Output only. The resource name. Format: + Identifier. The resource name. Format: projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id} description (str): Optional. Stores the database description. @@ -335,6 +350,11 @@ class HiveDatabase(proto.Message): parameters (MutableMapping[str, str]): Optional. Stores the properties associated with the database. The maximum size is 2 MiB. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time of the + database. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update time of the database. """ name: str = proto.Field( @@ -354,6 +374,16 @@ class HiveDatabase(proto.Message): 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, + ) class CreateHiveDatabaseRequest(proto.Message): @@ -506,7 +536,7 @@ class HiveTable(proto.Message): Attributes: name (str): - Output only. The resource name. Format: + Identifier. The resource name. Format: projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id}/tables/{table_id} description (str): Optional. Description of the table. The @@ -520,9 +550,17 @@ class HiveTable(proto.Message): parameters (MutableMapping[str, str]): Optional. Stores the properties associated with the table. The maximum size is 4MiB. + view_original_text (str): + Optional. The original view text. Empty for + non-view. The maximum size is 16MiB. + view_expanded_text (str): + Optional. The expanded view text. Empty for + non-view. The maximum size is 16MiB. table_type (str): Output only. The type of the table. This is EXTERNAL for BigLake hive tables. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update time of the table. """ name: str = proto.Field( @@ -553,10 +591,23 @@ class HiveTable(proto.Message): proto.STRING, number=8, ) + view_original_text: str = proto.Field( + proto.STRING, + number=9, + ) + view_expanded_text: str = proto.Field( + proto.STRING, + number=10, + ) table_type: str = proto.Field( proto.STRING, number=11, ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) class FieldSchema(proto.Message): diff --git a/packages/google-cloud-biglake-hive/tests/unit/gapic/biglake_hive_v1beta/test_hive_metastore_service.py b/packages/google-cloud-biglake-hive/tests/unit/gapic/biglake_hive_v1beta/test_hive_metastore_service.py index 90081caf667f..940af0eb1f1c 100644 --- a/packages/google-cloud-biglake-hive/tests/unit/gapic/biglake_hive_v1beta/test_hive_metastore_service.py +++ b/packages/google-cloud-biglake-hive/tests/unit/gapic/biglake_hive_v1beta/test_hive_metastore_service.py @@ -5307,6 +5307,8 @@ def test_create_hive_table(request_type, transport: str = "grpc"): call.return_value = hive_metastore.HiveTable( name="name_value", description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", table_type="table_type_value", ) response = client.create_hive_table(request) @@ -5321,6 +5323,8 @@ def test_create_hive_table(request_type, transport: str = "grpc"): assert isinstance(response, hive_metastore.HiveTable) assert response.name == "name_value" assert response.description == "description_value" + assert response.view_original_text == "view_original_text_value" + assert response.view_expanded_text == "view_expanded_text_value" assert response.table_type == "table_type_value" @@ -5463,6 +5467,8 @@ async def test_create_hive_table_async(request_type, transport: str = "grpc_asyn hive_metastore.HiveTable( name="name_value", description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", table_type="table_type_value", ) ) @@ -5478,6 +5484,8 @@ async def test_create_hive_table_async(request_type, transport: str = "grpc_asyn assert isinstance(response, hive_metastore.HiveTable) assert response.name == "name_value" assert response.description == "description_value" + assert response.view_original_text == "view_original_text_value" + assert response.view_expanded_text == "view_expanded_text_value" assert response.table_type == "table_type_value" @@ -5675,6 +5683,8 @@ def test_get_hive_table(request_type, transport: str = "grpc"): call.return_value = hive_metastore.HiveTable( name="name_value", description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", table_type="table_type_value", ) response = client.get_hive_table(request) @@ -5689,6 +5699,8 @@ def test_get_hive_table(request_type, transport: str = "grpc"): assert isinstance(response, hive_metastore.HiveTable) assert response.name == "name_value" assert response.description == "description_value" + assert response.view_original_text == "view_original_text_value" + assert response.view_expanded_text == "view_expanded_text_value" assert response.table_type == "table_type_value" @@ -5823,6 +5835,8 @@ async def test_get_hive_table_async(request_type, transport: str = "grpc_asyncio hive_metastore.HiveTable( name="name_value", description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", table_type="table_type_value", ) ) @@ -5838,6 +5852,8 @@ async def test_get_hive_table_async(request_type, transport: str = "grpc_asyncio assert isinstance(response, hive_metastore.HiveTable) assert response.name == "name_value" assert response.description == "description_value" + assert response.view_original_text == "view_original_text_value" + assert response.view_expanded_text == "view_expanded_text_value" assert response.table_type == "table_type_value" @@ -6527,6 +6543,8 @@ def test_update_hive_table(request_type, transport: str = "grpc"): call.return_value = hive_metastore.HiveTable( name="name_value", description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", table_type="table_type_value", ) response = client.update_hive_table(request) @@ -6541,6 +6559,8 @@ def test_update_hive_table(request_type, transport: str = "grpc"): assert isinstance(response, hive_metastore.HiveTable) assert response.name == "name_value" assert response.description == "description_value" + assert response.view_original_text == "view_original_text_value" + assert response.view_expanded_text == "view_expanded_text_value" assert response.table_type == "table_type_value" @@ -6677,6 +6697,8 @@ async def test_update_hive_table_async(request_type, transport: str = "grpc_asyn hive_metastore.HiveTable( name="name_value", description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", table_type="table_type_value", ) ) @@ -6692,6 +6714,8 @@ async def test_update_hive_table_async(request_type, transport: str = "grpc_asyn assert isinstance(response, hive_metastore.HiveTable) assert response.name == "name_value" assert response.description == "description_value" + assert response.view_original_text == "view_original_text_value" + assert response.view_expanded_text == "view_expanded_text_value" assert response.table_type == "table_type_value" @@ -13169,6 +13193,8 @@ async def test_create_hive_table_empty_call_grpc_asyncio(): hive_metastore.HiveTable( name="name_value", description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", table_type="table_type_value", ) ) @@ -13197,6 +13223,8 @@ async def test_get_hive_table_empty_call_grpc_asyncio(): hive_metastore.HiveTable( name="name_value", description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", table_type="table_type_value", ) ) @@ -13253,6 +13281,8 @@ async def test_update_hive_table_empty_call_grpc_asyncio(): hive_metastore.HiveTable( name="name_value", description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", table_type="table_type_value", ) ) @@ -13442,6 +13472,8 @@ def test_create_hive_catalog_rest_call_success(request_type): "description": "description_value", "location_uri": "location_uri_value", "replicas": [{"region": "region_value", "state": 1}], + "create_time": {"seconds": 751, "nanos": 543}, + "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 @@ -13923,6 +13955,8 @@ def test_update_hive_catalog_rest_call_success(request_type): "description": "description_value", "location_uri": "location_uri_value", "replicas": [{"region": "region_value", "state": 1}], + "create_time": {"seconds": 751, "nanos": 543}, + "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 @@ -14241,6 +14275,8 @@ def test_create_hive_database_rest_call_success(request_type): "description": "description_value", "location_uri": "location_uri_value", "parameters": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "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 @@ -14728,6 +14764,8 @@ def test_update_hive_database_rest_call_success(request_type): "description": "description_value", "location_uri": "location_uri_value", "parameters": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "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 @@ -15089,7 +15127,10 @@ def test_create_hive_table_rest_call_success(request_type): "create_time": {"seconds": 751, "nanos": 543}, "partition_keys": {}, "parameters": {}, + "view_original_text": "view_original_text_value", + "view_expanded_text": "view_expanded_text_value", "table_type": "table_type_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 @@ -15166,6 +15207,8 @@ def get_message_fields(field): return_value = hive_metastore.HiveTable( name="name_value", description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", table_type="table_type_value", ) @@ -15185,6 +15228,8 @@ def get_message_fields(field): assert isinstance(response, hive_metastore.HiveTable) assert response.name == "name_value" assert response.description == "description_value" + assert response.view_original_text == "view_original_text_value" + assert response.view_expanded_text == "view_expanded_text_value" assert response.table_type == "table_type_value" @@ -15305,6 +15350,8 @@ def test_get_hive_table_rest_call_success(request_type): return_value = hive_metastore.HiveTable( name="name_value", description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", table_type="table_type_value", ) @@ -15324,6 +15371,8 @@ def test_get_hive_table_rest_call_success(request_type): assert isinstance(response, hive_metastore.HiveTable) assert response.name == "name_value" assert response.description == "description_value" + assert response.view_original_text == "view_original_text_value" + assert response.view_expanded_text == "view_expanded_text_value" assert response.table_type == "table_type_value" @@ -15622,7 +15671,10 @@ def test_update_hive_table_rest_call_success(request_type): "create_time": {"seconds": 751, "nanos": 543}, "partition_keys": {}, "parameters": {}, + "view_original_text": "view_original_text_value", + "view_expanded_text": "view_expanded_text_value", "table_type": "table_type_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 @@ -15699,6 +15751,8 @@ def get_message_fields(field): return_value = hive_metastore.HiveTable( name="name_value", description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", table_type="table_type_value", ) @@ -15718,6 +15772,8 @@ def get_message_fields(field): assert isinstance(response, hive_metastore.HiveTable) assert response.name == "name_value" assert response.description == "description_value" + assert response.view_original_text == "view_original_text_value" + assert response.view_expanded_text == "view_expanded_text_value" assert response.table_type == "table_type_value" diff --git a/packages/google-cloud-binary-authorization/.repo-metadata.json b/packages/google-cloud-binary-authorization/.repo-metadata.json index ad15abd6a1d7..a05e070da2f2 100644 --- a/packages/google-cloud-binary-authorization/.repo-metadata.json +++ b/packages/google-cloud-binary-authorization/.repo-metadata.json @@ -1,5 +1,5 @@ { - "api_description": "The management interface for Binary Authorization, a system providing\npolicy control for images deployed to Kubernetes Engine clusters, Anthos\nclusters on VMware, and Cloud Run.", + "api_description": "The management interface for Binary Authorization, a service that provides\npolicy-based deployment validation and control for images deployed to\nGoogle Kubernetes Engine (GKE), Anthos Service Mesh, Anthos Clusters, and\nCloud Run.", "api_id": "binaryauthorization.googleapis.com", "api_shortname": "binaryauthorization", "client_documentation": "https://cloud.google.com/python/docs/reference/binaryauthorization/latest", diff --git a/packages/google-cloud-binary-authorization/README.rst b/packages/google-cloud-binary-authorization/README.rst index 2bfa90b8fdd5..3b263cbb4573 100644 --- a/packages/google-cloud-binary-authorization/README.rst +++ b/packages/google-cloud-binary-authorization/README.rst @@ -3,9 +3,10 @@ Python Client for Binary Authorization |stable| |pypi| |versions| -`Binary Authorization`_: The management interface for Binary Authorization, a system providing -policy control for images deployed to Kubernetes Engine clusters, Anthos -clusters on VMware, and Cloud Run. +`Binary Authorization`_: The management interface for Binary Authorization, a service that provides +policy-based deployment validation and control for images deployed to +Google Kubernetes Engine (GKE), Anthos Service Mesh, Anthos Clusters, and +Cloud Run. - `Client Library Documentation`_ - `Product Documentation`_ diff --git a/packages/google-cloud-binary-authorization/docs/README.rst b/packages/google-cloud-binary-authorization/docs/README.rst index 2bfa90b8fdd5..3b263cbb4573 100644 --- a/packages/google-cloud-binary-authorization/docs/README.rst +++ b/packages/google-cloud-binary-authorization/docs/README.rst @@ -3,9 +3,10 @@ Python Client for Binary Authorization |stable| |pypi| |versions| -`Binary Authorization`_: The management interface for Binary Authorization, a system providing -policy control for images deployed to Kubernetes Engine clusters, Anthos -clusters on VMware, and Cloud Run. +`Binary Authorization`_: The management interface for Binary Authorization, a service that provides +policy-based deployment validation and control for images deployed to +Google Kubernetes Engine (GKE), Anthos Service Mesh, Anthos Clusters, and +Cloud Run. - `Client Library Documentation`_ - `Product Documentation`_ diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/async_client.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/async_client.py index cb19ac5fcc07..4e6b6a4d3438 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/async_client.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/async_client.py @@ -45,6 +45,10 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.cloud.binaryauthorization_v1.services.binauthz_management_service_v1 import ( pagers, @@ -378,7 +382,7 @@ async def sample_get_policy(): Args: request (Optional[Union[google.cloud.binaryauthorization_v1.types.GetPolicyRequest, dict]]): The request object. Request message for - [BinauthzManagementService.GetPolicy][]. + [BinauthzManagementServiceV1.GetPolicy][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.GetPolicy]. name (:class:`str`): Required. The resource name of the [policy][google.cloud.binaryauthorization.v1.Policy] to @@ -397,8 +401,8 @@ async def sample_get_policy(): Returns: google.cloud.binaryauthorization_v1.types.Policy: - A [policy][google.cloud.binaryauthorization.v1.Policy] - for container image binary authorization. + A [policy][google.cloud.binaryauthorization.v1.Policy] for container image + binary authorization. """ # Create or coerce a protobuf request object. @@ -465,8 +469,8 @@ async def update_policy( [policy][google.cloud.binaryauthorization.v1.Policy]. A policy is always updated as a whole, to avoid race conditions with concurrent policy enforcement (or management!) requests. Returns - NOT_FOUND if the project does not exist, INVALID_ARGUMENT if the - request is malformed. + ``NOT_FOUND`` if the project does not exist, + ``INVALID_ARGUMENT`` if the request is malformed. .. code-block:: python @@ -501,7 +505,7 @@ async def sample_update_policy(): Args: request (Optional[Union[google.cloud.binaryauthorization_v1.types.UpdatePolicyRequest, dict]]): The request object. Request message for - [BinauthzManagementService.UpdatePolicy][]. + [BinauthzManagementServiceV1.UpdatePolicy][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.UpdatePolicy]. policy (:class:`google.cloud.binaryauthorization_v1.types.Policy`): Required. A new or updated [policy][google.cloud.binaryauthorization.v1.Policy] @@ -523,8 +527,8 @@ async def sample_update_policy(): Returns: google.cloud.binaryauthorization_v1.types.Policy: - A [policy][google.cloud.binaryauthorization.v1.Policy] - for container image binary authorization. + A [policy][google.cloud.binaryauthorization.v1.Policy] for container image + binary authorization. """ # Create or coerce a protobuf request object. @@ -593,10 +597,11 @@ async def create_attestor( [attestor][google.cloud.binaryauthorization.v1.Attestor], and returns a copy of the new [attestor][google.cloud.binaryauthorization.v1.Attestor]. - Returns NOT_FOUND if the project does not exist, - INVALID_ARGUMENT if the request is malformed, ALREADY_EXISTS if - the [attestor][google.cloud.binaryauthorization.v1.Attestor] - already exists. + Returns ``NOT_FOUND`` if the project does not exist, + ``INVALID_ARGUMENT`` if the request is malformed, + ``ALREADY_EXISTS`` if the + [attestor][google.cloud.binaryauthorization.v1.Attestor] already + exists. .. code-block:: python @@ -633,7 +638,7 @@ async def sample_create_attestor(): Args: request (Optional[Union[google.cloud.binaryauthorization_v1.types.CreateAttestorRequest, dict]]): The request object. Request message for - [BinauthzManagementService.CreateAttestor][]. + [BinauthzManagementServiceV1.CreateAttestor][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.CreateAttestor]. parent (:class:`str`): Required. The parent of this [attestor][google.cloud.binaryauthorization.v1.Attestor]. @@ -670,9 +675,9 @@ async def sample_create_attestor(): Returns: google.cloud.binaryauthorization_v1.types.Attestor: - An [attestor][google.cloud.binaryauthorization.v1.Attestor] that attests to container image - artifacts. An existing attestor cannot be modified - except where indicated. + An [attestor][google.cloud.binaryauthorization.v1.Attestor] that attests to + container image artifacts. An existing attestor + cannot be modified except where indicated. """ # Create or coerce a protobuf request object. @@ -739,7 +744,7 @@ async def get_attestor( ) -> resources.Attestor: r"""Gets an [attestor][google.cloud.binaryauthorization.v1.Attestor]. - Returns NOT_FOUND if the + Returns ``NOT_FOUND`` if the [attestor][google.cloud.binaryauthorization.v1.Attestor] does not exist. @@ -772,7 +777,7 @@ async def sample_get_attestor(): Args: request (Optional[Union[google.cloud.binaryauthorization_v1.types.GetAttestorRequest, dict]]): The request object. Request message for - [BinauthzManagementService.GetAttestor][]. + [BinauthzManagementServiceV1.GetAttestor][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.GetAttestor]. name (:class:`str`): Required. The name of the [attestor][google.cloud.binaryauthorization.v1.Attestor] @@ -791,9 +796,9 @@ async def sample_get_attestor(): Returns: google.cloud.binaryauthorization_v1.types.Attestor: - An [attestor][google.cloud.binaryauthorization.v1.Attestor] that attests to container image - artifacts. An existing attestor cannot be modified - except where indicated. + An [attestor][google.cloud.binaryauthorization.v1.Attestor] that attests to + container image artifacts. An existing attestor + cannot be modified except where indicated. """ # Create or coerce a protobuf request object. @@ -856,7 +861,7 @@ async def update_attestor( ) -> resources.Attestor: r"""Updates an [attestor][google.cloud.binaryauthorization.v1.Attestor]. - Returns NOT_FOUND if the + Returns ``NOT_FOUND`` if the [attestor][google.cloud.binaryauthorization.v1.Attestor] does not exist. @@ -893,7 +898,7 @@ async def sample_update_attestor(): Args: request (Optional[Union[google.cloud.binaryauthorization_v1.types.UpdateAttestorRequest, dict]]): The request object. Request message for - [BinauthzManagementService.UpdateAttestor][]. + [BinauthzManagementServiceV1.UpdateAttestor][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.UpdateAttestor]. attestor (:class:`google.cloud.binaryauthorization_v1.types.Attestor`): Required. The updated [attestor][google.cloud.binaryauthorization.v1.Attestor] @@ -915,9 +920,9 @@ async def sample_update_attestor(): Returns: google.cloud.binaryauthorization_v1.types.Attestor: - An [attestor][google.cloud.binaryauthorization.v1.Attestor] that attests to container image - artifacts. An existing attestor cannot be modified - except where indicated. + An [attestor][google.cloud.binaryauthorization.v1.Attestor] that attests to + container image artifacts. An existing attestor + cannot be modified except where indicated. """ # Create or coerce a protobuf request object. @@ -981,7 +986,7 @@ async def list_attestors( metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListAttestorsAsyncPager: r"""Lists [attestors][google.cloud.binaryauthorization.v1.Attestor]. - Returns INVALID_ARGUMENT if the project does not exist. + Returns ``INVALID_ARGUMENT`` if the project does not exist. .. code-block:: python @@ -1013,7 +1018,7 @@ async def sample_list_attestors(): Args: request (Optional[Union[google.cloud.binaryauthorization_v1.types.ListAttestorsRequest, dict]]): The request object. Request message for - [BinauthzManagementService.ListAttestors][]. + [BinauthzManagementServiceV1.ListAttestors][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.ListAttestors]. parent (:class:`str`): Required. The resource name of the project associated with the @@ -1034,7 +1039,7 @@ async def sample_list_attestors(): Returns: google.cloud.binaryauthorization_v1.services.binauthz_management_service_v1.pagers.ListAttestorsAsyncPager: Response message for - [BinauthzManagementService.ListAttestors][]. + [BinauthzManagementServiceV1.ListAttestors][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.ListAttestors]. Iterating over this object will yield results and resolve additional pages automatically. @@ -1111,7 +1116,7 @@ async def delete_attestor( ) -> None: r"""Deletes an [attestor][google.cloud.binaryauthorization.v1.Attestor]. - Returns NOT_FOUND if the + Returns ``NOT_FOUND`` if the [attestor][google.cloud.binaryauthorization.v1.Attestor] does not exist. @@ -1141,7 +1146,7 @@ async def sample_delete_attestor(): Args: request (Optional[Union[google.cloud.binaryauthorization_v1.types.DeleteAttestorRequest, dict]]): The request object. Request message for - [BinauthzManagementService.DeleteAttestor][]. + [BinauthzManagementServiceV1.DeleteAttestor][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.DeleteAttestor]. name (:class:`str`): Required. The name of the [attestors][google.cloud.binaryauthorization.v1.Attestor] @@ -1204,6 +1209,329 @@ async def sample_delete_attestor(): metadata=metadata, ) + async def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + 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, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + 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, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def __aenter__(self) -> "BinauthzManagementServiceV1AsyncClient": return self diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/client.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/client.py index bb36f8bac9fb..3e057c32d091 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/client.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/client.py @@ -62,6 +62,10 @@ _LOGGER = std_logging.getLogger(__name__) import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.cloud.binaryauthorization_v1.services.binauthz_management_service_v1 import ( pagers, @@ -813,7 +817,7 @@ def sample_get_policy(): Args: request (Union[google.cloud.binaryauthorization_v1.types.GetPolicyRequest, dict]): The request object. Request message for - [BinauthzManagementService.GetPolicy][]. + [BinauthzManagementServiceV1.GetPolicy][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.GetPolicy]. name (str): Required. The resource name of the [policy][google.cloud.binaryauthorization.v1.Policy] to @@ -832,8 +836,8 @@ def sample_get_policy(): Returns: google.cloud.binaryauthorization_v1.types.Policy: - A [policy][google.cloud.binaryauthorization.v1.Policy] - for container image binary authorization. + A [policy][google.cloud.binaryauthorization.v1.Policy] for container image + binary authorization. """ # Create or coerce a protobuf request object. @@ -897,8 +901,8 @@ def update_policy( [policy][google.cloud.binaryauthorization.v1.Policy]. A policy is always updated as a whole, to avoid race conditions with concurrent policy enforcement (or management!) requests. Returns - NOT_FOUND if the project does not exist, INVALID_ARGUMENT if the - request is malformed. + ``NOT_FOUND`` if the project does not exist, + ``INVALID_ARGUMENT`` if the request is malformed. .. code-block:: python @@ -933,7 +937,7 @@ def sample_update_policy(): Args: request (Union[google.cloud.binaryauthorization_v1.types.UpdatePolicyRequest, dict]): The request object. Request message for - [BinauthzManagementService.UpdatePolicy][]. + [BinauthzManagementServiceV1.UpdatePolicy][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.UpdatePolicy]. policy (google.cloud.binaryauthorization_v1.types.Policy): Required. A new or updated [policy][google.cloud.binaryauthorization.v1.Policy] @@ -955,8 +959,8 @@ def sample_update_policy(): Returns: google.cloud.binaryauthorization_v1.types.Policy: - A [policy][google.cloud.binaryauthorization.v1.Policy] - for container image binary authorization. + A [policy][google.cloud.binaryauthorization.v1.Policy] for container image + binary authorization. """ # Create or coerce a protobuf request object. @@ -1022,10 +1026,11 @@ def create_attestor( [attestor][google.cloud.binaryauthorization.v1.Attestor], and returns a copy of the new [attestor][google.cloud.binaryauthorization.v1.Attestor]. - Returns NOT_FOUND if the project does not exist, - INVALID_ARGUMENT if the request is malformed, ALREADY_EXISTS if - the [attestor][google.cloud.binaryauthorization.v1.Attestor] - already exists. + Returns ``NOT_FOUND`` if the project does not exist, + ``INVALID_ARGUMENT`` if the request is malformed, + ``ALREADY_EXISTS`` if the + [attestor][google.cloud.binaryauthorization.v1.Attestor] already + exists. .. code-block:: python @@ -1062,7 +1067,7 @@ def sample_create_attestor(): Args: request (Union[google.cloud.binaryauthorization_v1.types.CreateAttestorRequest, dict]): The request object. Request message for - [BinauthzManagementService.CreateAttestor][]. + [BinauthzManagementServiceV1.CreateAttestor][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.CreateAttestor]. parent (str): Required. The parent of this [attestor][google.cloud.binaryauthorization.v1.Attestor]. @@ -1099,9 +1104,9 @@ def sample_create_attestor(): Returns: google.cloud.binaryauthorization_v1.types.Attestor: - An [attestor][google.cloud.binaryauthorization.v1.Attestor] that attests to container image - artifacts. An existing attestor cannot be modified - except where indicated. + An [attestor][google.cloud.binaryauthorization.v1.Attestor] that attests to + container image artifacts. An existing attestor + cannot be modified except where indicated. """ # Create or coerce a protobuf request object. @@ -1165,7 +1170,7 @@ def get_attestor( ) -> resources.Attestor: r"""Gets an [attestor][google.cloud.binaryauthorization.v1.Attestor]. - Returns NOT_FOUND if the + Returns ``NOT_FOUND`` if the [attestor][google.cloud.binaryauthorization.v1.Attestor] does not exist. @@ -1198,7 +1203,7 @@ def sample_get_attestor(): Args: request (Union[google.cloud.binaryauthorization_v1.types.GetAttestorRequest, dict]): The request object. Request message for - [BinauthzManagementService.GetAttestor][]. + [BinauthzManagementServiceV1.GetAttestor][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.GetAttestor]. name (str): Required. The name of the [attestor][google.cloud.binaryauthorization.v1.Attestor] @@ -1217,9 +1222,9 @@ def sample_get_attestor(): Returns: google.cloud.binaryauthorization_v1.types.Attestor: - An [attestor][google.cloud.binaryauthorization.v1.Attestor] that attests to container image - artifacts. An existing attestor cannot be modified - except where indicated. + An [attestor][google.cloud.binaryauthorization.v1.Attestor] that attests to + container image artifacts. An existing attestor + cannot be modified except where indicated. """ # Create or coerce a protobuf request object. @@ -1279,7 +1284,7 @@ def update_attestor( ) -> resources.Attestor: r"""Updates an [attestor][google.cloud.binaryauthorization.v1.Attestor]. - Returns NOT_FOUND if the + Returns ``NOT_FOUND`` if the [attestor][google.cloud.binaryauthorization.v1.Attestor] does not exist. @@ -1316,7 +1321,7 @@ def sample_update_attestor(): Args: request (Union[google.cloud.binaryauthorization_v1.types.UpdateAttestorRequest, dict]): The request object. Request message for - [BinauthzManagementService.UpdateAttestor][]. + [BinauthzManagementServiceV1.UpdateAttestor][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.UpdateAttestor]. attestor (google.cloud.binaryauthorization_v1.types.Attestor): Required. The updated [attestor][google.cloud.binaryauthorization.v1.Attestor] @@ -1338,9 +1343,9 @@ def sample_update_attestor(): Returns: google.cloud.binaryauthorization_v1.types.Attestor: - An [attestor][google.cloud.binaryauthorization.v1.Attestor] that attests to container image - artifacts. An existing attestor cannot be modified - except where indicated. + An [attestor][google.cloud.binaryauthorization.v1.Attestor] that attests to + container image artifacts. An existing attestor + cannot be modified except where indicated. """ # Create or coerce a protobuf request object. @@ -1401,7 +1406,7 @@ def list_attestors( metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListAttestorsPager: r"""Lists [attestors][google.cloud.binaryauthorization.v1.Attestor]. - Returns INVALID_ARGUMENT if the project does not exist. + Returns ``INVALID_ARGUMENT`` if the project does not exist. .. code-block:: python @@ -1433,7 +1438,7 @@ def sample_list_attestors(): Args: request (Union[google.cloud.binaryauthorization_v1.types.ListAttestorsRequest, dict]): The request object. Request message for - [BinauthzManagementService.ListAttestors][]. + [BinauthzManagementServiceV1.ListAttestors][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.ListAttestors]. parent (str): Required. The resource name of the project associated with the @@ -1454,7 +1459,7 @@ def sample_list_attestors(): Returns: google.cloud.binaryauthorization_v1.services.binauthz_management_service_v1.pagers.ListAttestorsPager: Response message for - [BinauthzManagementService.ListAttestors][]. + [BinauthzManagementServiceV1.ListAttestors][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.ListAttestors]. Iterating over this object will yield results and resolve additional pages automatically. @@ -1528,7 +1533,7 @@ def delete_attestor( ) -> None: r"""Deletes an [attestor][google.cloud.binaryauthorization.v1.Attestor]. - Returns NOT_FOUND if the + Returns ``NOT_FOUND`` if the [attestor][google.cloud.binaryauthorization.v1.Attestor] does not exist. @@ -1558,7 +1563,7 @@ def sample_delete_attestor(): Args: request (Union[google.cloud.binaryauthorization_v1.types.DeleteAttestorRequest, dict]): The request object. Request message for - [BinauthzManagementService.DeleteAttestor][]. + [BinauthzManagementServiceV1.DeleteAttestor][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.DeleteAttestor]. name (str): Required. The name of the [attestors][google.cloud.binaryauthorization.v1.Attestor] @@ -1631,6 +1636,339 @@ def __exit__(self, type, value, traceback): """ self.transport.close() + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/base.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/base.py index 28ebf2e4f862..bcdeb36cd0f7 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/base.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/base.py @@ -24,6 +24,10 @@ from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.oauth2 import service_account # type: ignore from google.cloud.binaryauthorization_v1 import gapic_version as package_version @@ -238,6 +242,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -311,6 +330,36 @@ def delete_attestor( ]: raise NotImplementedError() + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/grpc.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/grpc.py index 9513b5006d0b..9fa684e4fed5 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/grpc.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/grpc.py @@ -27,6 +27,10 @@ from google.api_core import gapic_v1, grpc_helpers from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.protobuf.json_format import MessageToJson from google.cloud.binaryauthorization_v1.types import resources, service @@ -378,8 +382,8 @@ def update_policy( [policy][google.cloud.binaryauthorization.v1.Policy]. A policy is always updated as a whole, to avoid race conditions with concurrent policy enforcement (or management!) requests. Returns - NOT_FOUND if the project does not exist, INVALID_ARGUMENT if the - request is malformed. + ``NOT_FOUND`` if the project does not exist, + ``INVALID_ARGUMENT`` if the request is malformed. Returns: Callable[[~.UpdatePolicyRequest], @@ -409,10 +413,11 @@ def create_attestor( [attestor][google.cloud.binaryauthorization.v1.Attestor], and returns a copy of the new [attestor][google.cloud.binaryauthorization.v1.Attestor]. - Returns NOT_FOUND if the project does not exist, - INVALID_ARGUMENT if the request is malformed, ALREADY_EXISTS if - the [attestor][google.cloud.binaryauthorization.v1.Attestor] - already exists. + Returns ``NOT_FOUND`` if the project does not exist, + ``INVALID_ARGUMENT`` if the request is malformed, + ``ALREADY_EXISTS`` if the + [attestor][google.cloud.binaryauthorization.v1.Attestor] already + exists. Returns: Callable[[~.CreateAttestorRequest], @@ -440,7 +445,7 @@ def get_attestor( Gets an [attestor][google.cloud.binaryauthorization.v1.Attestor]. - Returns NOT_FOUND if the + Returns ``NOT_FOUND`` if the [attestor][google.cloud.binaryauthorization.v1.Attestor] does not exist. @@ -470,7 +475,7 @@ def update_attestor( Updates an [attestor][google.cloud.binaryauthorization.v1.Attestor]. - Returns NOT_FOUND if the + Returns ``NOT_FOUND`` if the [attestor][google.cloud.binaryauthorization.v1.Attestor] does not exist. @@ -499,7 +504,7 @@ def list_attestors( r"""Return a callable for the list attestors method over gRPC. Lists [attestors][google.cloud.binaryauthorization.v1.Attestor]. - Returns INVALID_ARGUMENT if the project does not exist. + Returns ``INVALID_ARGUMENT`` if the project does not exist. Returns: Callable[[~.ListAttestorsRequest], @@ -527,7 +532,7 @@ def delete_attestor( Deletes an [attestor][google.cloud.binaryauthorization.v1.Attestor]. - Returns NOT_FOUND if the + Returns ``NOT_FOUND`` if the [attestor][google.cloud.binaryauthorization.v1.Attestor] does not exist. @@ -552,6 +557,86 @@ def delete_attestor( def close(self): self._logged_channel.close() + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + @property def kind(self) -> str: return "grpc" diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/grpc_asyncio.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/grpc_asyncio.py index f51aeda2d96f..303d3af194a8 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/grpc_asyncio.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/grpc_asyncio.py @@ -29,6 +29,10 @@ from google.api_core import retry_async as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.protobuf.json_format import MessageToJson from grpc.experimental import aio # type: ignore @@ -390,8 +394,8 @@ def update_policy( [policy][google.cloud.binaryauthorization.v1.Policy]. A policy is always updated as a whole, to avoid race conditions with concurrent policy enforcement (or management!) requests. Returns - NOT_FOUND if the project does not exist, INVALID_ARGUMENT if the - request is malformed. + ``NOT_FOUND`` if the project does not exist, + ``INVALID_ARGUMENT`` if the request is malformed. Returns: Callable[[~.UpdatePolicyRequest], @@ -421,10 +425,11 @@ def create_attestor( [attestor][google.cloud.binaryauthorization.v1.Attestor], and returns a copy of the new [attestor][google.cloud.binaryauthorization.v1.Attestor]. - Returns NOT_FOUND if the project does not exist, - INVALID_ARGUMENT if the request is malformed, ALREADY_EXISTS if - the [attestor][google.cloud.binaryauthorization.v1.Attestor] - already exists. + Returns ``NOT_FOUND`` if the project does not exist, + ``INVALID_ARGUMENT`` if the request is malformed, + ``ALREADY_EXISTS`` if the + [attestor][google.cloud.binaryauthorization.v1.Attestor] already + exists. Returns: Callable[[~.CreateAttestorRequest], @@ -452,7 +457,7 @@ def get_attestor( Gets an [attestor][google.cloud.binaryauthorization.v1.Attestor]. - Returns NOT_FOUND if the + Returns ``NOT_FOUND`` if the [attestor][google.cloud.binaryauthorization.v1.Attestor] does not exist. @@ -482,7 +487,7 @@ def update_attestor( Updates an [attestor][google.cloud.binaryauthorization.v1.Attestor]. - Returns NOT_FOUND if the + Returns ``NOT_FOUND`` if the [attestor][google.cloud.binaryauthorization.v1.Attestor] does not exist. @@ -513,7 +518,7 @@ def list_attestors( r"""Return a callable for the list attestors method over gRPC. Lists [attestors][google.cloud.binaryauthorization.v1.Attestor]. - Returns INVALID_ARGUMENT if the project does not exist. + Returns ``INVALID_ARGUMENT`` if the project does not exist. Returns: Callable[[~.ListAttestorsRequest], @@ -541,7 +546,7 @@ def delete_attestor( Deletes an [attestor][google.cloud.binaryauthorization.v1.Attestor]. - Returns NOT_FOUND if the + Returns ``NOT_FOUND`` if the [attestor][google.cloud.binaryauthorization.v1.Attestor] does not exist. @@ -661,6 +666,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), } def _wrap_method(self, func, *args, **kwargs): @@ -675,5 +695,85 @@ def close(self): def kind(self) -> str: return "grpc_asyncio" + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + __all__ = ("BinauthzManagementServiceV1GrpcAsyncIOTransport",) diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/rest.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/rest.py index 2cb333187d5f..8f885e76110c 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/rest.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/rest.py @@ -26,6 +26,10 @@ from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.protobuf import json_format from requests import __version__ as requests_version @@ -409,6 +413,78 @@ def post_update_policy_with_metadata( """ return response, metadata + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BinauthzManagementServiceV1 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 BinauthzManagementServiceV1 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, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BinauthzManagementServiceV1 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 BinauthzManagementServiceV1 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, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the BinauthzManagementServiceV1 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 BinauthzManagementServiceV1 server but before + it is returned to user code. + """ + return response + @dataclasses.dataclass class BinauthzManagementServiceV1RestStub: @@ -554,7 +630,7 @@ def __call__( Args: request (~.service.CreateAttestorRequest): The request object. Request message for - [BinauthzManagementService.CreateAttestor][]. + [BinauthzManagementServiceV1.CreateAttestor][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.CreateAttestor]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -709,7 +785,7 @@ def __call__( Args: request (~.service.DeleteAttestorRequest): The request object. Request message for - [BinauthzManagementService.DeleteAttestor][]. + [BinauthzManagementServiceV1.DeleteAttestor][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.DeleteAttestor]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -817,7 +893,7 @@ def __call__( Args: request (~.service.GetAttestorRequest): The request object. Request message for - [BinauthzManagementService.GetAttestor][]. + [BinauthzManagementServiceV1.GetAttestor][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.GetAttestor]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -967,7 +1043,7 @@ def __call__( Args: request (~.service.GetPolicyRequest): The request object. Request message for - [BinauthzManagementService.GetPolicy][]. + [BinauthzManagementServiceV1.GetPolicy][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.GetPolicy]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1115,7 +1191,7 @@ def __call__( Args: request (~.service.ListAttestorsRequest): The request object. Request message for - [BinauthzManagementService.ListAttestors][]. + [BinauthzManagementServiceV1.ListAttestors][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.ListAttestors]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1127,7 +1203,7 @@ def __call__( Returns: ~.service.ListAttestorsResponse: Response message for - [BinauthzManagementService.ListAttestors][]. + [BinauthzManagementServiceV1.ListAttestors][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.ListAttestors]. """ @@ -1264,7 +1340,7 @@ def __call__( Args: request (~.service.UpdateAttestorRequest): The request object. Request message for - [BinauthzManagementService.UpdateAttestor][]. + [BinauthzManagementServiceV1.UpdateAttestor][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.UpdateAttestor]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1420,7 +1496,7 @@ def __call__( Args: request (~.service.UpdatePolicyRequest): The request object. Request message for - [BinauthzManagementService.UpdatePolicy][]. + [BinauthzManagementServiceV1.UpdatePolicy][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.UpdatePolicy]. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1585,6 +1661,441 @@ def update_policy( # In C++ this would require a dynamic_cast return self._UpdatePolicy(self._session, self._host, self._interceptor) # type: ignore + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy( + _BaseBinauthzManagementServiceV1RestTransport._BaseGetIamPolicy, + BinauthzManagementServiceV1RestStub, + ): + def __hash__(self): + return hash("BinauthzManagementServiceV1RestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseBinauthzManagementServiceV1RestTransport._BaseGetIamPolicy._get_http_options() + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseBinauthzManagementServiceV1RestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseBinauthzManagementServiceV1RestTransport._BaseGetIamPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.binaryauthorization_v1.BinauthzManagementServiceV1Client.GetIamPolicy", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BinauthzManagementServiceV1RestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.binaryauthorization_v1.BinauthzManagementServiceV1AsyncClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy( + _BaseBinauthzManagementServiceV1RestTransport._BaseSetIamPolicy, + BinauthzManagementServiceV1RestStub, + ): + def __hash__(self): + return hash("BinauthzManagementServiceV1RestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseBinauthzManagementServiceV1RestTransport._BaseSetIamPolicy._get_http_options() + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseBinauthzManagementServiceV1RestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) + + body = _BaseBinauthzManagementServiceV1RestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseBinauthzManagementServiceV1RestTransport._BaseSetIamPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.binaryauthorization_v1.BinauthzManagementServiceV1Client.SetIamPolicy", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BinauthzManagementServiceV1RestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.binaryauthorization_v1.BinauthzManagementServiceV1AsyncClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions( + _BaseBinauthzManagementServiceV1RestTransport._BaseTestIamPermissions, + BinauthzManagementServiceV1RestStub, + ): + def __hash__(self): + return hash("BinauthzManagementServiceV1RestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseBinauthzManagementServiceV1RestTransport._BaseTestIamPermissions._get_http_options() + + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + transcoded_request = _BaseBinauthzManagementServiceV1RestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) + + body = _BaseBinauthzManagementServiceV1RestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseBinauthzManagementServiceV1RestTransport._BaseTestIamPermissions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.binaryauthorization_v1.BinauthzManagementServiceV1Client.TestIamPermissions", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BinauthzManagementServiceV1RestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.binaryauthorization_v1.BinauthzManagementServiceV1AsyncClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + @property def kind(self) -> str: return "rest" diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/rest_base.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/rest_base.py index 1134c164dd91..d754c0f5ea1c 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/rest_base.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/binauthz_management_service_v1/transports/rest_base.py @@ -19,6 +19,10 @@ import google.protobuf.empty_pb2 as empty_pb2 # type: ignore from google.api_core import gapic_v1, path_template +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.protobuf import json_format from google.cloud.binaryauthorization_v1.types import resources, service @@ -451,5 +455,106 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{resource=projects/*/policy}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/attestors/*}:getIamPolicy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/policy}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/attestors/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/policy}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/attestors/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + __all__ = ("_BaseBinauthzManagementServiceV1RestTransport",) diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/async_client.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/async_client.py index 840c0dccbbae..e049513aed06 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/async_client.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/async_client.py @@ -45,6 +45,10 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.cloud.binaryauthorization_v1.types import resources, service @@ -354,8 +358,8 @@ async def sample_get_system_policy(): Returns: google.cloud.binaryauthorization_v1.types.Policy: - A [policy][google.cloud.binaryauthorization.v1.Policy] - for container image binary authorization. + A [policy][google.cloud.binaryauthorization.v1.Policy] for container image + binary authorization. """ # Create or coerce a protobuf request object. @@ -407,6 +411,329 @@ async def sample_get_system_policy(): # Done; return the response. return response + async def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + 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, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + 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, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def __aenter__(self) -> "SystemPolicyV1AsyncClient": return self diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/client.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/client.py index a91b9b515cb7..2d166f0e3602 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/client.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/client.py @@ -62,6 +62,10 @@ _LOGGER = std_logging.getLogger(__name__) import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.cloud.binaryauthorization_v1.types import resources, service @@ -781,8 +785,8 @@ def sample_get_system_policy(): Returns: google.cloud.binaryauthorization_v1.types.Policy: - A [policy][google.cloud.binaryauthorization.v1.Policy] - for container image binary authorization. + A [policy][google.cloud.binaryauthorization.v1.Policy] for container image + binary authorization. """ # Create or coerce a protobuf request object. @@ -844,6 +848,339 @@ def __exit__(self, type, value, traceback): """ self.transport.close() + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/base.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/base.py index d55ecdda8c40..04f1de638e6f 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/base.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/base.py @@ -23,6 +23,10 @@ from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.oauth2 import service_account # type: ignore from google.cloud.binaryauthorization_v1 import gapic_version as package_version @@ -147,6 +151,21 @@ def _prep_wrapped_messages(self, client_info): 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.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -167,6 +186,36 @@ def get_system_policy( ]: raise NotImplementedError() + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/grpc.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/grpc.py index 9f37ba7d605e..25dfa8ff68bc 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/grpc.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/grpc.py @@ -26,6 +26,10 @@ from google.api_core import gapic_v1, grpc_helpers from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.protobuf.json_format import MessageToJson from google.cloud.binaryauthorization_v1.types import resources, service @@ -355,6 +359,86 @@ def get_system_policy( def close(self): self._logged_channel.close() + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + @property def kind(self) -> str: return "grpc" diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/grpc_asyncio.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/grpc_asyncio.py index e53f18847693..1a400fdb20b5 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/grpc_asyncio.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/grpc_asyncio.py @@ -28,6 +28,10 @@ from google.api_core import retry_async as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.protobuf.json_format import MessageToJson from grpc.experimental import aio # type: ignore @@ -368,6 +372,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), } def _wrap_method(self, func, *args, **kwargs): @@ -382,5 +401,85 @@ def close(self): def kind(self) -> str: return "grpc_asyncio" + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + __all__ = ("SystemPolicyV1GrpcAsyncIOTransport",) diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/rest.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/rest.py index 7dbed3d73b11..f88d6ec03861 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/rest.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/rest.py @@ -25,6 +25,10 @@ from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.protobuf import json_format from requests import __version__ as requests_version @@ -130,6 +134,78 @@ def post_get_system_policy_with_metadata( """ return response, metadata + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the SystemPolicyV1 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 SystemPolicyV1 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, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the SystemPolicyV1 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 SystemPolicyV1 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, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the SystemPolicyV1 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 SystemPolicyV1 server but before + it is returned to user code. + """ + return response + @dataclasses.dataclass class SystemPolicyV1RestStub: @@ -379,6 +455,438 @@ def get_system_policy( # In C++ this would require a dynamic_cast return self._GetSystemPolicy(self._session, self._host, self._interceptor) # type: ignore + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy( + _BaseSystemPolicyV1RestTransport._BaseGetIamPolicy, SystemPolicyV1RestStub + ): + def __hash__(self): + return hash("SystemPolicyV1RestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = ( + _BaseSystemPolicyV1RestTransport._BaseGetIamPolicy._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseSystemPolicyV1RestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSystemPolicyV1RestTransport._BaseGetIamPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.binaryauthorization_v1.SystemPolicyV1Client.GetIamPolicy", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1.SystemPolicyV1", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SystemPolicyV1RestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.binaryauthorization_v1.SystemPolicyV1AsyncClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1.SystemPolicyV1", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy( + _BaseSystemPolicyV1RestTransport._BaseSetIamPolicy, SystemPolicyV1RestStub + ): + def __hash__(self): + return hash("SystemPolicyV1RestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = ( + _BaseSystemPolicyV1RestTransport._BaseSetIamPolicy._get_http_options() + ) + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseSystemPolicyV1RestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) + + body = _BaseSystemPolicyV1RestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSystemPolicyV1RestTransport._BaseSetIamPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.binaryauthorization_v1.SystemPolicyV1Client.SetIamPolicy", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1.SystemPolicyV1", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SystemPolicyV1RestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.binaryauthorization_v1.SystemPolicyV1AsyncClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1.SystemPolicyV1", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions( + _BaseSystemPolicyV1RestTransport._BaseTestIamPermissions, SystemPolicyV1RestStub + ): + def __hash__(self): + return hash("SystemPolicyV1RestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseSystemPolicyV1RestTransport._BaseTestIamPermissions._get_http_options() + + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + transcoded_request = _BaseSystemPolicyV1RestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) + + body = _BaseSystemPolicyV1RestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSystemPolicyV1RestTransport._BaseTestIamPermissions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.binaryauthorization_v1.SystemPolicyV1Client.TestIamPermissions", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1.SystemPolicyV1", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SystemPolicyV1RestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.binaryauthorization_v1.SystemPolicyV1AsyncClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1.SystemPolicyV1", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + @property def kind(self) -> str: return "rest" diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/rest_base.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/rest_base.py index ee8cf77bfb1a..d78db543e5a9 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/rest_base.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/system_policy_v1/transports/rest_base.py @@ -18,6 +18,10 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1, path_template +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.protobuf import json_format from google.cloud.binaryauthorization_v1.types import resources, service @@ -134,5 +138,106 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{resource=projects/*/policy}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/attestors/*}:getIamPolicy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/policy}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/attestors/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/policy}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/attestors/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + __all__ = ("_BaseSystemPolicyV1RestTransport",) diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/async_client.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/async_client.py index a24e93c409af..4f9b3a13d8f4 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/async_client.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/async_client.py @@ -44,6 +44,11 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) + from google.cloud.binaryauthorization_v1.types import service from .client import ValidationHelperV1Client @@ -306,8 +311,8 @@ async def validate_attestation_occurrence( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> service.ValidateAttestationOccurrenceResponse: - r"""Returns whether the given Attestation for the given - image URI was signed by the given Attestor + r"""Returns whether the given ``Attestation`` for the given image + URI was signed by the given ``Attestor`` .. code-block:: python @@ -387,6 +392,329 @@ async def sample_validate_attestation_occurrence(): # Done; return the response. return response + async def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + 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, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + 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, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def __aenter__(self) -> "ValidationHelperV1AsyncClient": return self diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/client.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/client.py index 2c179ffe98de..32373eed8ba5 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/client.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/client.py @@ -61,6 +61,11 @@ _LOGGER = std_logging.getLogger(__name__) +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) + from google.cloud.binaryauthorization_v1.types import service from .transports.base import DEFAULT_CLIENT_INFO, ValidationHelperV1Transport @@ -719,8 +724,8 @@ def validate_attestation_occurrence( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> service.ValidateAttestationOccurrenceResponse: - r"""Returns whether the given Attestation for the given - image URI was signed by the given Attestor + r"""Returns whether the given ``Attestation`` for the given image + URI was signed by the given ``Attestor`` .. code-block:: python @@ -813,6 +818,339 @@ def __exit__(self, type, value, traceback): """ self.transport.close() + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/base.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/base.py index fecf21f62026..78742ac580a7 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/base.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/base.py @@ -23,6 +23,10 @@ from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.oauth2 import service_account # type: ignore from google.cloud.binaryauthorization_v1 import gapic_version as package_version @@ -147,6 +151,21 @@ def _prep_wrapped_messages(self, client_info): 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.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -170,6 +189,36 @@ def validate_attestation_occurrence( ]: raise NotImplementedError() + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/grpc.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/grpc.py index bc94664e6278..b59bf62516eb 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/grpc.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/grpc.py @@ -26,6 +26,10 @@ from google.api_core import gapic_v1, grpc_helpers from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.protobuf.json_format import MessageToJson from google.cloud.binaryauthorization_v1.types import service @@ -335,8 +339,8 @@ def validate_attestation_occurrence( r"""Return a callable for the validate attestation occurrence method over gRPC. - Returns whether the given Attestation for the given - image URI was signed by the given Attestor + Returns whether the given ``Attestation`` for the given image + URI was signed by the given ``Attestor`` Returns: Callable[[~.ValidateAttestationOccurrenceRequest], @@ -361,6 +365,86 @@ def validate_attestation_occurrence( def close(self): self._logged_channel.close() + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + @property def kind(self) -> str: return "grpc" diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/grpc_asyncio.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/grpc_asyncio.py index 8c873d94b89f..5cbac703f955 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/grpc_asyncio.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/grpc_asyncio.py @@ -28,6 +28,10 @@ from google.api_core import retry_async as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.protobuf.json_format import MessageToJson from grpc.experimental import aio # type: ignore @@ -343,8 +347,8 @@ def validate_attestation_occurrence( r"""Return a callable for the validate attestation occurrence method over gRPC. - Returns whether the given Attestation for the given - image URI was signed by the given Attestor + Returns whether the given ``Attestation`` for the given image + URI was signed by the given ``Attestor`` Returns: Callable[[~.ValidateAttestationOccurrenceRequest], @@ -374,6 +378,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), } def _wrap_method(self, func, *args, **kwargs): @@ -388,5 +407,85 @@ def close(self): def kind(self) -> str: return "grpc_asyncio" + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + __all__ = ("ValidationHelperV1GrpcAsyncIOTransport",) diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/rest.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/rest.py index 77f2f6616f4a..51e2d5440259 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/rest.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/rest.py @@ -25,6 +25,10 @@ from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.protobuf import json_format from requests import __version__ as requests_version @@ -138,6 +142,78 @@ def post_validate_attestation_occurrence_with_metadata( """ return response, metadata + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the ValidationHelperV1 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 ValidationHelperV1 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, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the ValidationHelperV1 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 ValidationHelperV1 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, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the ValidationHelperV1 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 ValidationHelperV1 server but before + it is returned to user code. + """ + return response + @dataclasses.dataclass class ValidationHelperV1RestStub: @@ -404,6 +480,439 @@ def validate_attestation_occurrence( self._session, self._host, self._interceptor ) # type: ignore + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy( + _BaseValidationHelperV1RestTransport._BaseGetIamPolicy, + ValidationHelperV1RestStub, + ): + def __hash__(self): + return hash("ValidationHelperV1RestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseValidationHelperV1RestTransport._BaseGetIamPolicy._get_http_options() + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseValidationHelperV1RestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseValidationHelperV1RestTransport._BaseGetIamPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.binaryauthorization_v1.ValidationHelperV1Client.GetIamPolicy", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1.ValidationHelperV1", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ValidationHelperV1RestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.binaryauthorization_v1.ValidationHelperV1AsyncClient.GetIamPolicy", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1.ValidationHelperV1", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy( + _BaseValidationHelperV1RestTransport._BaseSetIamPolicy, + ValidationHelperV1RestStub, + ): + def __hash__(self): + return hash("ValidationHelperV1RestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseValidationHelperV1RestTransport._BaseSetIamPolicy._get_http_options() + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseValidationHelperV1RestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) + + body = _BaseValidationHelperV1RestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseValidationHelperV1RestTransport._BaseSetIamPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.binaryauthorization_v1.ValidationHelperV1Client.SetIamPolicy", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1.ValidationHelperV1", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ValidationHelperV1RestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.binaryauthorization_v1.ValidationHelperV1AsyncClient.SetIamPolicy", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1.ValidationHelperV1", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions( + _BaseValidationHelperV1RestTransport._BaseTestIamPermissions, + ValidationHelperV1RestStub, + ): + def __hash__(self): + return hash("ValidationHelperV1RestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseValidationHelperV1RestTransport._BaseTestIamPermissions._get_http_options() + + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + transcoded_request = _BaseValidationHelperV1RestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) + + body = _BaseValidationHelperV1RestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseValidationHelperV1RestTransport._BaseTestIamPermissions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.binaryauthorization_v1.ValidationHelperV1Client.TestIamPermissions", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1.ValidationHelperV1", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + ValidationHelperV1RestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.binaryauthorization_v1.ValidationHelperV1AsyncClient.TestIamPermissions", + extra={ + "serviceName": "google.cloud.binaryauthorization.v1.ValidationHelperV1", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + @property def kind(self) -> str: return "rest" diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/rest_base.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/rest_base.py index df1803c2a051..8d0cd64c4a4c 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/rest_base.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/services/validation_helper_v1/transports/rest_base.py @@ -18,6 +18,10 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1, path_template +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.protobuf import json_format from google.cloud.binaryauthorization_v1.types import service @@ -144,5 +148,106 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{resource=projects/*/policy}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/attestors/*}:getIamPolicy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/policy}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/attestors/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/policy}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/attestors/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + __all__ = ("_BaseValidationHelperV1RestTransport",) diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/types/resources.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/types/resources.py index 170c74f24d93..eac7b076f13d 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/types/resources.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/types/resources.py @@ -60,7 +60,13 @@ class Policy(proto.Message): exclude Google or third-party infrastructure images from Binary Authorization policies. cluster_admission_rules (MutableMapping[str, google.cloud.binaryauthorization_v1.types.AdmissionRule]): - Optional. Per-cluster admission rules. Cluster spec format: + Optional. A valid policy has only one of the following rule + maps non-empty, i.e. only one of + ``cluster_admission_rules``, + ``kubernetes_namespace_admission_rules``, + ``kubernetes_service_account_admission_rules``, or + ``istio_service_identity_admission_rules`` can be non-empty. + Per-cluster admission rules. Cluster spec format: ``location.clusterId``. There can be at most one admission rule per cluster spec. A ``location`` is either a compute zone (e.g. us-central1-a) or a region (e.g. us-central1). @@ -68,19 +74,17 @@ class Policy(proto.Message): https://cloud.google.com/container-engine/reference/rest/v1/projects.zones.clusters. kubernetes_namespace_admission_rules (MutableMapping[str, google.cloud.binaryauthorization_v1.types.AdmissionRule]): Optional. Per-kubernetes-namespace admission rules. K8s - namespace spec format: [a-z.-]+, e.g. 'some-namespace' + namespace spec format: ``[a-z.-]+``, e.g. ``some-namespace`` kubernetes_service_account_admission_rules (MutableMapping[str, google.cloud.binaryauthorization_v1.types.AdmissionRule]): Optional. Per-kubernetes-service-account admission rules. Service account spec format: ``namespace:serviceaccount``. - e.g. 'test-ns:default' + e.g. ``test-ns:default`` istio_service_identity_admission_rules (MutableMapping[str, google.cloud.binaryauthorization_v1.types.AdmissionRule]): - Optional. Per-istio-service-identity - admission rules. Istio service identity spec - format: - - spiffe:///ns//sa/ - or /ns//sa/ - e.g. spiffe://example.com/ns/test-ns/sa/default + Optional. Per-istio-service-identity admission rules. Istio + service identity spec format: + ``spiffe:///ns//sa/`` or + ``/ns//sa/`` e.g. + ``spiffe://example.com/ns/test-ns/sa/default`` default_admission_rule (google.cloud.binaryauthorization_v1.types.AdmissionRule): Required. Default admission rule for a cluster without a per-cluster, per- @@ -89,6 +93,12 @@ class Policy(proto.Message): update_time (google.protobuf.timestamp_pb2.Timestamp): Output only. Time when the policy was last updated. + etag (str): + Optional. A checksum, returned by the server, + that can be sent on update requests to ensure + the policy has an up-to-date value before + attempting to update it. See + https://google.aip.dev/154. """ class GlobalPolicyEvaluationMode(proto.Enum): @@ -96,7 +106,7 @@ class GlobalPolicyEvaluationMode(proto.Enum): Values: GLOBAL_POLICY_EVALUATION_MODE_UNSPECIFIED (0): - Not specified: DISABLE is assumed. + Not specified: ``DISABLE`` is assumed. ENABLE (1): Enables system policy evaluation. DISABLE (2): @@ -167,6 +177,10 @@ class GlobalPolicyEvaluationMode(proto.Enum): number=5, message=timestamp_pb2.Timestamp, ) + etag: str = proto.Field( + proto.STRING, + number=11, + ) class AdmissionWhitelistPattern(proto.Message): @@ -216,9 +230,9 @@ class AdmissionRule(proto.Message): the principal issuing the policy change request must be able to read the attestor resource. - Note: this field must be non-empty when the evaluation_mode - field specifies REQUIRE_ATTESTATION, otherwise it must be - empty. + Note: this field must be non-empty when the + ``evaluation_mode`` field specifies ``REQUIRE_ATTESTATION``, + otherwise it must be empty. enforcement_mode (google.cloud.binaryauthorization_v1.types.AdmissionRule.EnforcementMode): Required. The action when a pod creation is denied by the admission rule. @@ -231,11 +245,11 @@ class EvaluationMode(proto.Enum): EVALUATION_MODE_UNSPECIFIED (0): Do not use. ALWAYS_ALLOW (1): - This rule allows all all pod creations. + This rule allows all pod creations. REQUIRE_ATTESTATION (2): This rule allows a pod creation if all the attestors listed - in 'require_attestations_by' have valid attestations for all - of the images in the pod spec. + in ``require_attestations_by`` have valid attestations for + all of the images in the pod spec. ALWAYS_DENY (3): This rule denies all pod creations. """ @@ -306,6 +320,12 @@ class Attestor(proto.Message): update_time (google.protobuf.timestamp_pb2.Timestamp): Output only. Time when the attestor was last updated. + etag (str): + Optional. A checksum, returned by the server, + that can be sent on update requests to ensure + the attestor has an up-to-date value before + attempting to update it. See + https://google.aip.dev/154. """ name: str = proto.Field( @@ -327,6 +347,10 @@ class Attestor(proto.Message): number=4, message=timestamp_pb2.Timestamp, ) + etag: str = proto.Field( + proto.STRING, + number=7, + ) class UserOwnedGrafeasNote(proto.Message): @@ -338,8 +362,9 @@ class UserOwnedGrafeasNote(proto.Message): note_reference (str): Required. The Grafeas resource name of a Attestation.Authority Note, created by the user, in the - format: ``projects/*/notes/*``. This field may not be - updated. + format: ``projects/[PROJECT_ID]/notes/*``. This field may + not be updated. A project ID must be used, not a project + number. An attestation by this attestor is stored as a Grafeas Attestation.Authority Occurrence that names a container @@ -359,14 +384,16 @@ class UserOwnedGrafeasNote(proto.Message): returns that no valid attestations exist. delegation_service_account_email (str): Output only. This field will contain the service account - email address that this Attestor will use as the principal + email address that this attestor will use as the principal when querying Container Analysis. Attestor administrators must grant this service account the IAM role needed to read - attestations from the [note_reference][Note] in Container - Analysis (``containeranalysis.notes.occurrences.viewer``). + attestations from the + [note_reference][google.cloud.binaryauthorization.v1.UserOwnedGrafeasNote.note_reference] + in Container Analysis + (``containeranalysis.notes.occurrences.viewer``). This email address is fixed for the lifetime of the - Attestor, but callers should not make any other assumptions + attestor, but callers should not make any other assumptions about the service account email; future versions may use an email based on a different naming pattern. """ @@ -387,10 +414,10 @@ class UserOwnedGrafeasNote(proto.Message): class PkixPublicKey(proto.Message): - r"""A public key in the PkixPublicKey format (see - https://tools.ietf.org/html/rfc5280#section-4.1.2.7 for - details). Public keys of this type are typically textually - encoded using the PEM format. + r"""A public key in the PkixPublicKey + `format `__. + Public keys of this type are typically textually encoded using the + PEM format. Attributes: public_key_pem (str): @@ -402,28 +429,53 @@ class PkixPublicKey(proto.Message): match the structure and any object identifiers encoded in ``public_key_pem`` (i.e. this algorithm must match that of the public key). + key_id (str): + Optional. The ID of this public key. Signatures verified by + Binary Authorization must include the ID of the public key + that can be used to verify them. The ID must match exactly + contents of the ``key_id`` field exactly. + + The ID may be explicitly provided by the caller, but it MUST + be a valid RFC3986 URI. If ``key_id`` is left blank and this + ``PkixPublicKey`` is not used in the context of a wrapper + (see next paragraph), a default key ID will be computed + based on the digest of the DER encoding of the public key. + + If this ``PkixPublicKey`` is used in the context of a + wrapper that has its own notion of key ID (e.g. + ``AttestorPublicKey``), then this field can either match + that value exactly, or be left blank, in which case it + behaves exactly as though it is equal to that wrapper value. """ class SignatureAlgorithm(proto.Enum): - r"""Represents a signature algorithm and other information - necessary to verify signatures with a given public key. This is - based primarily on the public key types supported by Tink's - PemKeyType, which is in turn based on KMS's supported signing - algorithms. See https://cloud.google.com/kms/docs/algorithms. In - the future, BinAuthz might support additional public key types - independently of Tink and/or KMS. + r"""Represents a signature algorithm and other information necessary to + verify signatures with a given public key. This is based primarily + on the public key types supported by Tink's PemKeyType, which is in + turn based on KMS's supported signing + `algorithms `__. In + the future, Binary Authorization might support additional public key + types independently of Tink and/or KMS. Values: SIGNATURE_ALGORITHM_UNSPECIFIED (0): Not specified. RSA_PSS_2048_SHA256 (1): RSASSA-PSS 2048 bit key with a SHA256 digest. + RSA_SIGN_PSS_2048_SHA256 (1): + RSASSA-PSS 2048 bit key with a SHA256 digest. RSA_PSS_3072_SHA256 (2): RSASSA-PSS 3072 bit key with a SHA256 digest. + RSA_SIGN_PSS_3072_SHA256 (2): + RSASSA-PSS 3072 bit key with a SHA256 digest. RSA_PSS_4096_SHA256 (3): RSASSA-PSS 4096 bit key with a SHA256 digest. + RSA_SIGN_PSS_4096_SHA256 (3): + RSASSA-PSS 4096 bit key with a SHA256 digest. RSA_PSS_4096_SHA512 (4): RSASSA-PSS 4096 bit key with a SHA512 digest. + RSA_SIGN_PSS_4096_SHA512 (4): + RSASSA-PSS 4096 bit key with a SHA512 digest. RSA_SIGN_PKCS1_2048_SHA256 (5): RSASSA-PKCS1-v1_5 with a 2048 bit key and a SHA256 digest. RSA_SIGN_PKCS1_3072_SHA256 (6): @@ -450,14 +502,21 @@ class SignatureAlgorithm(proto.Enum): EC_SIGN_P521_SHA512 (11): ECDSA on the NIST P-521 curve with a SHA512 digest. + ML_DSA_65 (13): + ML-DSA-65 Post-Quantum Cryptography signature + algorithm. """ _pb_options = {"allow_alias": True} SIGNATURE_ALGORITHM_UNSPECIFIED = 0 RSA_PSS_2048_SHA256 = 1 + RSA_SIGN_PSS_2048_SHA256 = 1 RSA_PSS_3072_SHA256 = 2 + RSA_SIGN_PSS_3072_SHA256 = 2 RSA_PSS_4096_SHA256 = 3 + RSA_SIGN_PSS_4096_SHA256 = 3 RSA_PSS_4096_SHA512 = 4 + RSA_SIGN_PSS_4096_SHA512 = 4 RSA_SIGN_PKCS1_2048_SHA256 = 5 RSA_SIGN_PKCS1_3072_SHA256 = 6 RSA_SIGN_PKCS1_4096_SHA256 = 7 @@ -468,6 +527,7 @@ class SignatureAlgorithm(proto.Enum): EC_SIGN_P384_SHA384 = 10 ECDSA_P521_SHA512 = 11 EC_SIGN_P521_SHA512 = 11 + ML_DSA_65 = 13 public_key_pem: str = proto.Field( proto.STRING, @@ -478,6 +538,10 @@ class SignatureAlgorithm(proto.Enum): number=2, enum=SignatureAlgorithm, ) + key_id: str = proto.Field( + proto.STRING, + number=3, + ) class AttestorPublicKey(proto.Message): @@ -497,22 +561,23 @@ class AttestorPublicKey(proto.Message): Optional. A descriptive comment. This field may be updated. id (str): - The ID of this public key. Signatures verified by BinAuthz - must include the ID of the public key that can be used to - verify them, and that ID must match the contents of this - field exactly. Additional restrictions on this field can be - imposed based on which public key type is encapsulated. See - the documentation on ``public_key`` cases below for details. + The ID of this public key. Signatures verified by Binary + Authorization must include the ID of the public key that can + be used to verify them, and that ID must match the contents + of this field exactly. Additional restrictions on this field + can be imposed based on which public key type is + encapsulated. See the documentation on ``public_key`` cases + below for details. ascii_armored_pgp_public_key (str): ASCII-armored representation of a PGP public key, as the entire output by the command ``gpg --export --armor foo@example.com`` (either LF or CRLF line endings). When using this field, ``id`` should be left - blank. The BinAuthz API handlers will calculate the ID and - fill it in automatically. BinAuthz computes this ID as the - OpenPGP RFC4880 V4 fingerprint, represented as upper-case - hex. If ``id`` is provided by the caller, it will be - overwritten by the API-calculated ID. + blank. The Binary Authorization API handlers will calculate + the ID and fill it in automatically. Binary Authorization + computes this ID as the OpenPGP RFC4880 V4 fingerprint, + represented as upper-case hex. If ``id`` is provided by the + caller, it will be overwritten by the API-calculated ID. This field is a member of `oneof`_ ``public_key``. pkix_public_key (google.cloud.binaryauthorization_v1.types.PkixPublicKey): diff --git a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/types/service.py b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/types/service.py index c059db1f3e48..ca94c9de1411 100644 --- a/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/types/service.py +++ b/packages/google-cloud-binary-authorization/google/cloud/binaryauthorization_v1/types/service.py @@ -41,7 +41,8 @@ class GetPolicyRequest(proto.Message): - r"""Request message for [BinauthzManagementService.GetPolicy][]. + r"""Request message for + [BinauthzManagementServiceV1.GetPolicy][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.GetPolicy]. Attributes: name (str): @@ -57,7 +58,8 @@ class GetPolicyRequest(proto.Message): class UpdatePolicyRequest(proto.Message): - r"""Request message for [BinauthzManagementService.UpdatePolicy][]. + r"""Request message for + [BinauthzManagementServiceV1.UpdatePolicy][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.UpdatePolicy]. Attributes: policy (google.cloud.binaryauthorization_v1.types.Policy): @@ -77,7 +79,8 @@ class UpdatePolicyRequest(proto.Message): class CreateAttestorRequest(proto.Message): - r"""Request message for [BinauthzManagementService.CreateAttestor][]. + r"""Request message for + [BinauthzManagementServiceV1.CreateAttestor][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.CreateAttestor]. Attributes: parent (str): @@ -112,7 +115,8 @@ class CreateAttestorRequest(proto.Message): class GetAttestorRequest(proto.Message): - r"""Request message for [BinauthzManagementService.GetAttestor][]. + r"""Request message for + [BinauthzManagementServiceV1.GetAttestor][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.GetAttestor]. Attributes: name (str): @@ -128,7 +132,8 @@ class GetAttestorRequest(proto.Message): class UpdateAttestorRequest(proto.Message): - r"""Request message for [BinauthzManagementService.UpdateAttestor][]. + r"""Request message for + [BinauthzManagementServiceV1.UpdateAttestor][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.UpdateAttestor]. Attributes: attestor (google.cloud.binaryauthorization_v1.types.Attestor): @@ -148,7 +153,8 @@ class UpdateAttestorRequest(proto.Message): class ListAttestorsRequest(proto.Message): - r"""Request message for [BinauthzManagementService.ListAttestors][]. + r"""Request message for + [BinauthzManagementServiceV1.ListAttestors][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.ListAttestors]. Attributes: parent (str): @@ -183,7 +189,8 @@ class ListAttestorsRequest(proto.Message): class ListAttestorsResponse(proto.Message): - r"""Response message for [BinauthzManagementService.ListAttestors][]. + r"""Response message for + [BinauthzManagementServiceV1.ListAttestors][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.ListAttestors]. Attributes: attestors (MutableSequence[google.cloud.binaryauthorization_v1.types.Attestor]): @@ -213,7 +220,8 @@ def raw_page(self): class DeleteAttestorRequest(proto.Message): - r"""Request message for [BinauthzManagementService.DeleteAttestor][]. + r"""Request message for + [BinauthzManagementServiceV1.DeleteAttestor][google.cloud.binaryauthorization.v1.BinauthzManagementServiceV1.DeleteAttestor]. Attributes: name (str): @@ -257,9 +265,10 @@ class ValidateAttestationOccurrenceRequest(proto.Message): attestation (grafeas.grafeas_v1.types.AttestationOccurrence): Required. An [AttestationOccurrence][grafeas.v1.AttestationOccurrence] to - be checked that it can be verified by the Attestor. It does - not have to be an existing entity in Container Analysis. It - must otherwise be a valid AttestationOccurrence. + be checked that it can be verified by the ``Attestor``. It + does not have to be an existing entity in Container + Analysis. It must otherwise be a valid + ``AttestationOccurrence``. occurrence_note (str): Required. The resource name of the [Note][grafeas.v1.Note] to which the containing [Occurrence][grafeas.v1.Occurrence] @@ -302,7 +311,7 @@ class ValidateAttestationOccurrenceResponse(proto.Message): """ class Result(proto.Enum): - r"""The enum returned in the "result" field. + r"""The enum returned in the ``result`` field. Values: RESULT_UNSPECIFIED (0): diff --git a/packages/google-cloud-binary-authorization/setup.py b/packages/google-cloud-binary-authorization/setup.py index 32fab06a13ff..03e0247d6d5b 100644 --- a/packages/google-cloud-binary-authorization/setup.py +++ b/packages/google-cloud-binary-authorization/setup.py @@ -53,6 +53,7 @@ "grpcio >= 1.75.1, < 2.0.0; python_version >= '3.14'", "proto-plus >= 1.26.1, <2.0.0", "protobuf >= 6.33.5, < 8.0.0", + "grpc-google-iam-v1 >= 0.14.2, <1.0.0", ] extras = {} url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-binary-authorization" diff --git a/packages/google-cloud-binary-authorization/testing/constraints-3.10.txt b/packages/google-cloud-binary-authorization/testing/constraints-3.10.txt index 81605a716d32..3a84666fb90e 100644 --- a/packages/google-cloud-binary-authorization/testing/constraints-3.10.txt +++ b/packages/google-cloud-binary-authorization/testing/constraints-3.10.txt @@ -9,3 +9,4 @@ google-auth==2.14.1 grpcio==1.59.0 proto-plus==1.26.1 protobuf==6.33.5 +grpc-google-iam-v1==0.14.2 diff --git a/packages/google-cloud-binary-authorization/testing/constraints-3.11.txt b/packages/google-cloud-binary-authorization/testing/constraints-3.11.txt index 7599dea499ed..1cd0c5a2c3d4 100644 --- a/packages/google-cloud-binary-authorization/testing/constraints-3.11.txt +++ b/packages/google-cloud-binary-authorization/testing/constraints-3.11.txt @@ -8,3 +8,4 @@ proto-plus protobuf # cryptography is a direct dependency of google-auth cryptography +grpc-google-iam-v1 diff --git a/packages/google-cloud-binary-authorization/testing/constraints-3.12.txt b/packages/google-cloud-binary-authorization/testing/constraints-3.12.txt index 7599dea499ed..1cd0c5a2c3d4 100644 --- a/packages/google-cloud-binary-authorization/testing/constraints-3.12.txt +++ b/packages/google-cloud-binary-authorization/testing/constraints-3.12.txt @@ -8,3 +8,4 @@ proto-plus protobuf # cryptography is a direct dependency of google-auth cryptography +grpc-google-iam-v1 diff --git a/packages/google-cloud-binary-authorization/testing/constraints-3.13.txt b/packages/google-cloud-binary-authorization/testing/constraints-3.13.txt index 6bd7e1f5b03d..f85022a2fb62 100644 --- a/packages/google-cloud-binary-authorization/testing/constraints-3.13.txt +++ b/packages/google-cloud-binary-authorization/testing/constraints-3.13.txt @@ -10,3 +10,4 @@ google-auth>=2 grpcio>=1 proto-plus>=1 protobuf>=7 +grpc-google-iam-v1>=0 diff --git a/packages/google-cloud-binary-authorization/testing/constraints-3.14.txt b/packages/google-cloud-binary-authorization/testing/constraints-3.14.txt index 6bd7e1f5b03d..f85022a2fb62 100644 --- a/packages/google-cloud-binary-authorization/testing/constraints-3.14.txt +++ b/packages/google-cloud-binary-authorization/testing/constraints-3.14.txt @@ -10,3 +10,4 @@ google-auth>=2 grpcio>=1 proto-plus>=1 protobuf>=7 +grpc-google-iam-v1>=0 diff --git a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_binauthz_management_service_v1.py b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_binauthz_management_service_v1.py index 450f321c6436..5ff547c37bc2 100644 --- a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_binauthz_management_service_v1.py +++ b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_binauthz_management_service_v1.py @@ -51,6 +51,11 @@ from google.api_core import retry as retries from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + options_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.oauth2 import service_account from google.cloud.binaryauthorization_v1.services.binauthz_management_service_v1 import ( @@ -1451,6 +1456,7 @@ def test_get_policy(request_type, transport: str = "grpc"): name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) response = client.get_policy(request) @@ -1468,6 +1474,7 @@ def test_get_policy(request_type, transport: str = "grpc"): response.global_policy_evaluation_mode == resources.Policy.GlobalPolicyEvaluationMode.ENABLE ) + assert response.etag == "etag_value" def test_get_policy_non_empty_request_with_auto_populated_field(): @@ -1600,6 +1607,7 @@ async def test_get_policy_async(request_type, transport: str = "grpc_asyncio"): name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) ) response = await client.get_policy(request) @@ -1618,6 +1626,7 @@ async def test_get_policy_async(request_type, transport: str = "grpc_asyncio"): response.global_policy_evaluation_mode == resources.Policy.GlobalPolicyEvaluationMode.ENABLE ) + assert response.etag == "etag_value" def test_get_policy_field_headers(): @@ -1783,6 +1792,7 @@ def test_update_policy(request_type, transport: str = "grpc"): name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) response = client.update_policy(request) @@ -1800,6 +1810,7 @@ def test_update_policy(request_type, transport: str = "grpc"): response.global_policy_evaluation_mode == resources.Policy.GlobalPolicyEvaluationMode.ENABLE ) + assert response.etag == "etag_value" def test_update_policy_non_empty_request_with_auto_populated_field(): @@ -1930,6 +1941,7 @@ async def test_update_policy_async(request_type, transport: str = "grpc_asyncio" name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) ) response = await client.update_policy(request) @@ -1948,6 +1960,7 @@ async def test_update_policy_async(request_type, transport: str = "grpc_asyncio" response.global_policy_evaluation_mode == resources.Policy.GlobalPolicyEvaluationMode.ENABLE ) + assert response.etag == "etag_value" def test_update_policy_field_headers(): @@ -2112,6 +2125,7 @@ def test_create_attestor(request_type, transport: str = "grpc"): call.return_value = resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) response = client.create_attestor(request) @@ -2125,6 +2139,7 @@ def test_create_attestor(request_type, transport: str = "grpc"): assert isinstance(response, resources.Attestor) assert response.name == "name_value" assert response.description == "description_value" + assert response.etag == "etag_value" def test_create_attestor_non_empty_request_with_auto_populated_field(): @@ -2260,6 +2275,7 @@ async def test_create_attestor_async(request_type, transport: str = "grpc_asynci resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) ) response = await client.create_attestor(request) @@ -2274,6 +2290,7 @@ async def test_create_attestor_async(request_type, transport: str = "grpc_asynci assert isinstance(response, resources.Attestor) assert response.name == "name_value" assert response.description == "description_value" + assert response.etag == "etag_value" def test_create_attestor_field_headers(): @@ -2458,6 +2475,7 @@ def test_get_attestor(request_type, transport: str = "grpc"): call.return_value = resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) response = client.get_attestor(request) @@ -2471,6 +2489,7 @@ def test_get_attestor(request_type, transport: str = "grpc"): assert isinstance(response, resources.Attestor) assert response.name == "name_value" assert response.description == "description_value" + assert response.etag == "etag_value" def test_get_attestor_non_empty_request_with_auto_populated_field(): @@ -2604,6 +2623,7 @@ async def test_get_attestor_async(request_type, transport: str = "grpc_asyncio") resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) ) response = await client.get_attestor(request) @@ -2618,6 +2638,7 @@ async def test_get_attestor_async(request_type, transport: str = "grpc_asyncio") assert isinstance(response, resources.Attestor) assert response.name == "name_value" assert response.description == "description_value" + assert response.etag == "etag_value" def test_get_attestor_field_headers(): @@ -2782,6 +2803,7 @@ def test_update_attestor(request_type, transport: str = "grpc"): call.return_value = resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) response = client.update_attestor(request) @@ -2795,6 +2817,7 @@ def test_update_attestor(request_type, transport: str = "grpc"): assert isinstance(response, resources.Attestor) assert response.name == "name_value" assert response.description == "description_value" + assert response.etag == "etag_value" def test_update_attestor_non_empty_request_with_auto_populated_field(): @@ -2924,6 +2947,7 @@ async def test_update_attestor_async(request_type, transport: str = "grpc_asynci resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) ) response = await client.update_attestor(request) @@ -2938,6 +2962,7 @@ async def test_update_attestor_async(request_type, transport: str = "grpc_asynci assert isinstance(response, resources.Attestor) assert response.name == "name_value" assert response.description == "description_value" + assert response.etag == "etag_value" def test_update_attestor_field_headers(): @@ -5501,6 +5526,7 @@ async def test_get_policy_empty_call_grpc_asyncio(): name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) ) await client.get_policy(request=None) @@ -5529,6 +5555,7 @@ async def test_update_policy_empty_call_grpc_asyncio(): name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) ) await client.update_policy(request=None) @@ -5556,6 +5583,7 @@ async def test_create_attestor_empty_call_grpc_asyncio(): resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) ) await client.create_attestor(request=None) @@ -5583,6 +5611,7 @@ async def test_get_attestor_empty_call_grpc_asyncio(): resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) ) await client.get_attestor(request=None) @@ -5610,6 +5639,7 @@ async def test_update_attestor_empty_call_grpc_asyncio(): resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) ) await client.update_attestor(request=None) @@ -5723,6 +5753,7 @@ def test_get_policy_rest_call_success(request_type): name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) # Wrap the value into a proper Response obj @@ -5745,6 +5776,7 @@ def test_get_policy_rest_call_success(request_type): response.global_policy_evaluation_mode == resources.Policy.GlobalPolicyEvaluationMode.ENABLE ) + assert response.etag == "etag_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -5866,6 +5898,7 @@ def test_update_policy_rest_call_success(request_type): "enforcement_mode": 1, }, "update_time": {"seconds": 751, "nanos": 543}, + "etag": "etag_value", } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -5943,6 +5976,7 @@ def get_message_fields(field): name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) # Wrap the value into a proper Response obj @@ -5965,6 +5999,7 @@ def get_message_fields(field): response.global_policy_evaluation_mode == resources.Policy.GlobalPolicyEvaluationMode.ENABLE ) + assert response.etag == "etag_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -6081,12 +6116,14 @@ def test_create_attestor_rest_call_success(request_type): "pkix_public_key": { "public_key_pem": "public_key_pem_value", "signature_algorithm": 1, + "key_id": "key_id_value", }, } ], "delegation_service_account_email": "delegation_service_account_email_value", }, "update_time": {"seconds": 751, "nanos": 543}, + "etag": "etag_value", } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -6163,6 +6200,7 @@ def get_message_fields(field): return_value = resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) # Wrap the value into a proper Response obj @@ -6181,6 +6219,7 @@ def get_message_fields(field): assert isinstance(response, resources.Attestor) assert response.name == "name_value" assert response.description == "description_value" + assert response.etag == "etag_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -6293,6 +6332,7 @@ def test_get_attestor_rest_call_success(request_type): return_value = resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) # Wrap the value into a proper Response obj @@ -6311,6 +6351,7 @@ def test_get_attestor_rest_call_success(request_type): assert isinstance(response, resources.Attestor) assert response.name == "name_value" assert response.description == "description_value" + assert response.etag == "etag_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -6427,12 +6468,14 @@ def test_update_attestor_rest_call_success(request_type): "pkix_public_key": { "public_key_pem": "public_key_pem_value", "signature_algorithm": 1, + "key_id": "key_id_value", }, } ], "delegation_service_account_email": "delegation_service_account_email_value", }, "update_time": {"seconds": 751, "nanos": 543}, + "etag": "etag_value", } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -6509,6 +6552,7 @@ def get_message_fields(field): return_value = resources.Attestor( name="name_value", description="description_value", + etag="etag_value", ) # Wrap the value into a proper Response obj @@ -6527,6 +6571,7 @@ def get_message_fields(field): assert isinstance(response, resources.Attestor) assert response.name == "name_value" assert response.description == "description_value" + assert response.etag == "etag_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -6828,6 +6873,189 @@ def test_delete_attestor_rest_interceptors(null_interceptor): pre.assert_called_once() +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"resource": "projects/sample1/policy"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/policy"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"resource": "projects/sample1/policy"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/policy"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"resource": "projects/sample1/policy"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/policy"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + def test_initialize_client_w_rest(): client = BinauthzManagementServiceV1Client( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -7008,6 +7236,9 @@ def test_binauthz_management_service_v1_base_transport(): "update_attestor", "list_attestors", "delete_attestor", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", ) for method in methods: with pytest.raises(NotImplementedError): @@ -7607,6 +7838,625 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_set_iam_policy(transport: str = "grpc"): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = BinauthzManagementServiceV1AsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = BinauthzManagementServiceV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = BinauthzManagementServiceV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = BinauthzManagementServiceV1Client( + 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() + + client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = BinauthzManagementServiceV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +def test_get_iam_policy(transport: str = "grpc"): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = BinauthzManagementServiceV1AsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = BinauthzManagementServiceV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = BinauthzManagementServiceV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = BinauthzManagementServiceV1Client( + 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() + + client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = BinauthzManagementServiceV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = BinauthzManagementServiceV1AsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = BinauthzManagementServiceV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = BinauthzManagementServiceV1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = BinauthzManagementServiceV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_test_iam_permissions_flattened(): + client = BinauthzManagementServiceV1Client( + 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() + + client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = BinauthzManagementServiceV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + def test_transport_close_grpc(): client = BinauthzManagementServiceV1Client( credentials=ga_credentials.AnonymousCredentials(), transport="grpc" diff --git a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_system_policy_v1.py b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_system_policy_v1.py index d87f29b79e3b..47b52185f3b2 100644 --- a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_system_policy_v1.py +++ b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_system_policy_v1.py @@ -51,6 +51,11 @@ from google.api_core import retry as retries from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + options_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.oauth2 import service_account from google.cloud.binaryauthorization_v1.services.system_policy_v1 import ( @@ -1353,6 +1358,7 @@ def test_get_system_policy(request_type, transport: str = "grpc"): name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) response = client.get_system_policy(request) @@ -1370,6 +1376,7 @@ def test_get_system_policy(request_type, transport: str = "grpc"): response.global_policy_evaluation_mode == resources.Policy.GlobalPolicyEvaluationMode.ENABLE ) + assert response.etag == "etag_value" def test_get_system_policy_non_empty_request_with_auto_populated_field(): @@ -1510,6 +1517,7 @@ async def test_get_system_policy_async(request_type, transport: str = "grpc_asyn name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) ) response = await client.get_system_policy(request) @@ -1528,6 +1536,7 @@ async def test_get_system_policy_async(request_type, transport: str = "grpc_asyn response.global_policy_evaluation_mode == resources.Policy.GlobalPolicyEvaluationMode.ENABLE ) + assert response.etag == "etag_value" def test_get_system_policy_field_headers(): @@ -2016,6 +2025,7 @@ async def test_get_system_policy_empty_call_grpc_asyncio(): name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) ) await client.get_system_policy(request=None) @@ -2083,6 +2093,7 @@ def test_get_system_policy_rest_call_success(request_type): name="name_value", description="description_value", global_policy_evaluation_mode=resources.Policy.GlobalPolicyEvaluationMode.ENABLE, + etag="etag_value", ) # Wrap the value into a proper Response obj @@ -2105,6 +2116,7 @@ def test_get_system_policy_rest_call_success(request_type): response.global_policy_evaluation_mode == resources.Policy.GlobalPolicyEvaluationMode.ENABLE ) + assert response.etag == "etag_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -2170,6 +2182,189 @@ def test_get_system_policy_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = SystemPolicyV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"resource": "projects/sample1/policy"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = SystemPolicyV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/policy"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = SystemPolicyV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"resource": "projects/sample1/policy"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = SystemPolicyV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/policy"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = SystemPolicyV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"resource": "projects/sample1/policy"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = SystemPolicyV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/policy"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + def test_initialize_client_w_rest(): client = SystemPolicyV1Client( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -2230,7 +2425,12 @@ def test_system_policy_v1_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. - methods = ("get_system_policy",) + methods = ( + "get_system_policy", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + ) for method in methods: with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) @@ -2773,6 +2973,625 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_set_iam_policy(transport: str = "grpc"): + client = SystemPolicyV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = SystemPolicyV1AsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = SystemPolicyV1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SystemPolicyV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = SystemPolicyV1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = SystemPolicyV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = SystemPolicyV1Client( + 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() + + client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = SystemPolicyV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +def test_get_iam_policy(transport: str = "grpc"): + client = SystemPolicyV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = SystemPolicyV1AsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = SystemPolicyV1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SystemPolicyV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = SystemPolicyV1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = SystemPolicyV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = SystemPolicyV1Client( + 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() + + client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = SystemPolicyV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = SystemPolicyV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = SystemPolicyV1AsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = SystemPolicyV1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SystemPolicyV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = SystemPolicyV1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = SystemPolicyV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_test_iam_permissions_flattened(): + client = SystemPolicyV1Client( + 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() + + client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = SystemPolicyV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + def test_transport_close_grpc(): client = SystemPolicyV1Client( credentials=ga_credentials.AnonymousCredentials(), transport="grpc" diff --git a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_validation_helper_v1.py b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_validation_helper_v1.py index 9c8a41ce1cf5..a84affde77d0 100644 --- a/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_validation_helper_v1.py +++ b/packages/google-cloud-binary-authorization/tests/unit/gapic/binaryauthorization_v1/test_validation_helper_v1.py @@ -50,6 +50,11 @@ from google.api_core import retry as retries from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + options_pb2, # type: ignore + policy_pb2, # type: ignore +) from google.oauth2 import service_account from google.cloud.binaryauthorization_v1.services.validation_helper_v1 import ( @@ -2103,6 +2108,189 @@ def test_validate_attestation_occurrence_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + client = ValidationHelperV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"resource": "projects/sample1/policy"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = ValidationHelperV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/policy"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + client = ValidationHelperV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"resource": "projects/sample1/policy"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.set_iam_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = ValidationHelperV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/policy"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = ValidationHelperV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"resource": "projects/sample1/policy"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_iam_permissions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = ValidationHelperV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"resource": "projects/sample1/policy"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + def test_initialize_client_w_rest(): client = ValidationHelperV1Client( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -2163,7 +2351,12 @@ def test_validation_helper_v1_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. - methods = ("validate_attestation_occurrence",) + methods = ( + "validate_attestation_occurrence", + "set_iam_policy", + "get_iam_policy", + "test_iam_permissions", + ) for method in methods: with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) @@ -2688,6 +2881,625 @@ def test_client_with_default_client_info(): prep.assert_called_once_with(client_info) +def test_set_iam_policy(transport: str = "grpc"): + client = ValidationHelperV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = ValidationHelperV1AsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_field_headers(): + client = ValidationHelperV1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ValidationHelperV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_set_iam_policy_from_dict(): + client = ValidationHelperV1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = ValidationHelperV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = ValidationHelperV1Client( + 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() + + client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = ValidationHelperV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +def test_get_iam_policy(transport: str = "grpc"): + client = ValidationHelperV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = ValidationHelperV1AsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = ValidationHelperV1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ValidationHelperV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = ValidationHelperV1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = ValidationHelperV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = ValidationHelperV1Client( + 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() + + client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = ValidationHelperV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = ValidationHelperV1Client( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = ValidationHelperV1AsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = ValidationHelperV1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ValidationHelperV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource/value", + ) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = ValidationHelperV1Client( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = ValidationHelperV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_test_iam_permissions_flattened(): + client = ValidationHelperV1Client( + 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() + + client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = ValidationHelperV1AsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions() + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + def test_transport_close_grpc(): client = ValidationHelperV1Client( credentials=ga_credentials.AnonymousCredentials(), transport="grpc" diff --git a/packages/google-cloud-chronicle/docs/chronicle_v1/findings_refinement_service.rst b/packages/google-cloud-chronicle/docs/chronicle_v1/findings_refinement_service.rst new file mode 100644 index 000000000000..39dbb3fdecf5 --- /dev/null +++ b/packages/google-cloud-chronicle/docs/chronicle_v1/findings_refinement_service.rst @@ -0,0 +1,10 @@ +FindingsRefinementService +------------------------------------------- + +.. automodule:: google.cloud.chronicle_v1.services.findings_refinement_service + :members: + :inherited-members: + +.. automodule:: google.cloud.chronicle_v1.services.findings_refinement_service.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-chronicle/docs/chronicle_v1/services_.rst b/packages/google-cloud-chronicle/docs/chronicle_v1/services_.rst index 1cde737362f4..e1855add64c0 100644 --- a/packages/google-cloud-chronicle/docs/chronicle_v1/services_.rst +++ b/packages/google-cloud-chronicle/docs/chronicle_v1/services_.rst @@ -10,6 +10,7 @@ Services for Google Cloud Chronicle v1 API data_table_service entity_service featured_content_native_dashboard_service + findings_refinement_service instance_service native_dashboard_service reference_list_service diff --git a/packages/google-cloud-chronicle/google/cloud/chronicle/__init__.py b/packages/google-cloud-chronicle/google/cloud/chronicle/__init__.py index 8be7d23a51d0..acfc7c6a8604 100644 --- a/packages/google-cloud-chronicle/google/cloud/chronicle/__init__.py +++ b/packages/google-cloud-chronicle/google/cloud/chronicle/__init__.py @@ -58,6 +58,12 @@ from google.cloud.chronicle_v1.services.featured_content_native_dashboard_service.client import ( FeaturedContentNativeDashboardServiceClient, ) +from google.cloud.chronicle_v1.services.findings_refinement_service.async_client import ( + FindingsRefinementServiceAsyncClient, +) +from google.cloud.chronicle_v1.services.findings_refinement_service.client import ( + FindingsRefinementServiceClient, +) from google.cloud.chronicle_v1.services.instance_service.async_client import ( InstanceServiceAsyncClient, ) @@ -203,6 +209,28 @@ ListFeaturedContentNativeDashboardsRequest, ListFeaturedContentNativeDashboardsResponse, ) +from google.cloud.chronicle_v1.types.findings_refinement import ( + ComputeAllFindingsRefinementActivitiesRequest, + ComputeAllFindingsRefinementActivitiesResponse, + ComputeFindingsRefinementActivityRequest, + ComputeFindingsRefinementActivityResponse, + CreateFindingsRefinementRequest, + DetectionExclusionActivity, + DetectionExclusionApplication, + FindingsRefinement, + FindingsRefinementActivity, + FindingsRefinementDeployment, + FindingsRefinementType, + GetFindingsRefinementDeploymentRequest, + GetFindingsRefinementRequest, + ListAllFindingsRefinementDeploymentsRequest, + ListAllFindingsRefinementDeploymentsResponse, + ListFindingsRefinementsRequest, + ListFindingsRefinementsResponse, + OutcomeFilter, + UpdateFindingsRefinementDeploymentRequest, + UpdateFindingsRefinementRequest, +) from google.cloud.chronicle_v1.types.instance import GetInstanceRequest, Instance from google.cloud.chronicle_v1.types.native_dashboard import ( AddChartRequest, @@ -302,6 +330,8 @@ "EntityServiceAsyncClient", "FeaturedContentNativeDashboardServiceClient", "FeaturedContentNativeDashboardServiceAsyncClient", + "FindingsRefinementServiceClient", + "FindingsRefinementServiceAsyncClient", "InstanceServiceClient", "InstanceServiceAsyncClient", "NativeDashboardServiceClient", @@ -413,6 +443,26 @@ "InstallFeaturedContentNativeDashboardResponse", "ListFeaturedContentNativeDashboardsRequest", "ListFeaturedContentNativeDashboardsResponse", + "ComputeAllFindingsRefinementActivitiesRequest", + "ComputeAllFindingsRefinementActivitiesResponse", + "ComputeFindingsRefinementActivityRequest", + "ComputeFindingsRefinementActivityResponse", + "CreateFindingsRefinementRequest", + "DetectionExclusionActivity", + "DetectionExclusionApplication", + "FindingsRefinement", + "FindingsRefinementActivity", + "FindingsRefinementDeployment", + "GetFindingsRefinementDeploymentRequest", + "GetFindingsRefinementRequest", + "ListAllFindingsRefinementDeploymentsRequest", + "ListAllFindingsRefinementDeploymentsResponse", + "ListFindingsRefinementsRequest", + "ListFindingsRefinementsResponse", + "OutcomeFilter", + "UpdateFindingsRefinementDeploymentRequest", + "UpdateFindingsRefinementRequest", + "FindingsRefinementType", "GetInstanceRequest", "Instance", "AddChartRequest", diff --git a/packages/google-cloud-chronicle/google/cloud/chronicle_v1/__init__.py b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/__init__.py index 3f77c05f421f..cfbcffe12560 100644 --- a/packages/google-cloud-chronicle/google/cloud/chronicle_v1/__init__.py +++ b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/__init__.py @@ -48,6 +48,10 @@ FeaturedContentNativeDashboardServiceAsyncClient, FeaturedContentNativeDashboardServiceClient, ) +from .services.findings_refinement_service import ( + FindingsRefinementServiceAsyncClient, + FindingsRefinementServiceClient, +) from .services.instance_service import InstanceServiceAsyncClient, InstanceServiceClient from .services.native_dashboard_service import ( NativeDashboardServiceAsyncClient, @@ -177,6 +181,28 @@ ListFeaturedContentNativeDashboardsRequest, ListFeaturedContentNativeDashboardsResponse, ) +from .types.findings_refinement import ( + ComputeAllFindingsRefinementActivitiesRequest, + ComputeAllFindingsRefinementActivitiesResponse, + ComputeFindingsRefinementActivityRequest, + ComputeFindingsRefinementActivityResponse, + CreateFindingsRefinementRequest, + DetectionExclusionActivity, + DetectionExclusionApplication, + FindingsRefinement, + FindingsRefinementActivity, + FindingsRefinementDeployment, + FindingsRefinementType, + GetFindingsRefinementDeploymentRequest, + GetFindingsRefinementRequest, + ListAllFindingsRefinementDeploymentsRequest, + ListAllFindingsRefinementDeploymentsResponse, + ListFindingsRefinementsRequest, + ListFindingsRefinementsResponse, + OutcomeFilter, + UpdateFindingsRefinementDeploymentRequest, + UpdateFindingsRefinementRequest, +) from .types.instance import GetInstanceRequest, Instance from .types.native_dashboard import ( AddChartRequest, @@ -352,6 +378,7 @@ def _get_version(dependency_name): "DataTableServiceAsyncClient", "EntityServiceAsyncClient", "FeaturedContentNativeDashboardServiceAsyncClient", + "FindingsRefinementServiceAsyncClient", "InstanceServiceAsyncClient", "NativeDashboardServiceAsyncClient", "ReferenceListServiceAsyncClient", @@ -379,10 +406,15 @@ def _get_version(dependency_name): "ColumnMetadata", "CompilationDiagnostic", "CompilationPosition", + "ComputeAllFindingsRefinementActivitiesRequest", + "ComputeAllFindingsRefinementActivitiesResponse", + "ComputeFindingsRefinementActivityRequest", + "ComputeFindingsRefinementActivityResponse", "CreateDataAccessLabelRequest", "CreateDataAccessScopeRequest", "CreateDataTableRequest", "CreateDataTableRowRequest", + "CreateFindingsRefinementRequest", "CreateNativeDashboardRequest", "CreateReferenceListRequest", "CreateRetrohuntRequest", @@ -417,6 +449,8 @@ def _get_version(dependency_name): "DeleteNativeDashboardRequest", "DeleteRuleRequest", "DeleteWatchlistRequest", + "DetectionExclusionActivity", + "DetectionExclusionApplication", "DuplicateChartRequest", "DuplicateChartResponse", "DuplicateNativeDashboardRequest", @@ -432,6 +466,11 @@ def _get_version(dependency_name): "FeaturedContentNativeDashboardServiceClient", "FilterOperator", "FilterOperatorAndValues", + "FindingsRefinement", + "FindingsRefinementActivity", + "FindingsRefinementDeployment", + "FindingsRefinementServiceClient", + "FindingsRefinementType", "GetBigQueryExportRequest", "GetDashboardChartRequest", "GetDashboardQueryRequest", @@ -441,6 +480,8 @@ def _get_version(dependency_name): "GetDataTableRequest", "GetDataTableRowRequest", "GetFeaturedContentNativeDashboardRequest", + "GetFindingsRefinementDeploymentRequest", + "GetFindingsRefinementRequest", "GetInstanceRequest", "GetNativeDashboardRequest", "GetReferenceListRequest", @@ -464,6 +505,8 @@ def _get_version(dependency_name): "LatestExportJobState", "LegendAlign", "LegendOrient", + "ListAllFindingsRefinementDeploymentsRequest", + "ListAllFindingsRefinementDeploymentsResponse", "ListDataAccessLabelsRequest", "ListDataAccessLabelsResponse", "ListDataAccessScopesRequest", @@ -474,6 +517,8 @@ def _get_version(dependency_name): "ListDataTablesResponse", "ListFeaturedContentNativeDashboardsRequest", "ListFeaturedContentNativeDashboardsResponse", + "ListFindingsRefinementsRequest", + "ListFindingsRefinementsResponse", "ListNativeDashboardsRequest", "ListNativeDashboardsResponse", "ListReferenceListsRequest", @@ -498,6 +543,7 @@ def _get_version(dependency_name): "NativeDashboardServiceClient", "NativeDashboardView", "NativeDashboardWithChartsAndQueries", + "OutcomeFilter", "PlotMode", "PointSizeType", "ProvisionBigQueryExportRequest", @@ -534,6 +580,8 @@ def _get_version(dependency_name): "UpdateDataAccessScopeRequest", "UpdateDataTableRequest", "UpdateDataTableRowRequest", + "UpdateFindingsRefinementDeploymentRequest", + "UpdateFindingsRefinementRequest", "UpdateNativeDashboardRequest", "UpdateReferenceListRequest", "UpdateRuleDeploymentRequest", diff --git a/packages/google-cloud-chronicle/google/cloud/chronicle_v1/gapic_metadata.json b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/gapic_metadata.json index 511d879a4faa..ff9a64346478 100644 --- a/packages/google-cloud-chronicle/google/cloud/chronicle_v1/gapic_metadata.json +++ b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/gapic_metadata.json @@ -738,6 +738,160 @@ } } }, + "FindingsRefinementService": { + "clients": { + "grpc": { + "libraryClient": "FindingsRefinementServiceClient", + "rpcs": { + "ComputeAllFindingsRefinementActivities": { + "methods": [ + "compute_all_findings_refinement_activities" + ] + }, + "ComputeFindingsRefinementActivity": { + "methods": [ + "compute_findings_refinement_activity" + ] + }, + "CreateFindingsRefinement": { + "methods": [ + "create_findings_refinement" + ] + }, + "GetFindingsRefinement": { + "methods": [ + "get_findings_refinement" + ] + }, + "GetFindingsRefinementDeployment": { + "methods": [ + "get_findings_refinement_deployment" + ] + }, + "ListAllFindingsRefinementDeployments": { + "methods": [ + "list_all_findings_refinement_deployments" + ] + }, + "ListFindingsRefinements": { + "methods": [ + "list_findings_refinements" + ] + }, + "UpdateFindingsRefinement": { + "methods": [ + "update_findings_refinement" + ] + }, + "UpdateFindingsRefinementDeployment": { + "methods": [ + "update_findings_refinement_deployment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "FindingsRefinementServiceAsyncClient", + "rpcs": { + "ComputeAllFindingsRefinementActivities": { + "methods": [ + "compute_all_findings_refinement_activities" + ] + }, + "ComputeFindingsRefinementActivity": { + "methods": [ + "compute_findings_refinement_activity" + ] + }, + "CreateFindingsRefinement": { + "methods": [ + "create_findings_refinement" + ] + }, + "GetFindingsRefinement": { + "methods": [ + "get_findings_refinement" + ] + }, + "GetFindingsRefinementDeployment": { + "methods": [ + "get_findings_refinement_deployment" + ] + }, + "ListAllFindingsRefinementDeployments": { + "methods": [ + "list_all_findings_refinement_deployments" + ] + }, + "ListFindingsRefinements": { + "methods": [ + "list_findings_refinements" + ] + }, + "UpdateFindingsRefinement": { + "methods": [ + "update_findings_refinement" + ] + }, + "UpdateFindingsRefinementDeployment": { + "methods": [ + "update_findings_refinement_deployment" + ] + } + } + }, + "rest": { + "libraryClient": "FindingsRefinementServiceClient", + "rpcs": { + "ComputeAllFindingsRefinementActivities": { + "methods": [ + "compute_all_findings_refinement_activities" + ] + }, + "ComputeFindingsRefinementActivity": { + "methods": [ + "compute_findings_refinement_activity" + ] + }, + "CreateFindingsRefinement": { + "methods": [ + "create_findings_refinement" + ] + }, + "GetFindingsRefinement": { + "methods": [ + "get_findings_refinement" + ] + }, + "GetFindingsRefinementDeployment": { + "methods": [ + "get_findings_refinement_deployment" + ] + }, + "ListAllFindingsRefinementDeployments": { + "methods": [ + "list_all_findings_refinement_deployments" + ] + }, + "ListFindingsRefinements": { + "methods": [ + "list_findings_refinements" + ] + }, + "UpdateFindingsRefinement": { + "methods": [ + "update_findings_refinement" + ] + }, + "UpdateFindingsRefinementDeployment": { + "methods": [ + "update_findings_refinement_deployment" + ] + } + } + } + } + }, "InstanceService": { "clients": { "grpc": { diff --git a/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/__init__.py b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/__init__.py new file mode 100644 index 000000000000..3ac8bd4bf45d --- /dev/null +++ b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import FindingsRefinementServiceAsyncClient +from .client import FindingsRefinementServiceClient + +__all__ = ( + "FindingsRefinementServiceClient", + "FindingsRefinementServiceAsyncClient", +) diff --git a/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/async_client.py b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/async_client.py new file mode 100644 index 000000000000..1cf5cf7fe3e0 --- /dev/null +++ b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/async_client.py @@ -0,0 +1,1755 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.chronicle_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.chronicle_v1.services.findings_refinement_service import pagers +from google.cloud.chronicle_v1.types import findings_refinement +from google.cloud.chronicle_v1.types import ( + findings_refinement as gcc_findings_refinement, +) + +from .client import FindingsRefinementServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, FindingsRefinementServiceTransport +from .transports.grpc_asyncio import FindingsRefinementServiceGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class FindingsRefinementServiceAsyncClient: + """FindingsRefinementService provides an interface for filtering + out findings that are unlikely to be real threats to prevent + them from triggering alerts or notifications. + """ + + _client: FindingsRefinementServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = FindingsRefinementServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = FindingsRefinementServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ( + FindingsRefinementServiceClient._DEFAULT_ENDPOINT_TEMPLATE + ) + _DEFAULT_UNIVERSE = FindingsRefinementServiceClient._DEFAULT_UNIVERSE + + curated_rule_path = staticmethod(FindingsRefinementServiceClient.curated_rule_path) + parse_curated_rule_path = staticmethod( + FindingsRefinementServiceClient.parse_curated_rule_path + ) + curated_rule_set_path = staticmethod( + FindingsRefinementServiceClient.curated_rule_set_path + ) + parse_curated_rule_set_path = staticmethod( + FindingsRefinementServiceClient.parse_curated_rule_set_path + ) + findings_refinement_path = staticmethod( + FindingsRefinementServiceClient.findings_refinement_path + ) + parse_findings_refinement_path = staticmethod( + FindingsRefinementServiceClient.parse_findings_refinement_path + ) + findings_refinement_deployment_path = staticmethod( + FindingsRefinementServiceClient.findings_refinement_deployment_path + ) + parse_findings_refinement_deployment_path = staticmethod( + FindingsRefinementServiceClient.parse_findings_refinement_deployment_path + ) + instance_path = staticmethod(FindingsRefinementServiceClient.instance_path) + parse_instance_path = staticmethod( + FindingsRefinementServiceClient.parse_instance_path + ) + rule_path = staticmethod(FindingsRefinementServiceClient.rule_path) + parse_rule_path = staticmethod(FindingsRefinementServiceClient.parse_rule_path) + common_billing_account_path = staticmethod( + FindingsRefinementServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + FindingsRefinementServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + FindingsRefinementServiceClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + FindingsRefinementServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + FindingsRefinementServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + FindingsRefinementServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + FindingsRefinementServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + FindingsRefinementServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + FindingsRefinementServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + FindingsRefinementServiceClient.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: + FindingsRefinementServiceAsyncClient: The constructed client. + """ + sa_info_func = ( + FindingsRefinementServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(FindingsRefinementServiceAsyncClient, info, *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: + FindingsRefinementServiceAsyncClient: The constructed client. + """ + sa_file_func = ( + FindingsRefinementServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + FindingsRefinementServiceAsyncClient, filename, *args, **kwargs + ) + + 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 FindingsRefinementServiceClient.get_mtls_endpoint_and_cert_source( + client_options + ) # type: ignore + + @property + def transport(self) -> FindingsRefinementServiceTransport: + """Returns the transport used by the client instance. + + Returns: + FindingsRefinementServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """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 = FindingsRefinementServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + FindingsRefinementServiceTransport, + Callable[..., FindingsRefinementServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the findings refinement service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,FindingsRefinementServiceTransport,Callable[..., FindingsRefinementServiceTransport]]]): + 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 FindingsRefinementServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = FindingsRefinementServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient`.", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "credentialsType": None, + }, + ) + + async def get_findings_refinement( + self, + request: Optional[ + Union[findings_refinement.GetFindingsRefinementRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> findings_refinement.FindingsRefinement: + r"""Gets a single findings refinement. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import chronicle_v1 + + async def sample_get_findings_refinement(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceAsyncClient() + + # Initialize request argument(s) + request = chronicle_v1.GetFindingsRefinementRequest( + name="name_value", + ) + + # Make the request + response = await client.get_findings_refinement(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.chronicle_v1.types.GetFindingsRefinementRequest, dict]]): + The request object. Request message for + GetFindingsRefinement method. + name (:class:`str`): + Required. The name of the findings refinement to + retrieve. Format: + projects/{project}/locations/{location}/instances/{instance}/findingsRefinements/{findings_refinement} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.chronicle_v1.types.FindingsRefinement: + Represents a set of logic conditions + used to refine various types of findings + such as curated rule detections. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, findings_refinement.GetFindingsRefinementRequest): + request = findings_refinement.GetFindingsRefinementRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_findings_refinement + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_findings_refinements( + self, + request: Optional[ + Union[findings_refinement.ListFindingsRefinementsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListFindingsRefinementsAsyncPager: + r"""Lists a collection of findings refinements. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import chronicle_v1 + + async def sample_list_findings_refinements(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceAsyncClient() + + # Initialize request argument(s) + request = chronicle_v1.ListFindingsRefinementsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings_refinements(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.chronicle_v1.types.ListFindingsRefinementsRequest, dict]]): + The request object. Request message for + ListFindingsRefinements method. + parent (:class:`str`): + Required. The parent, which owns this + collection of findings refinements. + Format: + + projects/{project}/locations/{location}/instances/{instance} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.chronicle_v1.services.findings_refinement_service.pagers.ListFindingsRefinementsAsyncPager: + Response message for + ListFindingsRefinements method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, findings_refinement.ListFindingsRefinementsRequest): + request = findings_refinement.ListFindingsRefinementsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = 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_refinements + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListFindingsRefinementsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_findings_refinement( + self, + request: Optional[ + Union[gcc_findings_refinement.CreateFindingsRefinementRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + findings_refinement: Optional[ + gcc_findings_refinement.FindingsRefinement + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_findings_refinement.FindingsRefinement: + r"""Creates a new findings refinement. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import chronicle_v1 + + async def sample_create_findings_refinement(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceAsyncClient() + + # Initialize request argument(s) + request = chronicle_v1.CreateFindingsRefinementRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_findings_refinement(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.chronicle_v1.types.CreateFindingsRefinementRequest, dict]]): + The request object. Request message for + CreateFindingsRefinement method. + parent (:class:`str`): + Required. The parent resource where + this findings refinement will be + created. Format: + + projects/{project}/locations/{location}/instances/{instance} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + findings_refinement (:class:`google.cloud.chronicle_v1.types.FindingsRefinement`): + Required. The findings refinement to + create. + + This corresponds to the ``findings_refinement`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.chronicle_v1.types.FindingsRefinement: + Represents a set of logic conditions + used to refine various types of findings + such as curated rule detections. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, findings_refinement] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, gcc_findings_refinement.CreateFindingsRefinementRequest + ): + request = gcc_findings_refinement.CreateFindingsRefinementRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if findings_refinement is not None: + request.findings_refinement = findings_refinement + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_findings_refinement + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", 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_findings_refinement( + self, + request: Optional[ + Union[gcc_findings_refinement.UpdateFindingsRefinementRequest, dict] + ] = None, + *, + findings_refinement: Optional[ + gcc_findings_refinement.FindingsRefinement + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_findings_refinement.FindingsRefinement: + r"""Updates a findings refinement. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import chronicle_v1 + + async def sample_update_findings_refinement(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceAsyncClient() + + # Initialize request argument(s) + request = chronicle_v1.UpdateFindingsRefinementRequest( + ) + + # Make the request + response = await client.update_findings_refinement(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.chronicle_v1.types.UpdateFindingsRefinementRequest, dict]]): + The request object. Request message for + UpdateFindingsRefinement method. + findings_refinement (:class:`google.cloud.chronicle_v1.types.FindingsRefinement`): + Required. The findings refinement to update. + + The findings refinement's ``name`` field is used to + identify the findings refinement to update. Format: + projects/{project}/locations/{location}/instances/{instance}/findingsRefinements/{findings_refinement} + + This corresponds to the ``findings_refinement`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The list of fields to update. If ``*`` is + provided, all 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.chronicle_v1.types.FindingsRefinement: + Represents a set of logic conditions + used to refine various types of findings + such as curated rule detections. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [findings_refinement, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, gcc_findings_refinement.UpdateFindingsRefinementRequest + ): + request = gcc_findings_refinement.UpdateFindingsRefinementRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if findings_refinement is not None: + request.findings_refinement = findings_refinement + if update_mask 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_findings_refinement + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("findings_refinement.name", request.findings_refinement.name),) + ), + ) + + # Validate the universe domain. + self._client._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_findings_refinement_deployment( + self, + request: Optional[ + Union[findings_refinement.GetFindingsRefinementDeploymentRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> findings_refinement.FindingsRefinementDeployment: + r"""Gets a findings refinement deployment. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import chronicle_v1 + + async def sample_get_findings_refinement_deployment(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceAsyncClient() + + # Initialize request argument(s) + request = chronicle_v1.GetFindingsRefinementDeploymentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_findings_refinement_deployment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.chronicle_v1.types.GetFindingsRefinementDeploymentRequest, dict]]): + The request object. Request message for + GetFindingsRefinementDeployment method. + name (:class:`str`): + Required. The name of the findings refinement to + retrieve. Format: + projects/{project}/locations/{location}/instances/{instance}/findingsRefinements/{findings_refinement}/deployment + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.chronicle_v1.types.FindingsRefinementDeployment: + The FindingsRefinementDeployment + resource represents the deployment state + of a findings refinement. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, findings_refinement.GetFindingsRefinementDeploymentRequest + ): + request = findings_refinement.GetFindingsRefinementDeploymentRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_findings_refinement_deployment + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._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_findings_refinement_deployment( + self, + request: Optional[ + Union[findings_refinement.UpdateFindingsRefinementDeploymentRequest, dict] + ] = None, + *, + findings_refinement_deployment: Optional[ + findings_refinement.FindingsRefinementDeployment + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> findings_refinement.FindingsRefinementDeployment: + r"""Updates a findings refinement deployment. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import chronicle_v1 + + async def sample_update_findings_refinement_deployment(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceAsyncClient() + + # Initialize request argument(s) + findings_refinement_deployment = chronicle_v1.FindingsRefinementDeployment() + findings_refinement_deployment.name = "name_value" + + request = chronicle_v1.UpdateFindingsRefinementDeploymentRequest( + findings_refinement_deployment=findings_refinement_deployment, + ) + + # Make the request + response = await client.update_findings_refinement_deployment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.chronicle_v1.types.UpdateFindingsRefinementDeploymentRequest, dict]]): + The request object. Request message for + UpdateFindingsRefinementDeployment + method. + findings_refinement_deployment (:class:`google.cloud.chronicle_v1.types.FindingsRefinementDeployment`): + Required. The findings refinement deployment to update. + + The findings refinement deployment's ``name`` field is + used to identify the findings refinement deployment to + update. Format: + projects/{project}/locations/{location}/instances/{instance}/findingsRefinements/{findings_refinement}/deployment + + This corresponds to the ``findings_refinement_deployment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to update. If ``*`` is + provided, all 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.chronicle_v1.types.FindingsRefinementDeployment: + The FindingsRefinementDeployment + resource represents the deployment state + of a findings refinement. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [findings_refinement_deployment, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, findings_refinement.UpdateFindingsRefinementDeploymentRequest + ): + request = findings_refinement.UpdateFindingsRefinementDeploymentRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if findings_refinement_deployment is not None: + request.findings_refinement_deployment = findings_refinement_deployment + if update_mask 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_findings_refinement_deployment + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ( + "findings_refinement_deployment.name", + request.findings_refinement_deployment.name, + ), + ) + ), + ) + + # Validate the universe domain. + self._client._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_all_findings_refinement_deployments( + self, + request: Optional[ + Union[findings_refinement.ListAllFindingsRefinementDeploymentsRequest, dict] + ] = None, + *, + instance: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAllFindingsRefinementDeploymentsAsyncPager: + r"""Lists all findings refinement deployments. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import chronicle_v1 + + async def sample_list_all_findings_refinement_deployments(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceAsyncClient() + + # Initialize request argument(s) + request = chronicle_v1.ListAllFindingsRefinementDeploymentsRequest( + instance="instance_value", + ) + + # Make the request + page_result = client.list_all_findings_refinement_deployments(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.chronicle_v1.types.ListAllFindingsRefinementDeploymentsRequest, dict]]): + The request object. Request message for + ListAllFindingsRefinementDeployments + method. + instance (:class:`str`): + Required. The name of the parent + resource, which is the SecOps instance + to list all findings refinement + deployments over. Format: + + projects/{project}/locations/{location}/instances/{instance} + + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.chronicle_v1.services.findings_refinement_service.pagers.ListAllFindingsRefinementDeploymentsAsyncPager: + Response message for + ListAllFindingsRefinementDeployments + method. Iterating over this object will + yield results and resolve additional + pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [instance] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, findings_refinement.ListAllFindingsRefinementDeploymentsRequest + ): + request = findings_refinement.ListAllFindingsRefinementDeploymentsRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if instance is not None: + request.instance = instance + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_all_findings_refinement_deployments + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("instance", request.instance),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAllFindingsRefinementDeploymentsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def compute_findings_refinement_activity( + self, + request: Optional[ + Union[findings_refinement.ComputeFindingsRefinementActivityRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> findings_refinement.ComputeFindingsRefinementActivityResponse: + r"""Returns findings refinement activity for a specific + findings refinement. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import chronicle_v1 + + async def sample_compute_findings_refinement_activity(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceAsyncClient() + + # Initialize request argument(s) + request = chronicle_v1.ComputeFindingsRefinementActivityRequest( + name="name_value", + ) + + # Make the request + response = await client.compute_findings_refinement_activity(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.chronicle_v1.types.ComputeFindingsRefinementActivityRequest, dict]]): + The request object. Request message for + ComputeFindingsRefinementActivity + method. + name (:class:`str`): + Required. Full resource name for the findings refinement + to fetch the activity for. Format: + projects/{project}/locations/{region}/instances/{instance}/findingsRefinements/{findings_refinement} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.chronicle_v1.types.ComputeFindingsRefinementActivityResponse: + Response message for + ComputeFindingsRefinementActivity + method. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, findings_refinement.ComputeFindingsRefinementActivityRequest + ): + request = findings_refinement.ComputeFindingsRefinementActivityRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.compute_findings_refinement_activity + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def compute_all_findings_refinement_activities( + self, + request: Optional[ + Union[ + findings_refinement.ComputeAllFindingsRefinementActivitiesRequest, dict + ] + ] = None, + *, + instance: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> findings_refinement.ComputeAllFindingsRefinementActivitiesResponse: + r"""Returns findings refinement activity for all findings + refinements. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import chronicle_v1 + + async def sample_compute_all_findings_refinement_activities(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceAsyncClient() + + # Initialize request argument(s) + request = chronicle_v1.ComputeAllFindingsRefinementActivitiesRequest( + instance="instance_value", + ) + + # Make the request + response = await client.compute_all_findings_refinement_activities(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.chronicle_v1.types.ComputeAllFindingsRefinementActivitiesRequest, dict]]): + The request object. Request message for + ComputeAllFindingsRefinementActivities + method. + instance (:class:`str`): + Required. The ID of the Instance to + retrieve counts for. Format: + + projects/{project}/locations/{location}/instances/{instance} + + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.chronicle_v1.types.ComputeAllFindingsRefinementActivitiesResponse: + Response message for + ComputeAllFindingsRefinementActivities + method. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [instance] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, findings_refinement.ComputeAllFindingsRefinementActivitiesRequest + ): + request = findings_refinement.ComputeAllFindingsRefinementActivitiesRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if instance is not None: + request.instance = instance + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.compute_all_findings_refinement_activities + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("instance", request.instance),)), + ) + + # Validate the universe domain. + self._client._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[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.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 request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "FindingsRefinementServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("FindingsRefinementServiceAsyncClient",) diff --git a/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/client.py b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/client.py new file mode 100644 index 000000000000..03468dccbc0b --- /dev/null +++ b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/client.py @@ -0,0 +1,2281 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.chronicle_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.chronicle_v1.services.findings_refinement_service import pagers +from google.cloud.chronicle_v1.types import findings_refinement +from google.cloud.chronicle_v1.types import ( + findings_refinement as gcc_findings_refinement, +) + +from .transports.base import DEFAULT_CLIENT_INFO, FindingsRefinementServiceTransport +from .transports.grpc import FindingsRefinementServiceGrpcTransport +from .transports.grpc_asyncio import FindingsRefinementServiceGrpcAsyncIOTransport +from .transports.rest import FindingsRefinementServiceRestTransport + + +class FindingsRefinementServiceClientMeta(type): + """Metaclass for the FindingsRefinementService 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[FindingsRefinementServiceTransport]] + _transport_registry["grpc"] = FindingsRefinementServiceGrpcTransport + _transport_registry["grpc_asyncio"] = FindingsRefinementServiceGrpcAsyncIOTransport + _transport_registry["rest"] = FindingsRefinementServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[FindingsRefinementServiceTransport]: + """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 FindingsRefinementServiceClient(metaclass=FindingsRefinementServiceClientMeta): + """FindingsRefinementService provides an interface for filtering + out findings that are unlikely to be real threats to prevent + them from triggering alerts or notifications. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """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: + Optional[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) + if m is None: + # Could not parse api_endpoint; return as-is. + return 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 = "chronicle.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "chronicle.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FindingsRefinementServiceClient: 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: + FindingsRefinementServiceClient: 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) -> FindingsRefinementServiceTransport: + """Returns the transport used by the client instance. + + Returns: + FindingsRefinementServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def curated_rule_path( + project: str, + location: str, + instance: str, + curatedRule: str, + ) -> str: + """Returns a fully-qualified curated_rule string.""" + return "projects/{project}/locations/{location}/instances/{instance}/curatedRules/{curatedRule}".format( + project=project, + location=location, + instance=instance, + curatedRule=curatedRule, + ) + + @staticmethod + def parse_curated_rule_path(path: str) -> Dict[str, str]: + """Parses a curated_rule path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/curatedRules/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def curated_rule_set_path( + project: str, + location: str, + instance: str, + category: str, + rule_set: str, + ) -> str: + """Returns a fully-qualified curated_rule_set string.""" + return "projects/{project}/locations/{location}/instances/{instance}/curatedRuleSetCategories/{category}/curatedRuleSets/{rule_set}".format( + project=project, + location=location, + instance=instance, + category=category, + rule_set=rule_set, + ) + + @staticmethod + def parse_curated_rule_set_path(path: str) -> Dict[str, str]: + """Parses a curated_rule_set path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/curatedRuleSetCategories/(?P.+?)/curatedRuleSets/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def findings_refinement_path( + project: str, + location: str, + instance: str, + findings_refinement: str, + ) -> str: + """Returns a fully-qualified findings_refinement string.""" + return "projects/{project}/locations/{location}/instances/{instance}/findingsRefinements/{findings_refinement}".format( + project=project, + location=location, + instance=instance, + findings_refinement=findings_refinement, + ) + + @staticmethod + def parse_findings_refinement_path(path: str) -> Dict[str, str]: + """Parses a findings_refinement path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/findingsRefinements/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def findings_refinement_deployment_path( + project: str, + location: str, + instance: str, + findings_refinement: str, + ) -> str: + """Returns a fully-qualified findings_refinement_deployment string.""" + return "projects/{project}/locations/{location}/instances/{instance}/findingsRefinements/{findings_refinement}/deployment".format( + project=project, + location=location, + instance=instance, + findings_refinement=findings_refinement, + ) + + @staticmethod + def parse_findings_refinement_deployment_path(path: str) -> Dict[str, str]: + """Parses a findings_refinement_deployment path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/findingsRefinements/(?P.+?)/deployment$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def instance_path( + project: str, + location: str, + instance: str, + ) -> str: + """Returns a fully-qualified instance string.""" + return "projects/{project}/locations/{location}/instances/{instance}".format( + project=project, + location=location, + instance=instance, + ) + + @staticmethod + def parse_instance_path(path: str) -> Dict[str, str]: + """Parses a instance path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def rule_path( + project: str, + location: str, + instance: str, + rule: str, + ) -> str: + """Returns a fully-qualified rule string.""" + return "projects/{project}/locations/{location}/instances/{instance}/rules/{rule}".format( + project=project, + location=location, + instance=instance, + rule=rule, + ) + + @staticmethod + def parse_rule_path(path: str) -> Dict[str, str]: + """Parses a rule path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/rules/(?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 = FindingsRefinementServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + 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: + 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 = FindingsRefinementServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + 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, 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 + ) -> str: + """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 = FindingsRefinementServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = FindingsRefinementServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ( + FindingsRefinementServiceClient._DEFAULT_ENDPOINT_TEMPLATE.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 = FindingsRefinementServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """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, + FindingsRefinementServiceTransport, + Callable[..., FindingsRefinementServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the findings refinement service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,FindingsRefinementServiceTransport,Callable[..., FindingsRefinementServiceTransport]]]): + 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 FindingsRefinementServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = ( + FindingsRefinementServiceClient._read_environment_variables() + ) + self._client_cert_source = ( + FindingsRefinementServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = FindingsRefinementServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, FindingsRefinementServiceTransport) + if transport_provided: + # transport is a FindingsRefinementServiceTransport 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(FindingsRefinementServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or FindingsRefinementServiceClient._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[FindingsRefinementServiceTransport], + Callable[..., FindingsRefinementServiceTransport], + ] = ( + FindingsRefinementServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., FindingsRefinementServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.chronicle_v1.FindingsRefinementServiceClient`.", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "credentialsType": None, + }, + ) + + def get_findings_refinement( + self, + request: Optional[ + Union[findings_refinement.GetFindingsRefinementRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> findings_refinement.FindingsRefinement: + r"""Gets a single findings refinement. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import chronicle_v1 + + def sample_get_findings_refinement(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceClient() + + # Initialize request argument(s) + request = chronicle_v1.GetFindingsRefinementRequest( + name="name_value", + ) + + # Make the request + response = client.get_findings_refinement(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.chronicle_v1.types.GetFindingsRefinementRequest, dict]): + The request object. Request message for + GetFindingsRefinement method. + name (str): + Required. The name of the findings refinement to + retrieve. Format: + projects/{project}/locations/{location}/instances/{instance}/findingsRefinements/{findings_refinement} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.chronicle_v1.types.FindingsRefinement: + Represents a set of logic conditions + used to refine various types of findings + such as curated rule detections. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, findings_refinement.GetFindingsRefinementRequest): + request = findings_refinement.GetFindingsRefinementRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_findings_refinement] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_findings_refinements( + self, + request: Optional[ + Union[findings_refinement.ListFindingsRefinementsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListFindingsRefinementsPager: + r"""Lists a collection of findings refinements. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import chronicle_v1 + + def sample_list_findings_refinements(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceClient() + + # Initialize request argument(s) + request = chronicle_v1.ListFindingsRefinementsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings_refinements(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.chronicle_v1.types.ListFindingsRefinementsRequest, dict]): + The request object. Request message for + ListFindingsRefinements method. + parent (str): + Required. The parent, which owns this + collection of findings refinements. + Format: + + projects/{project}/locations/{location}/instances/{instance} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.chronicle_v1.services.findings_refinement_service.pagers.ListFindingsRefinementsPager: + Response message for + ListFindingsRefinements method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, findings_refinement.ListFindingsRefinementsRequest): + request = findings_refinement.ListFindingsRefinementsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + 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_refinements + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListFindingsRefinementsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_findings_refinement( + self, + request: Optional[ + Union[gcc_findings_refinement.CreateFindingsRefinementRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + findings_refinement: Optional[ + gcc_findings_refinement.FindingsRefinement + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_findings_refinement.FindingsRefinement: + r"""Creates a new findings refinement. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import chronicle_v1 + + def sample_create_findings_refinement(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceClient() + + # Initialize request argument(s) + request = chronicle_v1.CreateFindingsRefinementRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_findings_refinement(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.chronicle_v1.types.CreateFindingsRefinementRequest, dict]): + The request object. Request message for + CreateFindingsRefinement method. + parent (str): + Required. The parent resource where + this findings refinement will be + created. Format: + + projects/{project}/locations/{location}/instances/{instance} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + findings_refinement (google.cloud.chronicle_v1.types.FindingsRefinement): + Required. The findings refinement to + create. + + This corresponds to the ``findings_refinement`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.chronicle_v1.types.FindingsRefinement: + Represents a set of logic conditions + used to refine various types of findings + such as curated rule detections. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, findings_refinement] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, gcc_findings_refinement.CreateFindingsRefinementRequest + ): + request = gcc_findings_refinement.CreateFindingsRefinementRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if findings_refinement is not None: + request.findings_refinement = findings_refinement + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_findings_refinement + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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_findings_refinement( + self, + request: Optional[ + Union[gcc_findings_refinement.UpdateFindingsRefinementRequest, dict] + ] = None, + *, + findings_refinement: Optional[ + gcc_findings_refinement.FindingsRefinement + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_findings_refinement.FindingsRefinement: + r"""Updates a findings refinement. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import chronicle_v1 + + def sample_update_findings_refinement(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceClient() + + # Initialize request argument(s) + request = chronicle_v1.UpdateFindingsRefinementRequest( + ) + + # Make the request + response = client.update_findings_refinement(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.chronicle_v1.types.UpdateFindingsRefinementRequest, dict]): + The request object. Request message for + UpdateFindingsRefinement method. + findings_refinement (google.cloud.chronicle_v1.types.FindingsRefinement): + Required. The findings refinement to update. + + The findings refinement's ``name`` field is used to + identify the findings refinement to update. Format: + projects/{project}/locations/{location}/instances/{instance}/findingsRefinements/{findings_refinement} + + This corresponds to the ``findings_refinement`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. If ``*`` is + provided, all 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.chronicle_v1.types.FindingsRefinement: + Represents a set of logic conditions + used to refine various types of findings + such as curated rule detections. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [findings_refinement, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, gcc_findings_refinement.UpdateFindingsRefinementRequest + ): + request = gcc_findings_refinement.UpdateFindingsRefinementRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if findings_refinement is not None: + request.findings_refinement = findings_refinement + if update_mask 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_findings_refinement + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("findings_refinement.name", request.findings_refinement.name),) + ), + ) + + # Validate the universe 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_findings_refinement_deployment( + self, + request: Optional[ + Union[findings_refinement.GetFindingsRefinementDeploymentRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> findings_refinement.FindingsRefinementDeployment: + r"""Gets a findings refinement deployment. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import chronicle_v1 + + def sample_get_findings_refinement_deployment(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceClient() + + # Initialize request argument(s) + request = chronicle_v1.GetFindingsRefinementDeploymentRequest( + name="name_value", + ) + + # Make the request + response = client.get_findings_refinement_deployment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.chronicle_v1.types.GetFindingsRefinementDeploymentRequest, dict]): + The request object. Request message for + GetFindingsRefinementDeployment method. + name (str): + Required. The name of the findings refinement to + retrieve. Format: + projects/{project}/locations/{location}/instances/{instance}/findingsRefinements/{findings_refinement}/deployment + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.chronicle_v1.types.FindingsRefinementDeployment: + The FindingsRefinementDeployment + resource represents the deployment state + of a findings refinement. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, findings_refinement.GetFindingsRefinementDeploymentRequest + ): + request = findings_refinement.GetFindingsRefinementDeploymentRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.get_findings_refinement_deployment + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe 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_findings_refinement_deployment( + self, + request: Optional[ + Union[findings_refinement.UpdateFindingsRefinementDeploymentRequest, dict] + ] = None, + *, + findings_refinement_deployment: Optional[ + findings_refinement.FindingsRefinementDeployment + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> findings_refinement.FindingsRefinementDeployment: + r"""Updates a findings refinement deployment. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import chronicle_v1 + + def sample_update_findings_refinement_deployment(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceClient() + + # Initialize request argument(s) + findings_refinement_deployment = chronicle_v1.FindingsRefinementDeployment() + findings_refinement_deployment.name = "name_value" + + request = chronicle_v1.UpdateFindingsRefinementDeploymentRequest( + findings_refinement_deployment=findings_refinement_deployment, + ) + + # Make the request + response = client.update_findings_refinement_deployment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.chronicle_v1.types.UpdateFindingsRefinementDeploymentRequest, dict]): + The request object. Request message for + UpdateFindingsRefinementDeployment + method. + findings_refinement_deployment (google.cloud.chronicle_v1.types.FindingsRefinementDeployment): + Required. The findings refinement deployment to update. + + The findings refinement deployment's ``name`` field is + used to identify the findings refinement deployment to + update. Format: + projects/{project}/locations/{location}/instances/{instance}/findingsRefinements/{findings_refinement}/deployment + + This corresponds to the ``findings_refinement_deployment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. If ``*`` is + provided, all 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.chronicle_v1.types.FindingsRefinementDeployment: + The FindingsRefinementDeployment + resource represents the deployment state + of a findings refinement. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [findings_refinement_deployment, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, findings_refinement.UpdateFindingsRefinementDeploymentRequest + ): + request = findings_refinement.UpdateFindingsRefinementDeploymentRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if findings_refinement_deployment is not None: + request.findings_refinement_deployment = findings_refinement_deployment + if update_mask 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_findings_refinement_deployment + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ( + "findings_refinement_deployment.name", + request.findings_refinement_deployment.name, + ), + ) + ), + ) + + # Validate the universe 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_all_findings_refinement_deployments( + self, + request: Optional[ + Union[findings_refinement.ListAllFindingsRefinementDeploymentsRequest, dict] + ] = None, + *, + instance: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAllFindingsRefinementDeploymentsPager: + r"""Lists all findings refinement deployments. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import chronicle_v1 + + def sample_list_all_findings_refinement_deployments(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceClient() + + # Initialize request argument(s) + request = chronicle_v1.ListAllFindingsRefinementDeploymentsRequest( + instance="instance_value", + ) + + # Make the request + page_result = client.list_all_findings_refinement_deployments(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.chronicle_v1.types.ListAllFindingsRefinementDeploymentsRequest, dict]): + The request object. Request message for + ListAllFindingsRefinementDeployments + method. + instance (str): + Required. The name of the parent + resource, which is the SecOps instance + to list all findings refinement + deployments over. Format: + + projects/{project}/locations/{location}/instances/{instance} + + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.chronicle_v1.services.findings_refinement_service.pagers.ListAllFindingsRefinementDeploymentsPager: + Response message for + ListAllFindingsRefinementDeployments + method. Iterating over this object will + yield results and resolve additional + pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [instance] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, findings_refinement.ListAllFindingsRefinementDeploymentsRequest + ): + request = findings_refinement.ListAllFindingsRefinementDeploymentsRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if instance is not None: + request.instance = instance + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_all_findings_refinement_deployments + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("instance", request.instance),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAllFindingsRefinementDeploymentsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def compute_findings_refinement_activity( + self, + request: Optional[ + Union[findings_refinement.ComputeFindingsRefinementActivityRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> findings_refinement.ComputeFindingsRefinementActivityResponse: + r"""Returns findings refinement activity for a specific + findings refinement. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import chronicle_v1 + + def sample_compute_findings_refinement_activity(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceClient() + + # Initialize request argument(s) + request = chronicle_v1.ComputeFindingsRefinementActivityRequest( + name="name_value", + ) + + # Make the request + response = client.compute_findings_refinement_activity(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.chronicle_v1.types.ComputeFindingsRefinementActivityRequest, dict]): + The request object. Request message for + ComputeFindingsRefinementActivity + method. + name (str): + Required. Full resource name for the findings refinement + to fetch the activity for. Format: + projects/{project}/locations/{region}/instances/{instance}/findingsRefinements/{findings_refinement} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.chronicle_v1.types.ComputeFindingsRefinementActivityResponse: + Response message for + ComputeFindingsRefinementActivity + method. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, findings_refinement.ComputeFindingsRefinementActivityRequest + ): + request = findings_refinement.ComputeFindingsRefinementActivityRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.compute_findings_refinement_activity + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def compute_all_findings_refinement_activities( + self, + request: Optional[ + Union[ + findings_refinement.ComputeAllFindingsRefinementActivitiesRequest, dict + ] + ] = None, + *, + instance: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> findings_refinement.ComputeAllFindingsRefinementActivitiesResponse: + r"""Returns findings refinement activity for all findings + refinements. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import chronicle_v1 + + def sample_compute_all_findings_refinement_activities(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceClient() + + # Initialize request argument(s) + request = chronicle_v1.ComputeAllFindingsRefinementActivitiesRequest( + instance="instance_value", + ) + + # Make the request + response = client.compute_all_findings_refinement_activities(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.chronicle_v1.types.ComputeAllFindingsRefinementActivitiesRequest, dict]): + The request object. Request message for + ComputeAllFindingsRefinementActivities + method. + instance (str): + Required. The ID of the Instance to + retrieve counts for. Format: + + projects/{project}/locations/{location}/instances/{instance} + + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.chronicle_v1.types.ComputeAllFindingsRefinementActivitiesResponse: + Response message for + ComputeAllFindingsRefinementActivities + method. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [instance] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, findings_refinement.ComputeAllFindingsRefinementActivitiesRequest + ): + request = findings_refinement.ComputeAllFindingsRefinementActivitiesRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if instance is not None: + request.instance = instance + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.compute_all_findings_refinement_activities + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("instance", request.instance),)), + ) + + # Validate the universe 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) -> "FindingsRefinementServiceClient": + 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[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.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 request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[Union[operations_pb2.DeleteOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.DeleteOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.DeleteOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + 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 request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("FindingsRefinementServiceClient",) diff --git a/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/pagers.py b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/pagers.py new file mode 100644 index 000000000000..0d0a4a4452b8 --- /dev/null +++ b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/pagers.py @@ -0,0 +1,374 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +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.chronicle_v1.types import findings_refinement + + +class ListFindingsRefinementsPager: + """A pager for iterating through ``list_findings_refinements`` requests. + + This class thinly wraps an initial + :class:`google.cloud.chronicle_v1.types.ListFindingsRefinementsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``findings_refinements`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFindingsRefinements`` requests and continue to iterate + through the ``findings_refinements`` field on the + corresponding responses. + + All the usual :class:`google.cloud.chronicle_v1.types.ListFindingsRefinementsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., findings_refinement.ListFindingsRefinementsResponse], + request: findings_refinement.ListFindingsRefinementsRequest, + response: findings_refinement.ListFindingsRefinementsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.chronicle_v1.types.ListFindingsRefinementsRequest): + The initial request object. + response (google.cloud.chronicle_v1.types.ListFindingsRefinementsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = findings_refinement.ListFindingsRefinementsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[findings_refinement.ListFindingsRefinementsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[findings_refinement.FindingsRefinement]: + for page in self.pages: + yield from page.findings_refinements + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListFindingsRefinementsAsyncPager: + """A pager for iterating through ``list_findings_refinements`` requests. + + This class thinly wraps an initial + :class:`google.cloud.chronicle_v1.types.ListFindingsRefinementsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``findings_refinements`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFindingsRefinements`` requests and continue to iterate + through the ``findings_refinements`` field on the + corresponding responses. + + All the usual :class:`google.cloud.chronicle_v1.types.ListFindingsRefinementsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[findings_refinement.ListFindingsRefinementsResponse] + ], + request: findings_refinement.ListFindingsRefinementsRequest, + response: findings_refinement.ListFindingsRefinementsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.chronicle_v1.types.ListFindingsRefinementsRequest): + The initial request object. + response (google.cloud.chronicle_v1.types.ListFindingsRefinementsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = findings_refinement.ListFindingsRefinementsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[findings_refinement.ListFindingsRefinementsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[findings_refinement.FindingsRefinement]: + async def async_generator(): + async for page in self.pages: + for response in page.findings_refinements: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAllFindingsRefinementDeploymentsPager: + """A pager for iterating through ``list_all_findings_refinement_deployments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.chronicle_v1.types.ListAllFindingsRefinementDeploymentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``all_findings_refinement_deployments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAllFindingsRefinementDeployments`` requests and continue to iterate + through the ``all_findings_refinement_deployments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.chronicle_v1.types.ListAllFindingsRefinementDeploymentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., findings_refinement.ListAllFindingsRefinementDeploymentsResponse + ], + request: findings_refinement.ListAllFindingsRefinementDeploymentsRequest, + response: findings_refinement.ListAllFindingsRefinementDeploymentsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.chronicle_v1.types.ListAllFindingsRefinementDeploymentsRequest): + The initial request object. + response (google.cloud.chronicle_v1.types.ListAllFindingsRefinementDeploymentsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = findings_refinement.ListAllFindingsRefinementDeploymentsRequest( + request + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[findings_refinement.ListAllFindingsRefinementDeploymentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[findings_refinement.FindingsRefinementDeployment]: + for page in self.pages: + yield from page.all_findings_refinement_deployments + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAllFindingsRefinementDeploymentsAsyncPager: + """A pager for iterating through ``list_all_findings_refinement_deployments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.chronicle_v1.types.ListAllFindingsRefinementDeploymentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``all_findings_refinement_deployments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAllFindingsRefinementDeployments`` requests and continue to iterate + through the ``all_findings_refinement_deployments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.chronicle_v1.types.ListAllFindingsRefinementDeploymentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., + Awaitable[findings_refinement.ListAllFindingsRefinementDeploymentsResponse], + ], + request: findings_refinement.ListAllFindingsRefinementDeploymentsRequest, + response: findings_refinement.ListAllFindingsRefinementDeploymentsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.chronicle_v1.types.ListAllFindingsRefinementDeploymentsRequest): + The initial request object. + response (google.cloud.chronicle_v1.types.ListAllFindingsRefinementDeploymentsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = findings_refinement.ListAllFindingsRefinementDeploymentsRequest( + request + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[ + findings_refinement.ListAllFindingsRefinementDeploymentsResponse + ]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__( + self, + ) -> AsyncIterator[findings_refinement.FindingsRefinementDeployment]: + async def async_generator(): + async for page in self.pages: + for response in page.all_findings_refinement_deployments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/README.rst b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/README.rst new file mode 100644 index 000000000000..862929747327 --- /dev/null +++ b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``FindingsRefinementServiceTransport`` is the ABC for all transports. + +- public child ``FindingsRefinementServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``FindingsRefinementServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseFindingsRefinementServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``FindingsRefinementServiceRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/__init__.py b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/__init__.py new file mode 100644 index 000000000000..2af92d9ea8bd --- /dev/null +++ b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/__init__.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 FindingsRefinementServiceTransport +from .grpc import FindingsRefinementServiceGrpcTransport +from .grpc_asyncio import FindingsRefinementServiceGrpcAsyncIOTransport +from .rest import ( + FindingsRefinementServiceRestInterceptor, + FindingsRefinementServiceRestTransport, +) + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[FindingsRefinementServiceTransport]] +_transport_registry["grpc"] = FindingsRefinementServiceGrpcTransport +_transport_registry["grpc_asyncio"] = FindingsRefinementServiceGrpcAsyncIOTransport +_transport_registry["rest"] = FindingsRefinementServiceRestTransport + +__all__ = ( + "FindingsRefinementServiceTransport", + "FindingsRefinementServiceGrpcTransport", + "FindingsRefinementServiceGrpcAsyncIOTransport", + "FindingsRefinementServiceRestTransport", + "FindingsRefinementServiceRestInterceptor", +) diff --git a/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/base.py b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/base.py new file mode 100644 index 000000000000..7ee0901c4ddd --- /dev/null +++ b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/base.py @@ -0,0 +1,455 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.chronicle_v1 import gapic_version as package_version +from google.cloud.chronicle_v1.types import findings_refinement +from google.cloud.chronicle_v1.types import ( + findings_refinement as gcc_findings_refinement, +) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class FindingsRefinementServiceTransport(abc.ABC): + """Abstract transport class for FindingsRefinementService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/chronicle", + "https://www.googleapis.com/auth/chronicle.readonly", + "https://www.googleapis.com/auth/cloud-platform", + ) + + DEFAULT_HOST: str = "chronicle.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.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: 'chronicle.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # 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=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_findings_refinement: gapic_v1.method.wrap_method( + self.get_findings_refinement, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_findings_refinements: gapic_v1.method.wrap_method( + self.list_findings_refinements, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_findings_refinement: gapic_v1.method.wrap_method( + self.create_findings_refinement, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_findings_refinement: gapic_v1.method.wrap_method( + self.update_findings_refinement, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_findings_refinement_deployment: gapic_v1.method.wrap_method( + self.get_findings_refinement_deployment, + default_retry=retries.Retry( + initial=1.0, + maximum=120.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.update_findings_refinement_deployment: gapic_v1.method.wrap_method( + self.update_findings_refinement_deployment, + default_timeout=120.0, + client_info=client_info, + ), + self.list_all_findings_refinement_deployments: gapic_v1.method.wrap_method( + self.list_all_findings_refinement_deployments, + default_retry=retries.Retry( + initial=1.0, + maximum=120.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.compute_findings_refinement_activity: gapic_v1.method.wrap_method( + self.compute_findings_refinement_activity, + default_retry=retries.Retry( + initial=1.0, + maximum=600.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.compute_all_findings_refinement_activities: gapic_v1.method.wrap_method( + self.compute_all_findings_refinement_activities, + default_retry=retries.Retry( + initial=1.0, + maximum=600.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get_findings_refinement( + self, + ) -> Callable[ + [findings_refinement.GetFindingsRefinementRequest], + Union[ + findings_refinement.FindingsRefinement, + Awaitable[findings_refinement.FindingsRefinement], + ], + ]: + raise NotImplementedError() + + @property + def list_findings_refinements( + self, + ) -> Callable[ + [findings_refinement.ListFindingsRefinementsRequest], + Union[ + findings_refinement.ListFindingsRefinementsResponse, + Awaitable[findings_refinement.ListFindingsRefinementsResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_findings_refinement( + self, + ) -> Callable[ + [gcc_findings_refinement.CreateFindingsRefinementRequest], + Union[ + gcc_findings_refinement.FindingsRefinement, + Awaitable[gcc_findings_refinement.FindingsRefinement], + ], + ]: + raise NotImplementedError() + + @property + def update_findings_refinement( + self, + ) -> Callable[ + [gcc_findings_refinement.UpdateFindingsRefinementRequest], + Union[ + gcc_findings_refinement.FindingsRefinement, + Awaitable[gcc_findings_refinement.FindingsRefinement], + ], + ]: + raise NotImplementedError() + + @property + def get_findings_refinement_deployment( + self, + ) -> Callable[ + [findings_refinement.GetFindingsRefinementDeploymentRequest], + Union[ + findings_refinement.FindingsRefinementDeployment, + Awaitable[findings_refinement.FindingsRefinementDeployment], + ], + ]: + raise NotImplementedError() + + @property + def update_findings_refinement_deployment( + self, + ) -> Callable[ + [findings_refinement.UpdateFindingsRefinementDeploymentRequest], + Union[ + findings_refinement.FindingsRefinementDeployment, + Awaitable[findings_refinement.FindingsRefinementDeployment], + ], + ]: + raise NotImplementedError() + + @property + def list_all_findings_refinement_deployments( + self, + ) -> Callable[ + [findings_refinement.ListAllFindingsRefinementDeploymentsRequest], + Union[ + findings_refinement.ListAllFindingsRefinementDeploymentsResponse, + Awaitable[findings_refinement.ListAllFindingsRefinementDeploymentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def compute_findings_refinement_activity( + self, + ) -> Callable[ + [findings_refinement.ComputeFindingsRefinementActivityRequest], + Union[ + findings_refinement.ComputeFindingsRefinementActivityResponse, + Awaitable[findings_refinement.ComputeFindingsRefinementActivityResponse], + ], + ]: + raise NotImplementedError() + + @property + def compute_all_findings_refinement_activities( + self, + ) -> Callable[ + [findings_refinement.ComputeAllFindingsRefinementActivitiesRequest], + Union[ + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse, + Awaitable[ + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse + ], + ], + ]: + 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__ = ("FindingsRefinementServiceTransport",) diff --git a/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/grpc.py b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/grpc.py new file mode 100644 index 000000000000..6e476e3aa813 --- /dev/null +++ b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/grpc.py @@ -0,0 +1,694 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.chronicle_v1.types import findings_refinement +from google.cloud.chronicle_v1.types import ( + findings_refinement as gcc_findings_refinement, +) + +from .base import DEFAULT_CLIENT_INFO, FindingsRefinementServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class FindingsRefinementServiceGrpcTransport(FindingsRefinementServiceTransport): + """gRPC backend transport for FindingsRefinementService. + + FindingsRefinementService provides an interface for filtering + out findings that are unlikely to be real threats to prevent + them from triggering alerts or notifications. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = "chronicle.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'chronicle.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "chronicle.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def get_findings_refinement( + self, + ) -> Callable[ + [findings_refinement.GetFindingsRefinementRequest], + findings_refinement.FindingsRefinement, + ]: + r"""Return a callable for the get findings refinement method over gRPC. + + Gets a single findings refinement. + + Returns: + Callable[[~.GetFindingsRefinementRequest], + ~.FindingsRefinement]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_findings_refinement" not in self._stubs: + self._stubs["get_findings_refinement"] = self._logged_channel.unary_unary( + "/google.cloud.chronicle.v1.FindingsRefinementService/GetFindingsRefinement", + request_serializer=findings_refinement.GetFindingsRefinementRequest.serialize, + response_deserializer=findings_refinement.FindingsRefinement.deserialize, + ) + return self._stubs["get_findings_refinement"] + + @property + def list_findings_refinements( + self, + ) -> Callable[ + [findings_refinement.ListFindingsRefinementsRequest], + findings_refinement.ListFindingsRefinementsResponse, + ]: + r"""Return a callable for the list findings refinements method over gRPC. + + Lists a collection of findings refinements. + + Returns: + Callable[[~.ListFindingsRefinementsRequest], + ~.ListFindingsRefinementsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_refinements" not in self._stubs: + self._stubs["list_findings_refinements"] = self._logged_channel.unary_unary( + "/google.cloud.chronicle.v1.FindingsRefinementService/ListFindingsRefinements", + request_serializer=findings_refinement.ListFindingsRefinementsRequest.serialize, + response_deserializer=findings_refinement.ListFindingsRefinementsResponse.deserialize, + ) + return self._stubs["list_findings_refinements"] + + @property + def create_findings_refinement( + self, + ) -> Callable[ + [gcc_findings_refinement.CreateFindingsRefinementRequest], + gcc_findings_refinement.FindingsRefinement, + ]: + r"""Return a callable for the create findings refinement method over gRPC. + + Creates a new findings refinement. + + Returns: + Callable[[~.CreateFindingsRefinementRequest], + ~.FindingsRefinement]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_findings_refinement" not in self._stubs: + self._stubs["create_findings_refinement"] = ( + self._logged_channel.unary_unary( + "/google.cloud.chronicle.v1.FindingsRefinementService/CreateFindingsRefinement", + request_serializer=gcc_findings_refinement.CreateFindingsRefinementRequest.serialize, + response_deserializer=gcc_findings_refinement.FindingsRefinement.deserialize, + ) + ) + return self._stubs["create_findings_refinement"] + + @property + def update_findings_refinement( + self, + ) -> Callable[ + [gcc_findings_refinement.UpdateFindingsRefinementRequest], + gcc_findings_refinement.FindingsRefinement, + ]: + r"""Return a callable for the update findings refinement method over gRPC. + + Updates a findings refinement. + + Returns: + Callable[[~.UpdateFindingsRefinementRequest], + ~.FindingsRefinement]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_findings_refinement" not in self._stubs: + self._stubs["update_findings_refinement"] = ( + self._logged_channel.unary_unary( + "/google.cloud.chronicle.v1.FindingsRefinementService/UpdateFindingsRefinement", + request_serializer=gcc_findings_refinement.UpdateFindingsRefinementRequest.serialize, + response_deserializer=gcc_findings_refinement.FindingsRefinement.deserialize, + ) + ) + return self._stubs["update_findings_refinement"] + + @property + def get_findings_refinement_deployment( + self, + ) -> Callable[ + [findings_refinement.GetFindingsRefinementDeploymentRequest], + findings_refinement.FindingsRefinementDeployment, + ]: + r"""Return a callable for the get findings refinement + deployment method over gRPC. + + Gets a findings refinement deployment. + + Returns: + Callable[[~.GetFindingsRefinementDeploymentRequest], + ~.FindingsRefinementDeployment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_findings_refinement_deployment" not in self._stubs: + self._stubs["get_findings_refinement_deployment"] = ( + self._logged_channel.unary_unary( + "/google.cloud.chronicle.v1.FindingsRefinementService/GetFindingsRefinementDeployment", + request_serializer=findings_refinement.GetFindingsRefinementDeploymentRequest.serialize, + response_deserializer=findings_refinement.FindingsRefinementDeployment.deserialize, + ) + ) + return self._stubs["get_findings_refinement_deployment"] + + @property + def update_findings_refinement_deployment( + self, + ) -> Callable[ + [findings_refinement.UpdateFindingsRefinementDeploymentRequest], + findings_refinement.FindingsRefinementDeployment, + ]: + r"""Return a callable for the update findings refinement + deployment method over gRPC. + + Updates a findings refinement deployment. + + Returns: + Callable[[~.UpdateFindingsRefinementDeploymentRequest], + ~.FindingsRefinementDeployment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_findings_refinement_deployment" not in self._stubs: + self._stubs["update_findings_refinement_deployment"] = ( + self._logged_channel.unary_unary( + "/google.cloud.chronicle.v1.FindingsRefinementService/UpdateFindingsRefinementDeployment", + request_serializer=findings_refinement.UpdateFindingsRefinementDeploymentRequest.serialize, + response_deserializer=findings_refinement.FindingsRefinementDeployment.deserialize, + ) + ) + return self._stubs["update_findings_refinement_deployment"] + + @property + def list_all_findings_refinement_deployments( + self, + ) -> Callable[ + [findings_refinement.ListAllFindingsRefinementDeploymentsRequest], + findings_refinement.ListAllFindingsRefinementDeploymentsResponse, + ]: + r"""Return a callable for the list all findings refinement + deployments method over gRPC. + + Lists all findings refinement deployments. + + Returns: + Callable[[~.ListAllFindingsRefinementDeploymentsRequest], + ~.ListAllFindingsRefinementDeploymentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_all_findings_refinement_deployments" not in self._stubs: + self._stubs["list_all_findings_refinement_deployments"] = ( + self._logged_channel.unary_unary( + "/google.cloud.chronicle.v1.FindingsRefinementService/ListAllFindingsRefinementDeployments", + request_serializer=findings_refinement.ListAllFindingsRefinementDeploymentsRequest.serialize, + response_deserializer=findings_refinement.ListAllFindingsRefinementDeploymentsResponse.deserialize, + ) + ) + return self._stubs["list_all_findings_refinement_deployments"] + + @property + def compute_findings_refinement_activity( + self, + ) -> Callable[ + [findings_refinement.ComputeFindingsRefinementActivityRequest], + findings_refinement.ComputeFindingsRefinementActivityResponse, + ]: + r"""Return a callable for the compute findings refinement + activity method over gRPC. + + Returns findings refinement activity for a specific + findings refinement. + + Returns: + Callable[[~.ComputeFindingsRefinementActivityRequest], + ~.ComputeFindingsRefinementActivityResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "compute_findings_refinement_activity" not in self._stubs: + self._stubs["compute_findings_refinement_activity"] = ( + self._logged_channel.unary_unary( + "/google.cloud.chronicle.v1.FindingsRefinementService/ComputeFindingsRefinementActivity", + request_serializer=findings_refinement.ComputeFindingsRefinementActivityRequest.serialize, + response_deserializer=findings_refinement.ComputeFindingsRefinementActivityResponse.deserialize, + ) + ) + return self._stubs["compute_findings_refinement_activity"] + + @property + def compute_all_findings_refinement_activities( + self, + ) -> Callable[ + [findings_refinement.ComputeAllFindingsRefinementActivitiesRequest], + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse, + ]: + r"""Return a callable for the compute all findings + refinement activities method over gRPC. + + Returns findings refinement activity for all findings + refinements. + + Returns: + Callable[[~.ComputeAllFindingsRefinementActivitiesRequest], + ~.ComputeAllFindingsRefinementActivitiesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "compute_all_findings_refinement_activities" not in self._stubs: + self._stubs["compute_all_findings_refinement_activities"] = ( + self._logged_channel.unary_unary( + "/google.cloud.chronicle.v1.FindingsRefinementService/ComputeAllFindingsRefinementActivities", + request_serializer=findings_refinement.ComputeAllFindingsRefinementActivitiesRequest.serialize, + response_deserializer=findings_refinement.ComputeAllFindingsRefinementActivitiesResponse.deserialize, + ) + ) + return self._stubs["compute_all_findings_refinement_activities"] + + def close(self): + self._logged_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._logged_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._logged_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._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def 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._logged_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__ = ("FindingsRefinementServiceGrpcTransport",) diff --git a/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/grpc_asyncio.py b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..7bdefb8199d3 --- /dev/null +++ b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/grpc_asyncio.py @@ -0,0 +1,849 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.chronicle_v1.types import findings_refinement +from google.cloud.chronicle_v1.types import ( + findings_refinement as gcc_findings_refinement, +) + +from .base import DEFAULT_CLIENT_INFO, FindingsRefinementServiceTransport +from .grpc import FindingsRefinementServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class FindingsRefinementServiceGrpcAsyncIOTransport(FindingsRefinementServiceTransport): + """gRPC AsyncIO backend transport for FindingsRefinementService. + + FindingsRefinementService provides an interface for filtering + out findings that are unlikely to be real threats to prevent + them from triggering alerts or notifications. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = "chronicle.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (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 = "chronicle.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'chronicle.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def get_findings_refinement( + self, + ) -> Callable[ + [findings_refinement.GetFindingsRefinementRequest], + Awaitable[findings_refinement.FindingsRefinement], + ]: + r"""Return a callable for the get findings refinement method over gRPC. + + Gets a single findings refinement. + + Returns: + Callable[[~.GetFindingsRefinementRequest], + Awaitable[~.FindingsRefinement]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_findings_refinement" not in self._stubs: + self._stubs["get_findings_refinement"] = self._logged_channel.unary_unary( + "/google.cloud.chronicle.v1.FindingsRefinementService/GetFindingsRefinement", + request_serializer=findings_refinement.GetFindingsRefinementRequest.serialize, + response_deserializer=findings_refinement.FindingsRefinement.deserialize, + ) + return self._stubs["get_findings_refinement"] + + @property + def list_findings_refinements( + self, + ) -> Callable[ + [findings_refinement.ListFindingsRefinementsRequest], + Awaitable[findings_refinement.ListFindingsRefinementsResponse], + ]: + r"""Return a callable for the list findings refinements method over gRPC. + + Lists a collection of findings refinements. + + Returns: + Callable[[~.ListFindingsRefinementsRequest], + Awaitable[~.ListFindingsRefinementsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly 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_refinements" not in self._stubs: + self._stubs["list_findings_refinements"] = self._logged_channel.unary_unary( + "/google.cloud.chronicle.v1.FindingsRefinementService/ListFindingsRefinements", + request_serializer=findings_refinement.ListFindingsRefinementsRequest.serialize, + response_deserializer=findings_refinement.ListFindingsRefinementsResponse.deserialize, + ) + return self._stubs["list_findings_refinements"] + + @property + def create_findings_refinement( + self, + ) -> Callable[ + [gcc_findings_refinement.CreateFindingsRefinementRequest], + Awaitable[gcc_findings_refinement.FindingsRefinement], + ]: + r"""Return a callable for the create findings refinement method over gRPC. + + Creates a new findings refinement. + + Returns: + Callable[[~.CreateFindingsRefinementRequest], + Awaitable[~.FindingsRefinement]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_findings_refinement" not in self._stubs: + self._stubs["create_findings_refinement"] = ( + self._logged_channel.unary_unary( + "/google.cloud.chronicle.v1.FindingsRefinementService/CreateFindingsRefinement", + request_serializer=gcc_findings_refinement.CreateFindingsRefinementRequest.serialize, + response_deserializer=gcc_findings_refinement.FindingsRefinement.deserialize, + ) + ) + return self._stubs["create_findings_refinement"] + + @property + def update_findings_refinement( + self, + ) -> Callable[ + [gcc_findings_refinement.UpdateFindingsRefinementRequest], + Awaitable[gcc_findings_refinement.FindingsRefinement], + ]: + r"""Return a callable for the update findings refinement method over gRPC. + + Updates a findings refinement. + + Returns: + Callable[[~.UpdateFindingsRefinementRequest], + Awaitable[~.FindingsRefinement]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_findings_refinement" not in self._stubs: + self._stubs["update_findings_refinement"] = ( + self._logged_channel.unary_unary( + "/google.cloud.chronicle.v1.FindingsRefinementService/UpdateFindingsRefinement", + request_serializer=gcc_findings_refinement.UpdateFindingsRefinementRequest.serialize, + response_deserializer=gcc_findings_refinement.FindingsRefinement.deserialize, + ) + ) + return self._stubs["update_findings_refinement"] + + @property + def get_findings_refinement_deployment( + self, + ) -> Callable[ + [findings_refinement.GetFindingsRefinementDeploymentRequest], + Awaitable[findings_refinement.FindingsRefinementDeployment], + ]: + r"""Return a callable for the get findings refinement + deployment method over gRPC. + + Gets a findings refinement deployment. + + Returns: + Callable[[~.GetFindingsRefinementDeploymentRequest], + Awaitable[~.FindingsRefinementDeployment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_findings_refinement_deployment" not in self._stubs: + self._stubs["get_findings_refinement_deployment"] = ( + self._logged_channel.unary_unary( + "/google.cloud.chronicle.v1.FindingsRefinementService/GetFindingsRefinementDeployment", + request_serializer=findings_refinement.GetFindingsRefinementDeploymentRequest.serialize, + response_deserializer=findings_refinement.FindingsRefinementDeployment.deserialize, + ) + ) + return self._stubs["get_findings_refinement_deployment"] + + @property + def update_findings_refinement_deployment( + self, + ) -> Callable[ + [findings_refinement.UpdateFindingsRefinementDeploymentRequest], + Awaitable[findings_refinement.FindingsRefinementDeployment], + ]: + r"""Return a callable for the update findings refinement + deployment method over gRPC. + + Updates a findings refinement deployment. + + Returns: + Callable[[~.UpdateFindingsRefinementDeploymentRequest], + Awaitable[~.FindingsRefinementDeployment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_findings_refinement_deployment" not in self._stubs: + self._stubs["update_findings_refinement_deployment"] = ( + self._logged_channel.unary_unary( + "/google.cloud.chronicle.v1.FindingsRefinementService/UpdateFindingsRefinementDeployment", + request_serializer=findings_refinement.UpdateFindingsRefinementDeploymentRequest.serialize, + response_deserializer=findings_refinement.FindingsRefinementDeployment.deserialize, + ) + ) + return self._stubs["update_findings_refinement_deployment"] + + @property + def list_all_findings_refinement_deployments( + self, + ) -> Callable[ + [findings_refinement.ListAllFindingsRefinementDeploymentsRequest], + Awaitable[findings_refinement.ListAllFindingsRefinementDeploymentsResponse], + ]: + r"""Return a callable for the list all findings refinement + deployments method over gRPC. + + Lists all findings refinement deployments. + + Returns: + Callable[[~.ListAllFindingsRefinementDeploymentsRequest], + Awaitable[~.ListAllFindingsRefinementDeploymentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_all_findings_refinement_deployments" not in self._stubs: + self._stubs["list_all_findings_refinement_deployments"] = ( + self._logged_channel.unary_unary( + "/google.cloud.chronicle.v1.FindingsRefinementService/ListAllFindingsRefinementDeployments", + request_serializer=findings_refinement.ListAllFindingsRefinementDeploymentsRequest.serialize, + response_deserializer=findings_refinement.ListAllFindingsRefinementDeploymentsResponse.deserialize, + ) + ) + return self._stubs["list_all_findings_refinement_deployments"] + + @property + def compute_findings_refinement_activity( + self, + ) -> Callable[ + [findings_refinement.ComputeFindingsRefinementActivityRequest], + Awaitable[findings_refinement.ComputeFindingsRefinementActivityResponse], + ]: + r"""Return a callable for the compute findings refinement + activity method over gRPC. + + Returns findings refinement activity for a specific + findings refinement. + + Returns: + Callable[[~.ComputeFindingsRefinementActivityRequest], + Awaitable[~.ComputeFindingsRefinementActivityResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "compute_findings_refinement_activity" not in self._stubs: + self._stubs["compute_findings_refinement_activity"] = ( + self._logged_channel.unary_unary( + "/google.cloud.chronicle.v1.FindingsRefinementService/ComputeFindingsRefinementActivity", + request_serializer=findings_refinement.ComputeFindingsRefinementActivityRequest.serialize, + response_deserializer=findings_refinement.ComputeFindingsRefinementActivityResponse.deserialize, + ) + ) + return self._stubs["compute_findings_refinement_activity"] + + @property + def compute_all_findings_refinement_activities( + self, + ) -> Callable[ + [findings_refinement.ComputeAllFindingsRefinementActivitiesRequest], + Awaitable[findings_refinement.ComputeAllFindingsRefinementActivitiesResponse], + ]: + r"""Return a callable for the compute all findings + refinement activities method over gRPC. + + Returns findings refinement activity for all findings + refinements. + + Returns: + Callable[[~.ComputeAllFindingsRefinementActivitiesRequest], + Awaitable[~.ComputeAllFindingsRefinementActivitiesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "compute_all_findings_refinement_activities" not in self._stubs: + self._stubs["compute_all_findings_refinement_activities"] = ( + self._logged_channel.unary_unary( + "/google.cloud.chronicle.v1.FindingsRefinementService/ComputeAllFindingsRefinementActivities", + request_serializer=findings_refinement.ComputeAllFindingsRefinementActivitiesRequest.serialize, + response_deserializer=findings_refinement.ComputeAllFindingsRefinementActivitiesResponse.deserialize, + ) + ) + return self._stubs["compute_all_findings_refinement_activities"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_findings_refinement: self._wrap_method( + self.get_findings_refinement, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_findings_refinements: self._wrap_method( + self.list_findings_refinements, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_findings_refinement: self._wrap_method( + self.create_findings_refinement, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_findings_refinement: self._wrap_method( + self.update_findings_refinement, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_findings_refinement_deployment: self._wrap_method( + self.get_findings_refinement_deployment, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=120.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.update_findings_refinement_deployment: self._wrap_method( + self.update_findings_refinement_deployment, + default_timeout=120.0, + client_info=client_info, + ), + self.list_all_findings_refinement_deployments: self._wrap_method( + self.list_all_findings_refinement_deployments, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=120.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=120.0, + ), + default_timeout=120.0, + client_info=client_info, + ), + self.compute_findings_refinement_activity: self._wrap_method( + self.compute_findings_refinement_activity, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=600.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.compute_all_findings_refinement_activities: self._wrap_method( + self.compute_all_findings_refinement_activities, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=600.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_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._logged_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._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def 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._logged_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__ = ("FindingsRefinementServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/rest.py b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/rest.py new file mode 100644 index 000000000000..e5fbbfa0cadd --- /dev/null +++ b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/rest.py @@ -0,0 +1,2913 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.chronicle_v1.types import findings_refinement +from google.cloud.chronicle_v1.types import ( + findings_refinement as gcc_findings_refinement, +) + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseFindingsRefinementServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class FindingsRefinementServiceRestInterceptor: + """Interceptor for FindingsRefinementService. + + 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 FindingsRefinementServiceRestTransport. + + .. code-block:: python + class MyCustomFindingsRefinementServiceInterceptor(FindingsRefinementServiceRestInterceptor): + def pre_compute_all_findings_refinement_activities(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_compute_all_findings_refinement_activities(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_compute_findings_refinement_activity(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_compute_findings_refinement_activity(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_findings_refinement(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_findings_refinement(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_findings_refinement(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_findings_refinement(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_findings_refinement_deployment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_findings_refinement_deployment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_all_findings_refinement_deployments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_all_findings_refinement_deployments(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_findings_refinements(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_findings_refinements(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_findings_refinement(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_findings_refinement(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_findings_refinement_deployment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_findings_refinement_deployment(self, response): + logging.log(f"Received response: {response}") + return response + + transport = FindingsRefinementServiceRestTransport(interceptor=MyCustomFindingsRefinementServiceInterceptor()) + client = FindingsRefinementServiceClient(transport=transport) + + + """ + + def pre_compute_all_findings_refinement_activities( + self, + request: findings_refinement.ComputeAllFindingsRefinementActivitiesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + findings_refinement.ComputeAllFindingsRefinementActivitiesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for compute_all_findings_refinement_activities + + Override in a subclass to manipulate the request or metadata + before they are sent to the FindingsRefinementService server. + """ + return request, metadata + + def post_compute_all_findings_refinement_activities( + self, + response: findings_refinement.ComputeAllFindingsRefinementActivitiesResponse, + ) -> findings_refinement.ComputeAllFindingsRefinementActivitiesResponse: + """Post-rpc interceptor for compute_all_findings_refinement_activities + + DEPRECATED. Please use the `post_compute_all_findings_refinement_activities_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the FindingsRefinementService server but before + it is returned to user code. This `post_compute_all_findings_refinement_activities` interceptor runs + before the `post_compute_all_findings_refinement_activities_with_metadata` interceptor. + """ + return response + + def post_compute_all_findings_refinement_activities_with_metadata( + self, + response: findings_refinement.ComputeAllFindingsRefinementActivitiesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for compute_all_findings_refinement_activities + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the FindingsRefinementService server but before it is returned to user code. + + We recommend only using this `post_compute_all_findings_refinement_activities_with_metadata` + interceptor in new development instead of the `post_compute_all_findings_refinement_activities` interceptor. + When both interceptors are used, this `post_compute_all_findings_refinement_activities_with_metadata` interceptor runs after the + `post_compute_all_findings_refinement_activities` interceptor. The (possibly modified) response returned by + `post_compute_all_findings_refinement_activities` will be passed to + `post_compute_all_findings_refinement_activities_with_metadata`. + """ + return response, metadata + + def pre_compute_findings_refinement_activity( + self, + request: findings_refinement.ComputeFindingsRefinementActivityRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + findings_refinement.ComputeFindingsRefinementActivityRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for compute_findings_refinement_activity + + Override in a subclass to manipulate the request or metadata + before they are sent to the FindingsRefinementService server. + """ + return request, metadata + + def post_compute_findings_refinement_activity( + self, response: findings_refinement.ComputeFindingsRefinementActivityResponse + ) -> findings_refinement.ComputeFindingsRefinementActivityResponse: + """Post-rpc interceptor for compute_findings_refinement_activity + + DEPRECATED. Please use the `post_compute_findings_refinement_activity_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the FindingsRefinementService server but before + it is returned to user code. This `post_compute_findings_refinement_activity` interceptor runs + before the `post_compute_findings_refinement_activity_with_metadata` interceptor. + """ + return response + + def post_compute_findings_refinement_activity_with_metadata( + self, + response: findings_refinement.ComputeFindingsRefinementActivityResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + findings_refinement.ComputeFindingsRefinementActivityResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for compute_findings_refinement_activity + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the FindingsRefinementService server but before it is returned to user code. + + We recommend only using this `post_compute_findings_refinement_activity_with_metadata` + interceptor in new development instead of the `post_compute_findings_refinement_activity` interceptor. + When both interceptors are used, this `post_compute_findings_refinement_activity_with_metadata` interceptor runs after the + `post_compute_findings_refinement_activity` interceptor. The (possibly modified) response returned by + `post_compute_findings_refinement_activity` will be passed to + `post_compute_findings_refinement_activity_with_metadata`. + """ + return response, metadata + + def pre_create_findings_refinement( + self, + request: gcc_findings_refinement.CreateFindingsRefinementRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcc_findings_refinement.CreateFindingsRefinementRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_findings_refinement + + Override in a subclass to manipulate the request or metadata + before they are sent to the FindingsRefinementService server. + """ + return request, metadata + + def post_create_findings_refinement( + self, response: gcc_findings_refinement.FindingsRefinement + ) -> gcc_findings_refinement.FindingsRefinement: + """Post-rpc interceptor for create_findings_refinement + + DEPRECATED. Please use the `post_create_findings_refinement_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the FindingsRefinementService server but before + it is returned to user code. This `post_create_findings_refinement` interceptor runs + before the `post_create_findings_refinement_with_metadata` interceptor. + """ + return response + + def post_create_findings_refinement_with_metadata( + self, + response: gcc_findings_refinement.FindingsRefinement, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcc_findings_refinement.FindingsRefinement, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for create_findings_refinement + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the FindingsRefinementService server but before it is returned to user code. + + We recommend only using this `post_create_findings_refinement_with_metadata` + interceptor in new development instead of the `post_create_findings_refinement` interceptor. + When both interceptors are used, this `post_create_findings_refinement_with_metadata` interceptor runs after the + `post_create_findings_refinement` interceptor. The (possibly modified) response returned by + `post_create_findings_refinement` will be passed to + `post_create_findings_refinement_with_metadata`. + """ + return response, metadata + + def pre_get_findings_refinement( + self, + request: findings_refinement.GetFindingsRefinementRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + findings_refinement.GetFindingsRefinementRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_findings_refinement + + Override in a subclass to manipulate the request or metadata + before they are sent to the FindingsRefinementService server. + """ + return request, metadata + + def post_get_findings_refinement( + self, response: findings_refinement.FindingsRefinement + ) -> findings_refinement.FindingsRefinement: + """Post-rpc interceptor for get_findings_refinement + + DEPRECATED. Please use the `post_get_findings_refinement_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the FindingsRefinementService server but before + it is returned to user code. This `post_get_findings_refinement` interceptor runs + before the `post_get_findings_refinement_with_metadata` interceptor. + """ + return response + + def post_get_findings_refinement_with_metadata( + self, + response: findings_refinement.FindingsRefinement, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + findings_refinement.FindingsRefinement, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_findings_refinement + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the FindingsRefinementService server but before it is returned to user code. + + We recommend only using this `post_get_findings_refinement_with_metadata` + interceptor in new development instead of the `post_get_findings_refinement` interceptor. + When both interceptors are used, this `post_get_findings_refinement_with_metadata` interceptor runs after the + `post_get_findings_refinement` interceptor. The (possibly modified) response returned by + `post_get_findings_refinement` will be passed to + `post_get_findings_refinement_with_metadata`. + """ + return response, metadata + + def pre_get_findings_refinement_deployment( + self, + request: findings_refinement.GetFindingsRefinementDeploymentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + findings_refinement.GetFindingsRefinementDeploymentRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_findings_refinement_deployment + + Override in a subclass to manipulate the request or metadata + before they are sent to the FindingsRefinementService server. + """ + return request, metadata + + def post_get_findings_refinement_deployment( + self, response: findings_refinement.FindingsRefinementDeployment + ) -> findings_refinement.FindingsRefinementDeployment: + """Post-rpc interceptor for get_findings_refinement_deployment + + DEPRECATED. Please use the `post_get_findings_refinement_deployment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the FindingsRefinementService server but before + it is returned to user code. This `post_get_findings_refinement_deployment` interceptor runs + before the `post_get_findings_refinement_deployment_with_metadata` interceptor. + """ + return response + + def post_get_findings_refinement_deployment_with_metadata( + self, + response: findings_refinement.FindingsRefinementDeployment, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + findings_refinement.FindingsRefinementDeployment, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_findings_refinement_deployment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the FindingsRefinementService server but before it is returned to user code. + + We recommend only using this `post_get_findings_refinement_deployment_with_metadata` + interceptor in new development instead of the `post_get_findings_refinement_deployment` interceptor. + When both interceptors are used, this `post_get_findings_refinement_deployment_with_metadata` interceptor runs after the + `post_get_findings_refinement_deployment` interceptor. The (possibly modified) response returned by + `post_get_findings_refinement_deployment` will be passed to + `post_get_findings_refinement_deployment_with_metadata`. + """ + return response, metadata + + def pre_list_all_findings_refinement_deployments( + self, + request: findings_refinement.ListAllFindingsRefinementDeploymentsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + findings_refinement.ListAllFindingsRefinementDeploymentsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_all_findings_refinement_deployments + + Override in a subclass to manipulate the request or metadata + before they are sent to the FindingsRefinementService server. + """ + return request, metadata + + def post_list_all_findings_refinement_deployments( + self, response: findings_refinement.ListAllFindingsRefinementDeploymentsResponse + ) -> findings_refinement.ListAllFindingsRefinementDeploymentsResponse: + """Post-rpc interceptor for list_all_findings_refinement_deployments + + DEPRECATED. Please use the `post_list_all_findings_refinement_deployments_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the FindingsRefinementService server but before + it is returned to user code. This `post_list_all_findings_refinement_deployments` interceptor runs + before the `post_list_all_findings_refinement_deployments_with_metadata` interceptor. + """ + return response + + def post_list_all_findings_refinement_deployments_with_metadata( + self, + response: findings_refinement.ListAllFindingsRefinementDeploymentsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + findings_refinement.ListAllFindingsRefinementDeploymentsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_all_findings_refinement_deployments + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the FindingsRefinementService server but before it is returned to user code. + + We recommend only using this `post_list_all_findings_refinement_deployments_with_metadata` + interceptor in new development instead of the `post_list_all_findings_refinement_deployments` interceptor. + When both interceptors are used, this `post_list_all_findings_refinement_deployments_with_metadata` interceptor runs after the + `post_list_all_findings_refinement_deployments` interceptor. The (possibly modified) response returned by + `post_list_all_findings_refinement_deployments` will be passed to + `post_list_all_findings_refinement_deployments_with_metadata`. + """ + return response, metadata + + def pre_list_findings_refinements( + self, + request: findings_refinement.ListFindingsRefinementsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + findings_refinement.ListFindingsRefinementsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_findings_refinements + + Override in a subclass to manipulate the request or metadata + before they are sent to the FindingsRefinementService server. + """ + return request, metadata + + def post_list_findings_refinements( + self, response: findings_refinement.ListFindingsRefinementsResponse + ) -> findings_refinement.ListFindingsRefinementsResponse: + """Post-rpc interceptor for list_findings_refinements + + DEPRECATED. Please use the `post_list_findings_refinements_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the FindingsRefinementService server but before + it is returned to user code. This `post_list_findings_refinements` interceptor runs + before the `post_list_findings_refinements_with_metadata` interceptor. + """ + return response + + def post_list_findings_refinements_with_metadata( + self, + response: findings_refinement.ListFindingsRefinementsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + findings_refinement.ListFindingsRefinementsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_findings_refinements + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the FindingsRefinementService server but before it is returned to user code. + + We recommend only using this `post_list_findings_refinements_with_metadata` + interceptor in new development instead of the `post_list_findings_refinements` interceptor. + When both interceptors are used, this `post_list_findings_refinements_with_metadata` interceptor runs after the + `post_list_findings_refinements` interceptor. The (possibly modified) response returned by + `post_list_findings_refinements` will be passed to + `post_list_findings_refinements_with_metadata`. + """ + return response, metadata + + def pre_update_findings_refinement( + self, + request: gcc_findings_refinement.UpdateFindingsRefinementRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcc_findings_refinement.UpdateFindingsRefinementRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_findings_refinement + + Override in a subclass to manipulate the request or metadata + before they are sent to the FindingsRefinementService server. + """ + return request, metadata + + def post_update_findings_refinement( + self, response: gcc_findings_refinement.FindingsRefinement + ) -> gcc_findings_refinement.FindingsRefinement: + """Post-rpc interceptor for update_findings_refinement + + DEPRECATED. Please use the `post_update_findings_refinement_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the FindingsRefinementService server but before + it is returned to user code. This `post_update_findings_refinement` interceptor runs + before the `post_update_findings_refinement_with_metadata` interceptor. + """ + return response + + def post_update_findings_refinement_with_metadata( + self, + response: gcc_findings_refinement.FindingsRefinement, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcc_findings_refinement.FindingsRefinement, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for update_findings_refinement + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the FindingsRefinementService server but before it is returned to user code. + + We recommend only using this `post_update_findings_refinement_with_metadata` + interceptor in new development instead of the `post_update_findings_refinement` interceptor. + When both interceptors are used, this `post_update_findings_refinement_with_metadata` interceptor runs after the + `post_update_findings_refinement` interceptor. The (possibly modified) response returned by + `post_update_findings_refinement` will be passed to + `post_update_findings_refinement_with_metadata`. + """ + return response, metadata + + def pre_update_findings_refinement_deployment( + self, + request: findings_refinement.UpdateFindingsRefinementDeploymentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + findings_refinement.UpdateFindingsRefinementDeploymentRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_findings_refinement_deployment + + Override in a subclass to manipulate the request or metadata + before they are sent to the FindingsRefinementService server. + """ + return request, metadata + + def post_update_findings_refinement_deployment( + self, response: findings_refinement.FindingsRefinementDeployment + ) -> findings_refinement.FindingsRefinementDeployment: + """Post-rpc interceptor for update_findings_refinement_deployment + + DEPRECATED. Please use the `post_update_findings_refinement_deployment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the FindingsRefinementService server but before + it is returned to user code. This `post_update_findings_refinement_deployment` interceptor runs + before the `post_update_findings_refinement_deployment_with_metadata` interceptor. + """ + return response + + def post_update_findings_refinement_deployment_with_metadata( + self, + response: findings_refinement.FindingsRefinementDeployment, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + findings_refinement.FindingsRefinementDeployment, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for update_findings_refinement_deployment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the FindingsRefinementService server but before it is returned to user code. + + We recommend only using this `post_update_findings_refinement_deployment_with_metadata` + interceptor in new development instead of the `post_update_findings_refinement_deployment` interceptor. + When both interceptors are used, this `post_update_findings_refinement_deployment_with_metadata` interceptor runs after the + `post_update_findings_refinement_deployment` interceptor. The (possibly modified) response returned by + `post_update_findings_refinement_deployment` will be passed to + `post_update_findings_refinement_deployment_with_metadata`. + """ + return response, metadata + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the FindingsRefinementService 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 FindingsRefinementService server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the FindingsRefinementService 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 FindingsRefinementService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the FindingsRefinementService 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 FindingsRefinementService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the FindingsRefinementService 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 FindingsRefinementService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class FindingsRefinementServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: FindingsRefinementServiceRestInterceptor + + +class FindingsRefinementServiceRestTransport( + _BaseFindingsRefinementServiceRestTransport +): + """REST backend synchronous transport for FindingsRefinementService. + + FindingsRefinementService provides an interface for filtering + out findings that are unlikely to be real threats to prevent + them from triggering alerts or notifications. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "chronicle.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[FindingsRefinementServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'chronicle.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + 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. + interceptor (Optional[FindingsRefinementServiceRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or FindingsRefinementServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ComputeAllFindingsRefinementActivities( + _BaseFindingsRefinementServiceRestTransport._BaseComputeAllFindingsRefinementActivities, + FindingsRefinementServiceRestStub, + ): + def __hash__(self): + return hash( + "FindingsRefinementServiceRestTransport.ComputeAllFindingsRefinementActivities" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: findings_refinement.ComputeAllFindingsRefinementActivitiesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> findings_refinement.ComputeAllFindingsRefinementActivitiesResponse: + r"""Call the compute all findings + refinement activities method over HTTP. + + Args: + request (~.findings_refinement.ComputeAllFindingsRefinementActivitiesRequest): + The request object. Request message for + ComputeAllFindingsRefinementActivities + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.findings_refinement.ComputeAllFindingsRefinementActivitiesResponse: + Response message for + ComputeAllFindingsRefinementActivities + method. + + """ + + http_options = _BaseFindingsRefinementServiceRestTransport._BaseComputeAllFindingsRefinementActivities._get_http_options() + + request, metadata = ( + self._interceptor.pre_compute_all_findings_refinement_activities( + request, metadata + ) + ) + transcoded_request = _BaseFindingsRefinementServiceRestTransport._BaseComputeAllFindingsRefinementActivities._get_transcoded_request( + http_options, request + ) + + body = _BaseFindingsRefinementServiceRestTransport._BaseComputeAllFindingsRefinementActivities._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseFindingsRefinementServiceRestTransport._BaseComputeAllFindingsRefinementActivities._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.chronicle_v1.FindingsRefinementServiceClient.ComputeAllFindingsRefinementActivities", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "ComputeAllFindingsRefinementActivities", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = FindingsRefinementServiceRestTransport._ComputeAllFindingsRefinementActivities._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = findings_refinement.ComputeAllFindingsRefinementActivitiesResponse() + pb_resp = ( + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse.pb( + resp + ) + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_compute_all_findings_refinement_activities( + resp + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_compute_all_findings_refinement_activities_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = findings_refinement.ComputeAllFindingsRefinementActivitiesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.chronicle_v1.FindingsRefinementServiceClient.compute_all_findings_refinement_activities", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "ComputeAllFindingsRefinementActivities", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ComputeFindingsRefinementActivity( + _BaseFindingsRefinementServiceRestTransport._BaseComputeFindingsRefinementActivity, + FindingsRefinementServiceRestStub, + ): + def __hash__(self): + return hash( + "FindingsRefinementServiceRestTransport.ComputeFindingsRefinementActivity" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: findings_refinement.ComputeFindingsRefinementActivityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> findings_refinement.ComputeFindingsRefinementActivityResponse: + r"""Call the compute findings + refinement activity method over HTTP. + + Args: + request (~.findings_refinement.ComputeFindingsRefinementActivityRequest): + The request object. Request message for + ComputeFindingsRefinementActivity + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.findings_refinement.ComputeFindingsRefinementActivityResponse: + Response message for + ComputeFindingsRefinementActivity + method. + + """ + + http_options = _BaseFindingsRefinementServiceRestTransport._BaseComputeFindingsRefinementActivity._get_http_options() + + request, metadata = ( + self._interceptor.pre_compute_findings_refinement_activity( + request, metadata + ) + ) + transcoded_request = _BaseFindingsRefinementServiceRestTransport._BaseComputeFindingsRefinementActivity._get_transcoded_request( + http_options, request + ) + + body = _BaseFindingsRefinementServiceRestTransport._BaseComputeFindingsRefinementActivity._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseFindingsRefinementServiceRestTransport._BaseComputeFindingsRefinementActivity._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.chronicle_v1.FindingsRefinementServiceClient.ComputeFindingsRefinementActivity", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "ComputeFindingsRefinementActivity", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = FindingsRefinementServiceRestTransport._ComputeFindingsRefinementActivity._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = findings_refinement.ComputeFindingsRefinementActivityResponse() + pb_resp = findings_refinement.ComputeFindingsRefinementActivityResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_compute_findings_refinement_activity(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_compute_findings_refinement_activity_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = findings_refinement.ComputeFindingsRefinementActivityResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.chronicle_v1.FindingsRefinementServiceClient.compute_findings_refinement_activity", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "ComputeFindingsRefinementActivity", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateFindingsRefinement( + _BaseFindingsRefinementServiceRestTransport._BaseCreateFindingsRefinement, + FindingsRefinementServiceRestStub, + ): + def __hash__(self): + return hash( + "FindingsRefinementServiceRestTransport.CreateFindingsRefinement" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gcc_findings_refinement.CreateFindingsRefinementRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_findings_refinement.FindingsRefinement: + r"""Call the create findings + refinement method over HTTP. + + Args: + request (~.gcc_findings_refinement.CreateFindingsRefinementRequest): + The request object. Request message for + CreateFindingsRefinement method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcc_findings_refinement.FindingsRefinement: + Represents a set of logic conditions + used to refine various types of findings + such as curated rule detections. + + """ + + http_options = _BaseFindingsRefinementServiceRestTransport._BaseCreateFindingsRefinement._get_http_options() + + request, metadata = self._interceptor.pre_create_findings_refinement( + request, metadata + ) + transcoded_request = _BaseFindingsRefinementServiceRestTransport._BaseCreateFindingsRefinement._get_transcoded_request( + http_options, request + ) + + body = _BaseFindingsRefinementServiceRestTransport._BaseCreateFindingsRefinement._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseFindingsRefinementServiceRestTransport._BaseCreateFindingsRefinement._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.chronicle_v1.FindingsRefinementServiceClient.CreateFindingsRefinement", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "CreateFindingsRefinement", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = FindingsRefinementServiceRestTransport._CreateFindingsRefinement._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcc_findings_refinement.FindingsRefinement() + pb_resp = gcc_findings_refinement.FindingsRefinement.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_findings_refinement(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_findings_refinement_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + gcc_findings_refinement.FindingsRefinement.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.chronicle_v1.FindingsRefinementServiceClient.create_findings_refinement", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "CreateFindingsRefinement", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetFindingsRefinement( + _BaseFindingsRefinementServiceRestTransport._BaseGetFindingsRefinement, + FindingsRefinementServiceRestStub, + ): + def __hash__(self): + return hash("FindingsRefinementServiceRestTransport.GetFindingsRefinement") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: findings_refinement.GetFindingsRefinementRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> findings_refinement.FindingsRefinement: + r"""Call the get findings refinement method over HTTP. + + Args: + request (~.findings_refinement.GetFindingsRefinementRequest): + The request object. Request message for + GetFindingsRefinement method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.findings_refinement.FindingsRefinement: + Represents a set of logic conditions + used to refine various types of findings + such as curated rule detections. + + """ + + http_options = _BaseFindingsRefinementServiceRestTransport._BaseGetFindingsRefinement._get_http_options() + + request, metadata = self._interceptor.pre_get_findings_refinement( + request, metadata + ) + transcoded_request = _BaseFindingsRefinementServiceRestTransport._BaseGetFindingsRefinement._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseFindingsRefinementServiceRestTransport._BaseGetFindingsRefinement._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.chronicle_v1.FindingsRefinementServiceClient.GetFindingsRefinement", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "GetFindingsRefinement", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = FindingsRefinementServiceRestTransport._GetFindingsRefinement._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = findings_refinement.FindingsRefinement() + pb_resp = findings_refinement.FindingsRefinement.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_findings_refinement(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_findings_refinement_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = findings_refinement.FindingsRefinement.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.chronicle_v1.FindingsRefinementServiceClient.get_findings_refinement", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "GetFindingsRefinement", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetFindingsRefinementDeployment( + _BaseFindingsRefinementServiceRestTransport._BaseGetFindingsRefinementDeployment, + FindingsRefinementServiceRestStub, + ): + def __hash__(self): + return hash( + "FindingsRefinementServiceRestTransport.GetFindingsRefinementDeployment" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: findings_refinement.GetFindingsRefinementDeploymentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> findings_refinement.FindingsRefinementDeployment: + r"""Call the get findings refinement + deployment method over HTTP. + + Args: + request (~.findings_refinement.GetFindingsRefinementDeploymentRequest): + The request object. Request message for + GetFindingsRefinementDeployment method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.findings_refinement.FindingsRefinementDeployment: + The FindingsRefinementDeployment + resource represents the deployment state + of a findings refinement. + + """ + + http_options = _BaseFindingsRefinementServiceRestTransport._BaseGetFindingsRefinementDeployment._get_http_options() + + request, metadata = ( + self._interceptor.pre_get_findings_refinement_deployment( + request, metadata + ) + ) + transcoded_request = _BaseFindingsRefinementServiceRestTransport._BaseGetFindingsRefinementDeployment._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseFindingsRefinementServiceRestTransport._BaseGetFindingsRefinementDeployment._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.chronicle_v1.FindingsRefinementServiceClient.GetFindingsRefinementDeployment", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "GetFindingsRefinementDeployment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = FindingsRefinementServiceRestTransport._GetFindingsRefinementDeployment._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = findings_refinement.FindingsRefinementDeployment() + pb_resp = findings_refinement.FindingsRefinementDeployment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_findings_refinement_deployment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_get_findings_refinement_deployment_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + findings_refinement.FindingsRefinementDeployment.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.chronicle_v1.FindingsRefinementServiceClient.get_findings_refinement_deployment", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "GetFindingsRefinementDeployment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAllFindingsRefinementDeployments( + _BaseFindingsRefinementServiceRestTransport._BaseListAllFindingsRefinementDeployments, + FindingsRefinementServiceRestStub, + ): + def __hash__(self): + return hash( + "FindingsRefinementServiceRestTransport.ListAllFindingsRefinementDeployments" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: findings_refinement.ListAllFindingsRefinementDeploymentsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> findings_refinement.ListAllFindingsRefinementDeploymentsResponse: + r"""Call the list all findings + refinement deployments method over HTTP. + + Args: + request (~.findings_refinement.ListAllFindingsRefinementDeploymentsRequest): + The request object. Request message for + ListAllFindingsRefinementDeployments + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.findings_refinement.ListAllFindingsRefinementDeploymentsResponse: + Response message for + ListAllFindingsRefinementDeployments + method. + + """ + + http_options = _BaseFindingsRefinementServiceRestTransport._BaseListAllFindingsRefinementDeployments._get_http_options() + + request, metadata = ( + self._interceptor.pre_list_all_findings_refinement_deployments( + request, metadata + ) + ) + transcoded_request = _BaseFindingsRefinementServiceRestTransport._BaseListAllFindingsRefinementDeployments._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseFindingsRefinementServiceRestTransport._BaseListAllFindingsRefinementDeployments._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.chronicle_v1.FindingsRefinementServiceClient.ListAllFindingsRefinementDeployments", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "ListAllFindingsRefinementDeployments", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = FindingsRefinementServiceRestTransport._ListAllFindingsRefinementDeployments._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = findings_refinement.ListAllFindingsRefinementDeploymentsResponse() + pb_resp = ( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse.pb( + resp + ) + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_all_findings_refinement_deployments(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_list_all_findings_refinement_deployments_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = findings_refinement.ListAllFindingsRefinementDeploymentsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.chronicle_v1.FindingsRefinementServiceClient.list_all_findings_refinement_deployments", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "ListAllFindingsRefinementDeployments", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListFindingsRefinements( + _BaseFindingsRefinementServiceRestTransport._BaseListFindingsRefinements, + FindingsRefinementServiceRestStub, + ): + def __hash__(self): + return hash( + "FindingsRefinementServiceRestTransport.ListFindingsRefinements" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: findings_refinement.ListFindingsRefinementsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> findings_refinement.ListFindingsRefinementsResponse: + r"""Call the list findings refinements method over HTTP. + + Args: + request (~.findings_refinement.ListFindingsRefinementsRequest): + The request object. Request message for + ListFindingsRefinements method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.findings_refinement.ListFindingsRefinementsResponse: + Response message for + ListFindingsRefinements method. + + """ + + http_options = _BaseFindingsRefinementServiceRestTransport._BaseListFindingsRefinements._get_http_options() + + request, metadata = self._interceptor.pre_list_findings_refinements( + request, metadata + ) + transcoded_request = _BaseFindingsRefinementServiceRestTransport._BaseListFindingsRefinements._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseFindingsRefinementServiceRestTransport._BaseListFindingsRefinements._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.chronicle_v1.FindingsRefinementServiceClient.ListFindingsRefinements", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "ListFindingsRefinements", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = FindingsRefinementServiceRestTransport._ListFindingsRefinements._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = findings_refinement.ListFindingsRefinementsResponse() + pb_resp = findings_refinement.ListFindingsRefinementsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_findings_refinements(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_findings_refinements_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + findings_refinement.ListFindingsRefinementsResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.chronicle_v1.FindingsRefinementServiceClient.list_findings_refinements", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "ListFindingsRefinements", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateFindingsRefinement( + _BaseFindingsRefinementServiceRestTransport._BaseUpdateFindingsRefinement, + FindingsRefinementServiceRestStub, + ): + def __hash__(self): + return hash( + "FindingsRefinementServiceRestTransport.UpdateFindingsRefinement" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gcc_findings_refinement.UpdateFindingsRefinementRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_findings_refinement.FindingsRefinement: + r"""Call the update findings + refinement method over HTTP. + + Args: + request (~.gcc_findings_refinement.UpdateFindingsRefinementRequest): + The request object. Request message for + UpdateFindingsRefinement method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcc_findings_refinement.FindingsRefinement: + Represents a set of logic conditions + used to refine various types of findings + such as curated rule detections. + + """ + + http_options = _BaseFindingsRefinementServiceRestTransport._BaseUpdateFindingsRefinement._get_http_options() + + request, metadata = self._interceptor.pre_update_findings_refinement( + request, metadata + ) + transcoded_request = _BaseFindingsRefinementServiceRestTransport._BaseUpdateFindingsRefinement._get_transcoded_request( + http_options, request + ) + + body = _BaseFindingsRefinementServiceRestTransport._BaseUpdateFindingsRefinement._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseFindingsRefinementServiceRestTransport._BaseUpdateFindingsRefinement._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.chronicle_v1.FindingsRefinementServiceClient.UpdateFindingsRefinement", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "UpdateFindingsRefinement", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = FindingsRefinementServiceRestTransport._UpdateFindingsRefinement._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcc_findings_refinement.FindingsRefinement() + pb_resp = gcc_findings_refinement.FindingsRefinement.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_findings_refinement(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_findings_refinement_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + gcc_findings_refinement.FindingsRefinement.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.chronicle_v1.FindingsRefinementServiceClient.update_findings_refinement", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "UpdateFindingsRefinement", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateFindingsRefinementDeployment( + _BaseFindingsRefinementServiceRestTransport._BaseUpdateFindingsRefinementDeployment, + FindingsRefinementServiceRestStub, + ): + def __hash__(self): + return hash( + "FindingsRefinementServiceRestTransport.UpdateFindingsRefinementDeployment" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: findings_refinement.UpdateFindingsRefinementDeploymentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> findings_refinement.FindingsRefinementDeployment: + r"""Call the update findings + refinement deployment method over HTTP. + + Args: + request (~.findings_refinement.UpdateFindingsRefinementDeploymentRequest): + The request object. Request message for + UpdateFindingsRefinementDeployment + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.findings_refinement.FindingsRefinementDeployment: + The FindingsRefinementDeployment + resource represents the deployment state + of a findings refinement. + + """ + + http_options = _BaseFindingsRefinementServiceRestTransport._BaseUpdateFindingsRefinementDeployment._get_http_options() + + request, metadata = ( + self._interceptor.pre_update_findings_refinement_deployment( + request, metadata + ) + ) + transcoded_request = _BaseFindingsRefinementServiceRestTransport._BaseUpdateFindingsRefinementDeployment._get_transcoded_request( + http_options, request + ) + + body = _BaseFindingsRefinementServiceRestTransport._BaseUpdateFindingsRefinementDeployment._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseFindingsRefinementServiceRestTransport._BaseUpdateFindingsRefinementDeployment._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.chronicle_v1.FindingsRefinementServiceClient.UpdateFindingsRefinementDeployment", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "UpdateFindingsRefinementDeployment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = FindingsRefinementServiceRestTransport._UpdateFindingsRefinementDeployment._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = findings_refinement.FindingsRefinementDeployment() + pb_resp = findings_refinement.FindingsRefinementDeployment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_findings_refinement_deployment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_update_findings_refinement_deployment_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + findings_refinement.FindingsRefinementDeployment.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.chronicle_v1.FindingsRefinementServiceClient.update_findings_refinement_deployment", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "UpdateFindingsRefinementDeployment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def compute_all_findings_refinement_activities( + self, + ) -> Callable[ + [findings_refinement.ComputeAllFindingsRefinementActivitiesRequest], + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ComputeAllFindingsRefinementActivities( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def compute_findings_refinement_activity( + self, + ) -> Callable[ + [findings_refinement.ComputeFindingsRefinementActivityRequest], + findings_refinement.ComputeFindingsRefinementActivityResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ComputeFindingsRefinementActivity( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def create_findings_refinement( + self, + ) -> Callable[ + [gcc_findings_refinement.CreateFindingsRefinementRequest], + gcc_findings_refinement.FindingsRefinement, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateFindingsRefinement( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_findings_refinement( + self, + ) -> Callable[ + [findings_refinement.GetFindingsRefinementRequest], + findings_refinement.FindingsRefinement, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetFindingsRefinement(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_findings_refinement_deployment( + self, + ) -> Callable[ + [findings_refinement.GetFindingsRefinementDeploymentRequest], + findings_refinement.FindingsRefinementDeployment, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetFindingsRefinementDeployment( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_all_findings_refinement_deployments( + self, + ) -> Callable[ + [findings_refinement.ListAllFindingsRefinementDeploymentsRequest], + findings_refinement.ListAllFindingsRefinementDeploymentsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAllFindingsRefinementDeployments( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_findings_refinements( + self, + ) -> Callable[ + [findings_refinement.ListFindingsRefinementsRequest], + findings_refinement.ListFindingsRefinementsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListFindingsRefinements( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def update_findings_refinement( + self, + ) -> Callable[ + [gcc_findings_refinement.UpdateFindingsRefinementRequest], + gcc_findings_refinement.FindingsRefinement, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateFindingsRefinement( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def update_findings_refinement_deployment( + self, + ) -> Callable[ + [findings_refinement.UpdateFindingsRefinementDeploymentRequest], + findings_refinement.FindingsRefinementDeployment, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateFindingsRefinementDeployment( + 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( + _BaseFindingsRefinementServiceRestTransport._BaseCancelOperation, + FindingsRefinementServiceRestStub, + ): + def __hash__(self): + return hash("FindingsRefinementServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseFindingsRefinementServiceRestTransport._BaseCancelOperation._get_http_options() + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseFindingsRefinementServiceRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + + body = _BaseFindingsRefinementServiceRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseFindingsRefinementServiceRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.chronicle_v1.FindingsRefinementServiceClient.CancelOperation", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + FindingsRefinementServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation( + _BaseFindingsRefinementServiceRestTransport._BaseDeleteOperation, + FindingsRefinementServiceRestStub, + ): + def __hash__(self): + return hash("FindingsRefinementServiceRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseFindingsRefinementServiceRestTransport._BaseDeleteOperation._get_http_options() + + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request = _BaseFindingsRefinementServiceRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseFindingsRefinementServiceRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.chronicle_v1.FindingsRefinementServiceClient.DeleteOperation", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + FindingsRefinementServiceRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseFindingsRefinementServiceRestTransport._BaseGetOperation, + FindingsRefinementServiceRestStub, + ): + def __hash__(self): + return hash("FindingsRefinementServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseFindingsRefinementServiceRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseFindingsRefinementServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseFindingsRefinementServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.chronicle_v1.FindingsRefinementServiceClient.GetOperation", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + FindingsRefinementServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseFindingsRefinementServiceRestTransport._BaseListOperations, + FindingsRefinementServiceRestStub, + ): + def __hash__(self): + return hash("FindingsRefinementServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = _BaseFindingsRefinementServiceRestTransport._BaseListOperations._get_http_options() + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseFindingsRefinementServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseFindingsRefinementServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.chronicle_v1.FindingsRefinementServiceClient.ListOperations", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + FindingsRefinementServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.chronicle.v1.FindingsRefinementService", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("FindingsRefinementServiceRestTransport",) diff --git a/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/rest_base.py b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/rest_base.py new file mode 100644 index 000000000000..352ded762bb1 --- /dev/null +++ b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/services/findings_refinement_service/transports/rest_base.py @@ -0,0 +1,696 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.chronicle_v1.types import findings_refinement +from google.cloud.chronicle_v1.types import ( + findings_refinement as gcc_findings_refinement, +) + +from .base import DEFAULT_CLIENT_INFO, FindingsRefinementServiceTransport + + +class _BaseFindingsRefinementServiceRestTransport(FindingsRefinementServiceTransport): + """Base REST backend transport for FindingsRefinementService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "chronicle.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'chronicle.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseComputeAllFindingsRefinementActivities: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{instance=projects/*/locations/*/instances/*}:computeAllFindingsRefinementActivities", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + findings_refinement.ComputeAllFindingsRefinementActivitiesRequest.pb( + request + ) + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseFindingsRefinementServiceRestTransport._BaseComputeAllFindingsRefinementActivities._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseComputeFindingsRefinementActivity: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/instances/*/findingsRefinements/*}:computeFindingsRefinementActivity", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + findings_refinement.ComputeFindingsRefinementActivityRequest.pb(request) + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseFindingsRefinementServiceRestTransport._BaseComputeFindingsRefinementActivity._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateFindingsRefinement: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/instances/*}/findingsRefinements", + "body": "findings_refinement", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcc_findings_refinement.CreateFindingsRefinementRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseFindingsRefinementServiceRestTransport._BaseCreateFindingsRefinement._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetFindingsRefinement: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/instances/*/findingsRefinements/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = findings_refinement.GetFindingsRefinementRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseFindingsRefinementServiceRestTransport._BaseGetFindingsRefinement._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetFindingsRefinementDeployment: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/instances/*/findingsRefinements/*/deployment}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = findings_refinement.GetFindingsRefinementDeploymentRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseFindingsRefinementServiceRestTransport._BaseGetFindingsRefinementDeployment._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListAllFindingsRefinementDeployments: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{instance=projects/*/locations/*/instances/*}:listAllFindingsRefinementDeployments", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + findings_refinement.ListAllFindingsRefinementDeploymentsRequest.pb( + request + ) + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseFindingsRefinementServiceRestTransport._BaseListAllFindingsRefinementDeployments._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListFindingsRefinements: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/instances/*}/findingsRefinements", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = findings_refinement.ListFindingsRefinementsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseFindingsRefinementServiceRestTransport._BaseListFindingsRefinements._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateFindingsRefinement: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{findings_refinement.name=projects/*/locations/*/instances/*/findingsRefinements/*}", + "body": "findings_refinement", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcc_findings_refinement.UpdateFindingsRefinementRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseFindingsRefinementServiceRestTransport._BaseUpdateFindingsRefinement._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateFindingsRefinementDeployment: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{findings_refinement_deployment.name=projects/*/locations/*/instances/*/findingsRefinements/*/deployment}", + "body": "findings_refinement_deployment", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ( + findings_refinement.UpdateFindingsRefinementDeploymentRequest.pb( + request + ) + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseFindingsRefinementServiceRestTransport._BaseUpdateFindingsRefinementDeployment._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/instances/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/instances/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/instances/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/instances/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseFindingsRefinementServiceRestTransport",) diff --git a/packages/google-cloud-chronicle/google/cloud/chronicle_v1/types/__init__.py b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/types/__init__.py index 603d579ff47c..9e9b3559ee3f 100644 --- a/packages/google-cloud-chronicle/google/cloud/chronicle_v1/types/__init__.py +++ b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/types/__init__.py @@ -130,6 +130,28 @@ ListFeaturedContentNativeDashboardsRequest, ListFeaturedContentNativeDashboardsResponse, ) +from .findings_refinement import ( + ComputeAllFindingsRefinementActivitiesRequest, + ComputeAllFindingsRefinementActivitiesResponse, + ComputeFindingsRefinementActivityRequest, + ComputeFindingsRefinementActivityResponse, + CreateFindingsRefinementRequest, + DetectionExclusionActivity, + DetectionExclusionApplication, + FindingsRefinement, + FindingsRefinementActivity, + FindingsRefinementDeployment, + FindingsRefinementType, + GetFindingsRefinementDeploymentRequest, + GetFindingsRefinementRequest, + ListAllFindingsRefinementDeploymentsRequest, + ListAllFindingsRefinementDeploymentsResponse, + ListFindingsRefinementsRequest, + ListFindingsRefinementsResponse, + OutcomeFilter, + UpdateFindingsRefinementDeploymentRequest, + UpdateFindingsRefinementRequest, +) from .instance import ( GetInstanceRequest, Instance, @@ -319,6 +341,26 @@ "InstallFeaturedContentNativeDashboardResponse", "ListFeaturedContentNativeDashboardsRequest", "ListFeaturedContentNativeDashboardsResponse", + "ComputeAllFindingsRefinementActivitiesRequest", + "ComputeAllFindingsRefinementActivitiesResponse", + "ComputeFindingsRefinementActivityRequest", + "ComputeFindingsRefinementActivityResponse", + "CreateFindingsRefinementRequest", + "DetectionExclusionActivity", + "DetectionExclusionApplication", + "FindingsRefinement", + "FindingsRefinementActivity", + "FindingsRefinementDeployment", + "GetFindingsRefinementDeploymentRequest", + "GetFindingsRefinementRequest", + "ListAllFindingsRefinementDeploymentsRequest", + "ListAllFindingsRefinementDeploymentsResponse", + "ListFindingsRefinementsRequest", + "ListFindingsRefinementsResponse", + "OutcomeFilter", + "UpdateFindingsRefinementDeploymentRequest", + "UpdateFindingsRefinementRequest", + "FindingsRefinementType", "GetInstanceRequest", "Instance", "AddChartRequest", diff --git a/packages/google-cloud-chronicle/google/cloud/chronicle_v1/types/findings_refinement.py b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/types/findings_refinement.py new file mode 100644 index 000000000000..02683bf40393 --- /dev/null +++ b/packages/google-cloud-chronicle/google/cloud/chronicle_v1/types/findings_refinement.py @@ -0,0 +1,761 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.type.interval_pb2 as interval_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.chronicle.v1", + manifest={ + "FindingsRefinementType", + "FindingsRefinement", + "FindingsRefinementDeployment", + "DetectionExclusionApplication", + "FindingsRefinementActivity", + "DetectionExclusionActivity", + "GetFindingsRefinementRequest", + "ListFindingsRefinementsRequest", + "ListFindingsRefinementsResponse", + "CreateFindingsRefinementRequest", + "UpdateFindingsRefinementRequest", + "GetFindingsRefinementDeploymentRequest", + "UpdateFindingsRefinementDeploymentRequest", + "ListAllFindingsRefinementDeploymentsRequest", + "ListAllFindingsRefinementDeploymentsResponse", + "OutcomeFilter", + "ComputeFindingsRefinementActivityRequest", + "ComputeFindingsRefinementActivityResponse", + "ComputeAllFindingsRefinementActivitiesRequest", + "ComputeAllFindingsRefinementActivitiesResponse", + }, +) + + +class FindingsRefinementType(proto.Enum): + r"""The type of findings refinement, which determines what the + findings refinement runs over and the mechanism by which it + runs. + + Values: + FINDINGS_REFINEMENT_TYPE_UNSPECIFIED (0): + The findings refinement type is unspecified. + DETECTION_EXCLUSION (1): + Indicates that the findings refinement is a + detection exclusion and should exclude matching + detections. + """ + + FINDINGS_REFINEMENT_TYPE_UNSPECIFIED = 0 + DETECTION_EXCLUSION = 1 + + +class FindingsRefinement(proto.Message): + r"""Represents a set of logic conditions used to refine various + types of findings such as curated rule detections. + + Attributes: + name (str): + Full resource name for the findings refinement. Format: + projects/{project}/locations/{region}/instances/{instance}/findingsRefinements/{findings_refinement} + display_name (str): + Display name of the findings refinement. + type_ (google.cloud.chronicle_v1.types.FindingsRefinementType): + The type of findings refinement. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp of when the + findings refinement was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp of when the + findings refinement was last updated. + query (str): + The query for the findings refinement. Works + in conjunction with the type field to determine + the findings refinement behavior. The syntax of + this query is the same as a UDM search string. + See the following for more information: + + https://cloud.google.com/chronicle/docs/investigation/udm-search + outcome_filters (MutableSequence[google.cloud.chronicle_v1.types.OutcomeFilter]): + Optional. The outcome filters for the + findings refinement. These allow you to specify + filters that are applied to the outcome + variables in the detection. All filters must be + true for a detection to match the findings + refinement. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + type_: "FindingsRefinementType" = proto.Field( + proto.ENUM, + number=3, + enum="FindingsRefinementType", + ) + 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, + ) + query: str = proto.Field( + proto.STRING, + number=7, + ) + outcome_filters: MutableSequence["OutcomeFilter"] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message="OutcomeFilter", + ) + + +class FindingsRefinementDeployment(proto.Message): + r"""The FindingsRefinementDeployment resource represents the + deployment state of a findings refinement. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + detection_exclusion_application (google.cloud.chronicle_v1.types.DetectionExclusionApplication): + The resources which the detection exclusion + is applied to. + + This field is a member of `oneof`_ ``FindingsRefinementApplication``. + name (str): + Required. The resource name of the findings refinement + deployment. Format: + projects/{project}/locations/{location}/instances/{instance}/findingsRefinements/{findings_refinement}/deployment + enabled (bool): + Whether the findings refinement is currently + deployed continuously against incoming findings. + archived (bool): + The archive state of the findings refinement + deployment. Cannot be set to true unless enabled + is set to false. If currently set to true, + enabled cannot be updated to true. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the findings + refinement deployment was last updated. + """ + + detection_exclusion_application: "DetectionExclusionApplication" = proto.Field( + proto.MESSAGE, + number=5, + oneof="FindingsRefinementApplication", + message="DetectionExclusionApplication", + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + enabled: bool = proto.Field( + proto.BOOL, + number=2, + ) + archived: bool = proto.Field( + proto.BOOL, + number=3, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +class DetectionExclusionApplication(proto.Message): + r"""Describes the detectors a detection exclusion is applied to. + + Attributes: + curated_rule_sets (MutableSequence[str]): + The CuratedRuleSets this detection exclusion applies to. + Format: + projects/{project}/locations/{location}/instances/{instance}/curatedRuleSetCategories/{category}/curatedRuleSets/{rule_set} + curated_rules (MutableSequence[str]): + The CuratedRules this detection exclusion + applies to. Format: + + projects/{project}/locations/{location}/instances/{instance}/curatedRules/{rule} + rules (MutableSequence[str]): + Optional. The Rules this detection exclusion + applies to. Format: + + projects/{project}/locations/{location}/instances/{instance}/rules/{rule} + deleted_curated_rule_sets (MutableSequence[str]): + Output only. The deleted CuratedRuleSets this detection + exclusion applies to. Indicates to the customer that the + detection exclusion no longer applies to the rule sets, so + the detection exclusion should be updated. Format: + projects/{project}/locations/{location}/instances/{instance}/curatedRuleSetCategories/{category}/curatedRuleSets/{rule_set} + """ + + curated_rule_sets: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + curated_rules: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + rules: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + deleted_curated_rule_sets: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +class FindingsRefinementActivity(proto.Message): + r"""The activity for a specific findings refinement. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + detection_exclusion_activity (google.cloud.chronicle_v1.types.DetectionExclusionActivity): + The activity for the detection exclusion. + + This field is a member of `oneof`_ ``Activity``. + findings_refinement (str): + Required. Full resource name for the findings refinement + this activity corresponds to. Format: + projects/{project}/locations/{region}/instances/{instance}/findingsRefinements/{findings_refinement} + """ + + detection_exclusion_activity: "DetectionExclusionActivity" = proto.Field( + proto.MESSAGE, + number=2, + oneof="Activity", + message="DetectionExclusionActivity", + ) + findings_refinement: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DetectionExclusionActivity(proto.Message): + r"""The activity for a findings refinement that is a detection + exclusion. The activity is broken down per detector. + + Attributes: + detection_exclusion_detector_activities (MutableSequence[google.cloud.chronicle_v1.types.DetectionExclusionActivity.DetectionExclusionDetectorActivity]): + The activity for the detection exclusion + broken down by detector. + """ + + class DetectionExclusionDetectorActivity(proto.Message): + r"""The activity for a findings refinement that is a detection + exclusion broken down for one specific detector. + + 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: + curated_rule (str): + Full resource name for the curated rule this + activity corresponds to. Format: + + projects/{project}/locations/{location}/instances/{instance}/curatedRules/{rule} + + This field is a member of `oneof`_ ``detector_name``. + curated_rule_set (str): + Full resource name for the curated rule set this activity + corresponds to. This field will only be set if the customer + has access to the curated rule set the exclusion is applied + to. Format: + projects/{project}/locations/{location}/instances/{instance}/curatedRuleSetCategories/{curated_rule_set_category}/curatedRuleSets/{curated_rule_set} + + This field is a member of `oneof`_ ``detector_name``. + rule (str): + Full resource name for the rule this activity + corresponds to. Format: + + projects/{project}/locations/{location}/instances/{instance}/rules/{rule} + + This field is a member of `oneof`_ ``detector_name``. + deleted_curated_rule_set (str): + Full resource name for the deleted curated rule set this + activity corresponds to. This field will only be set if the + customer does not have access to the curated rule set the + exclusion is applied to. Format: + projects/{project}/locations/{location}/instances/{instance}/curatedRuleSetCategories/{curated_rule_set_category}/curatedRuleSets/{curated_rule_set} + + This field is a member of `oneof`_ ``detector_name``. + excluded_detection_count (int): + The number of detections for the detector + that were excluded by the detection exclusion. + total_detection_count (int): + The total number of detections found by the + detector. This includes both excluded detections + and non-excluded detections. + """ + + curated_rule: str = proto.Field( + proto.STRING, + number=1, + oneof="detector_name", + ) + curated_rule_set: str = proto.Field( + proto.STRING, + number=2, + oneof="detector_name", + ) + rule: str = proto.Field( + proto.STRING, + number=5, + oneof="detector_name", + ) + deleted_curated_rule_set: str = proto.Field( + proto.STRING, + number=6, + oneof="detector_name", + ) + excluded_detection_count: int = proto.Field( + proto.INT64, + number=3, + ) + total_detection_count: int = proto.Field( + proto.INT64, + number=4, + ) + + detection_exclusion_detector_activities: MutableSequence[ + DetectionExclusionDetectorActivity + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=DetectionExclusionDetectorActivity, + ) + + +class GetFindingsRefinementRequest(proto.Message): + r"""Request message for GetFindingsRefinement method. + + Attributes: + name (str): + Required. The name of the findings refinement to retrieve. + Format: + projects/{project}/locations/{location}/instances/{instance}/findingsRefinements/{findings_refinement} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFindingsRefinementsRequest(proto.Message): + r"""Request message for ListFindingsRefinements method. + + Attributes: + parent (str): + Required. The parent, which owns this + collection of findings refinements. Format: + + projects/{project}/locations/{location}/instances/{instance} + page_size (int): + The maximum number of findings refinements to + return. The service may return fewer than this + value. If unspecified, at most 100 rules 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 + ``ListFindingsRefinements`` call. Provide this to retrieve + the subsequent page. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListFindingsRefinementsResponse(proto.Message): + r"""Response message for ListFindingsRefinements method. + + Attributes: + findings_refinements (MutableSequence[google.cloud.chronicle_v1.types.FindingsRefinement]): + List of findings refinements. + 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 + + findings_refinements: MutableSequence["FindingsRefinement"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="FindingsRefinement", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateFindingsRefinementRequest(proto.Message): + r"""Request message for CreateFindingsRefinement method. + + Attributes: + parent (str): + Required. The parent resource where this + findings refinement will be created. Format: + + projects/{project}/locations/{location}/instances/{instance} + findings_refinement (google.cloud.chronicle_v1.types.FindingsRefinement): + Required. The findings refinement to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + findings_refinement: "FindingsRefinement" = proto.Field( + proto.MESSAGE, + number=2, + message="FindingsRefinement", + ) + + +class UpdateFindingsRefinementRequest(proto.Message): + r"""Request message for UpdateFindingsRefinement method. + + Attributes: + findings_refinement (google.cloud.chronicle_v1.types.FindingsRefinement): + Required. The findings refinement to update. + + The findings refinement's ``name`` field is used to identify + the findings refinement to update. Format: + projects/{project}/locations/{location}/instances/{instance}/findingsRefinements/{findings_refinement} + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. If ``*`` is + provided, all fields will be updated. + """ + + findings_refinement: "FindingsRefinement" = proto.Field( + proto.MESSAGE, + number=1, + message="FindingsRefinement", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetFindingsRefinementDeploymentRequest(proto.Message): + r"""Request message for GetFindingsRefinementDeployment method. + + Attributes: + name (str): + Required. The name of the findings refinement to retrieve. + Format: + projects/{project}/locations/{location}/instances/{instance}/findingsRefinements/{findings_refinement}/deployment + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateFindingsRefinementDeploymentRequest(proto.Message): + r"""Request message for UpdateFindingsRefinementDeployment + method. + + Attributes: + findings_refinement_deployment (google.cloud.chronicle_v1.types.FindingsRefinementDeployment): + Required. The findings refinement deployment to update. + + The findings refinement deployment's ``name`` field is used + to identify the findings refinement deployment to update. + Format: + projects/{project}/locations/{location}/instances/{instance}/findingsRefinements/{findings_refinement}/deployment + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. If ``*`` is + provided, all fields will be updated. + """ + + findings_refinement_deployment: "FindingsRefinementDeployment" = proto.Field( + proto.MESSAGE, + number=1, + message="FindingsRefinementDeployment", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListAllFindingsRefinementDeploymentsRequest(proto.Message): + r"""Request message for ListAllFindingsRefinementDeployments + method. + + Attributes: + instance (str): + Required. The name of the parent resource, + which is the SecOps instance to list all + findings refinement deployments over. Format: + + projects/{project}/locations/{location}/instances/{instance} + page_size (int): + The maximum number of findings refinement + deployments to return. The service may return + fewer than this value. If unspecified, at most + 100 rule deployments 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 + ``ListAllFindingsRefinementDeployments`` call. Provide this + to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListAllFindingsRefinementDeployments`` must match the call + that provided the page token. + filter (str): + A filter that can be used to retrieve specific findings + refinement deployments. Only the following filters are + allowed: + detection_exclusion_application.curated_rule_sets:""", + detection_exclusion_application.curated_rules:"". + """ + + instance: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListAllFindingsRefinementDeploymentsResponse(proto.Message): + r"""Response message for ListAllFindingsRefinementDeployments + method. + + Attributes: + all_findings_refinement_deployments (MutableSequence[google.cloud.chronicle_v1.types.FindingsRefinementDeployment]): + List of all findings refinement deployments. + 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 + + all_findings_refinement_deployments: MutableSequence[ + "FindingsRefinementDeployment" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="FindingsRefinementDeployment", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class OutcomeFilter(proto.Message): + r"""Outcome filter for the findings refinement. This is used to + filter the findings refinement based on the outcome variable + values. + + Attributes: + outcome_variable (str): + Required. The outcome variable name. + outcome_value (str): + Required. The value of the outcome variable + to match. + outcome_filter_operator (google.cloud.chronicle_v1.types.OutcomeFilter.Operator): + Required. The operator to be applied to the + outcome variable. + """ + + class Operator(proto.Enum): + r"""The operator to compare the outcome variable value with the + outcome value in the outcome filter. + + Values: + OPERATOR_UNSPECIFIED (0): + The operator is unspecified. + EQUAL (1): + The outcome variable value must be equal to + the outcome value in the outcome filter. + CONTAINS (2): + The outcome variable value must contain the + outcome value in the outcome filter. + MATCHES_REGEX (3): + The outcome variable value must match the + outcome value regex in the outcome filter. + MATCHES_CIDR (4): + The outcome variable value must be a valid IP + address in the outcome filter value CIDR range. + """ + + OPERATOR_UNSPECIFIED = 0 + EQUAL = 1 + CONTAINS = 2 + MATCHES_REGEX = 3 + MATCHES_CIDR = 4 + + outcome_variable: str = proto.Field( + proto.STRING, + number=1, + ) + outcome_value: str = proto.Field( + proto.STRING, + number=2, + ) + outcome_filter_operator: Operator = proto.Field( + proto.ENUM, + number=3, + enum=Operator, + ) + + +class ComputeFindingsRefinementActivityRequest(proto.Message): + r"""Request message for ComputeFindingsRefinementActivity method. + + Attributes: + name (str): + Required. Full resource name for the findings refinement to + fetch the activity for. Format: + projects/{project}/locations/{region}/instances/{instance}/findingsRefinements/{findings_refinement} + interval (google.type.interval_pb2.Interval): + The time interval the activity is measured + over. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + interval: interval_pb2.Interval = proto.Field( + proto.MESSAGE, + number=2, + message=interval_pb2.Interval, + ) + + +class ComputeFindingsRefinementActivityResponse(proto.Message): + r"""Response message for ComputeFindingsRefinementActivity + method. + + Attributes: + activity (google.cloud.chronicle_v1.types.FindingsRefinementActivity): + The activity for the findings refinement. + """ + + activity: "FindingsRefinementActivity" = proto.Field( + proto.MESSAGE, + number=1, + message="FindingsRefinementActivity", + ) + + +class ComputeAllFindingsRefinementActivitiesRequest(proto.Message): + r"""Request message for ComputeAllFindingsRefinementActivities + method. + + Attributes: + instance (str): + Required. The ID of the Instance to retrieve + counts for. Format: + + projects/{project}/locations/{location}/instances/{instance} + interval (google.type.interval_pb2.Interval): + The time interval the activity is measured + over. + """ + + instance: str = proto.Field( + proto.STRING, + number=1, + ) + interval: interval_pb2.Interval = proto.Field( + proto.MESSAGE, + number=2, + message=interval_pb2.Interval, + ) + + +class ComputeAllFindingsRefinementActivitiesResponse(proto.Message): + r"""Response message for ComputeAllFindingsRefinementActivities + method. + + Attributes: + activities (MutableSequence[google.cloud.chronicle_v1.types.FindingsRefinementActivity]): + The activities of all findings refinements. + """ + + activities: MutableSequence["FindingsRefinementActivity"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="FindingsRefinementActivity", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_compute_all_findings_refinement_activities_async.py b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_compute_all_findings_refinement_activities_async.py new file mode 100644 index 000000000000..238c48f648f2 --- /dev/null +++ b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_compute_all_findings_refinement_activities_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeAllFindingsRefinementActivities +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-chronicle + + +# [START chronicle_v1_generated_FindingsRefinementService_ComputeAllFindingsRefinementActivities_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import chronicle_v1 + + +async def sample_compute_all_findings_refinement_activities(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceAsyncClient() + + # Initialize request argument(s) + request = chronicle_v1.ComputeAllFindingsRefinementActivitiesRequest( + instance="instance_value", + ) + + # Make the request + response = await client.compute_all_findings_refinement_activities(request=request) + + # Handle the response + print(response) + + +# [END chronicle_v1_generated_FindingsRefinementService_ComputeAllFindingsRefinementActivities_async] diff --git a/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_compute_all_findings_refinement_activities_sync.py b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_compute_all_findings_refinement_activities_sync.py new file mode 100644 index 000000000000..b9b4f6562d90 --- /dev/null +++ b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_compute_all_findings_refinement_activities_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeAllFindingsRefinementActivities +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-chronicle + + +# [START chronicle_v1_generated_FindingsRefinementService_ComputeAllFindingsRefinementActivities_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import chronicle_v1 + + +def sample_compute_all_findings_refinement_activities(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceClient() + + # Initialize request argument(s) + request = chronicle_v1.ComputeAllFindingsRefinementActivitiesRequest( + instance="instance_value", + ) + + # Make the request + response = client.compute_all_findings_refinement_activities(request=request) + + # Handle the response + print(response) + + +# [END chronicle_v1_generated_FindingsRefinementService_ComputeAllFindingsRefinementActivities_sync] diff --git a/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_compute_findings_refinement_activity_async.py b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_compute_findings_refinement_activity_async.py new file mode 100644 index 000000000000..40e87b587011 --- /dev/null +++ b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_compute_findings_refinement_activity_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeFindingsRefinementActivity +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-chronicle + + +# [START chronicle_v1_generated_FindingsRefinementService_ComputeFindingsRefinementActivity_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import chronicle_v1 + + +async def sample_compute_findings_refinement_activity(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceAsyncClient() + + # Initialize request argument(s) + request = chronicle_v1.ComputeFindingsRefinementActivityRequest( + name="name_value", + ) + + # Make the request + response = await client.compute_findings_refinement_activity(request=request) + + # Handle the response + print(response) + + +# [END chronicle_v1_generated_FindingsRefinementService_ComputeFindingsRefinementActivity_async] diff --git a/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_compute_findings_refinement_activity_sync.py b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_compute_findings_refinement_activity_sync.py new file mode 100644 index 000000000000..7b24a5238615 --- /dev/null +++ b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_compute_findings_refinement_activity_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeFindingsRefinementActivity +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-chronicle + + +# [START chronicle_v1_generated_FindingsRefinementService_ComputeFindingsRefinementActivity_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import chronicle_v1 + + +def sample_compute_findings_refinement_activity(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceClient() + + # Initialize request argument(s) + request = chronicle_v1.ComputeFindingsRefinementActivityRequest( + name="name_value", + ) + + # Make the request + response = client.compute_findings_refinement_activity(request=request) + + # Handle the response + print(response) + + +# [END chronicle_v1_generated_FindingsRefinementService_ComputeFindingsRefinementActivity_sync] diff --git a/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_create_findings_refinement_async.py b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_create_findings_refinement_async.py new file mode 100644 index 000000000000..9e88f395845b --- /dev/null +++ b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_create_findings_refinement_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateFindingsRefinement +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-chronicle + + +# [START chronicle_v1_generated_FindingsRefinementService_CreateFindingsRefinement_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import chronicle_v1 + + +async def sample_create_findings_refinement(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceAsyncClient() + + # Initialize request argument(s) + request = chronicle_v1.CreateFindingsRefinementRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_findings_refinement(request=request) + + # Handle the response + print(response) + + +# [END chronicle_v1_generated_FindingsRefinementService_CreateFindingsRefinement_async] diff --git a/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_create_findings_refinement_sync.py b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_create_findings_refinement_sync.py new file mode 100644 index 000000000000..91584d7bb8fc --- /dev/null +++ b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_create_findings_refinement_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateFindingsRefinement +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-chronicle + + +# [START chronicle_v1_generated_FindingsRefinementService_CreateFindingsRefinement_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import chronicle_v1 + + +def sample_create_findings_refinement(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceClient() + + # Initialize request argument(s) + request = chronicle_v1.CreateFindingsRefinementRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_findings_refinement(request=request) + + # Handle the response + print(response) + + +# [END chronicle_v1_generated_FindingsRefinementService_CreateFindingsRefinement_sync] diff --git a/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_get_findings_refinement_async.py b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_get_findings_refinement_async.py new file mode 100644 index 000000000000..e72fbe6f888c --- /dev/null +++ b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_get_findings_refinement_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetFindingsRefinement +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-chronicle + + +# [START chronicle_v1_generated_FindingsRefinementService_GetFindingsRefinement_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import chronicle_v1 + + +async def sample_get_findings_refinement(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceAsyncClient() + + # Initialize request argument(s) + request = chronicle_v1.GetFindingsRefinementRequest( + name="name_value", + ) + + # Make the request + response = await client.get_findings_refinement(request=request) + + # Handle the response + print(response) + + +# [END chronicle_v1_generated_FindingsRefinementService_GetFindingsRefinement_async] diff --git a/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_get_findings_refinement_deployment_async.py b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_get_findings_refinement_deployment_async.py new file mode 100644 index 000000000000..d69fd95ccaa4 --- /dev/null +++ b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_get_findings_refinement_deployment_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetFindingsRefinementDeployment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-chronicle + + +# [START chronicle_v1_generated_FindingsRefinementService_GetFindingsRefinementDeployment_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import chronicle_v1 + + +async def sample_get_findings_refinement_deployment(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceAsyncClient() + + # Initialize request argument(s) + request = chronicle_v1.GetFindingsRefinementDeploymentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_findings_refinement_deployment(request=request) + + # Handle the response + print(response) + + +# [END chronicle_v1_generated_FindingsRefinementService_GetFindingsRefinementDeployment_async] diff --git a/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_get_findings_refinement_deployment_sync.py b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_get_findings_refinement_deployment_sync.py new file mode 100644 index 000000000000..0ed250886b66 --- /dev/null +++ b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_get_findings_refinement_deployment_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetFindingsRefinementDeployment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-chronicle + + +# [START chronicle_v1_generated_FindingsRefinementService_GetFindingsRefinementDeployment_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import chronicle_v1 + + +def sample_get_findings_refinement_deployment(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceClient() + + # Initialize request argument(s) + request = chronicle_v1.GetFindingsRefinementDeploymentRequest( + name="name_value", + ) + + # Make the request + response = client.get_findings_refinement_deployment(request=request) + + # Handle the response + print(response) + + +# [END chronicle_v1_generated_FindingsRefinementService_GetFindingsRefinementDeployment_sync] diff --git a/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_get_findings_refinement_sync.py b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_get_findings_refinement_sync.py new file mode 100644 index 000000000000..089de9ea2f9c --- /dev/null +++ b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_get_findings_refinement_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetFindingsRefinement +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-chronicle + + +# [START chronicle_v1_generated_FindingsRefinementService_GetFindingsRefinement_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import chronicle_v1 + + +def sample_get_findings_refinement(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceClient() + + # Initialize request argument(s) + request = chronicle_v1.GetFindingsRefinementRequest( + name="name_value", + ) + + # Make the request + response = client.get_findings_refinement(request=request) + + # Handle the response + print(response) + + +# [END chronicle_v1_generated_FindingsRefinementService_GetFindingsRefinement_sync] diff --git a/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_list_all_findings_refinement_deployments_async.py b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_list_all_findings_refinement_deployments_async.py new file mode 100644 index 000000000000..bb82f889d04a --- /dev/null +++ b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_list_all_findings_refinement_deployments_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAllFindingsRefinementDeployments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-chronicle + + +# [START chronicle_v1_generated_FindingsRefinementService_ListAllFindingsRefinementDeployments_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import chronicle_v1 + + +async def sample_list_all_findings_refinement_deployments(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceAsyncClient() + + # Initialize request argument(s) + request = chronicle_v1.ListAllFindingsRefinementDeploymentsRequest( + instance="instance_value", + ) + + # Make the request + page_result = client.list_all_findings_refinement_deployments(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END chronicle_v1_generated_FindingsRefinementService_ListAllFindingsRefinementDeployments_async] diff --git a/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_list_all_findings_refinement_deployments_sync.py b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_list_all_findings_refinement_deployments_sync.py new file mode 100644 index 000000000000..76cc883d9cd8 --- /dev/null +++ b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_list_all_findings_refinement_deployments_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAllFindingsRefinementDeployments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-chronicle + + +# [START chronicle_v1_generated_FindingsRefinementService_ListAllFindingsRefinementDeployments_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import chronicle_v1 + + +def sample_list_all_findings_refinement_deployments(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceClient() + + # Initialize request argument(s) + request = chronicle_v1.ListAllFindingsRefinementDeploymentsRequest( + instance="instance_value", + ) + + # Make the request + page_result = client.list_all_findings_refinement_deployments(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END chronicle_v1_generated_FindingsRefinementService_ListAllFindingsRefinementDeployments_sync] diff --git a/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_list_findings_refinements_async.py b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_list_findings_refinements_async.py new file mode 100644 index 000000000000..2dd48ba75727 --- /dev/null +++ b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_list_findings_refinements_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListFindingsRefinements +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-chronicle + + +# [START chronicle_v1_generated_FindingsRefinementService_ListFindingsRefinements_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import chronicle_v1 + + +async def sample_list_findings_refinements(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceAsyncClient() + + # Initialize request argument(s) + request = chronicle_v1.ListFindingsRefinementsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings_refinements(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END chronicle_v1_generated_FindingsRefinementService_ListFindingsRefinements_async] diff --git a/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_list_findings_refinements_sync.py b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_list_findings_refinements_sync.py new file mode 100644 index 000000000000..dd90f579084b --- /dev/null +++ b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_list_findings_refinements_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListFindingsRefinements +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-chronicle + + +# [START chronicle_v1_generated_FindingsRefinementService_ListFindingsRefinements_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import chronicle_v1 + + +def sample_list_findings_refinements(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceClient() + + # Initialize request argument(s) + request = chronicle_v1.ListFindingsRefinementsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_findings_refinements(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END chronicle_v1_generated_FindingsRefinementService_ListFindingsRefinements_sync] diff --git a/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_update_findings_refinement_async.py b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_update_findings_refinement_async.py new file mode 100644 index 000000000000..ff48c24f6ed7 --- /dev/null +++ b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_update_findings_refinement_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateFindingsRefinement +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-chronicle + + +# [START chronicle_v1_generated_FindingsRefinementService_UpdateFindingsRefinement_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import chronicle_v1 + + +async def sample_update_findings_refinement(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceAsyncClient() + + # Initialize request argument(s) + request = chronicle_v1.UpdateFindingsRefinementRequest() + + # Make the request + response = await client.update_findings_refinement(request=request) + + # Handle the response + print(response) + + +# [END chronicle_v1_generated_FindingsRefinementService_UpdateFindingsRefinement_async] diff --git a/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_update_findings_refinement_deployment_async.py b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_update_findings_refinement_deployment_async.py new file mode 100644 index 000000000000..4f1ba373631a --- /dev/null +++ b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_update_findings_refinement_deployment_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateFindingsRefinementDeployment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-chronicle + + +# [START chronicle_v1_generated_FindingsRefinementService_UpdateFindingsRefinementDeployment_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import chronicle_v1 + + +async def sample_update_findings_refinement_deployment(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceAsyncClient() + + # Initialize request argument(s) + findings_refinement_deployment = chronicle_v1.FindingsRefinementDeployment() + findings_refinement_deployment.name = "name_value" + + request = chronicle_v1.UpdateFindingsRefinementDeploymentRequest( + findings_refinement_deployment=findings_refinement_deployment, + ) + + # Make the request + response = await client.update_findings_refinement_deployment(request=request) + + # Handle the response + print(response) + + +# [END chronicle_v1_generated_FindingsRefinementService_UpdateFindingsRefinementDeployment_async] diff --git a/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_update_findings_refinement_deployment_sync.py b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_update_findings_refinement_deployment_sync.py new file mode 100644 index 000000000000..2e57dbfc7591 --- /dev/null +++ b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_update_findings_refinement_deployment_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateFindingsRefinementDeployment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-chronicle + + +# [START chronicle_v1_generated_FindingsRefinementService_UpdateFindingsRefinementDeployment_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import chronicle_v1 + + +def sample_update_findings_refinement_deployment(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceClient() + + # Initialize request argument(s) + findings_refinement_deployment = chronicle_v1.FindingsRefinementDeployment() + findings_refinement_deployment.name = "name_value" + + request = chronicle_v1.UpdateFindingsRefinementDeploymentRequest( + findings_refinement_deployment=findings_refinement_deployment, + ) + + # Make the request + response = client.update_findings_refinement_deployment(request=request) + + # Handle the response + print(response) + + +# [END chronicle_v1_generated_FindingsRefinementService_UpdateFindingsRefinementDeployment_sync] diff --git a/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_update_findings_refinement_sync.py b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_update_findings_refinement_sync.py new file mode 100644 index 000000000000..a633aea266b4 --- /dev/null +++ b/packages/google-cloud-chronicle/samples/generated_samples/chronicle_v1_generated_findings_refinement_service_update_findings_refinement_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateFindingsRefinement +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-chronicle + + +# [START chronicle_v1_generated_FindingsRefinementService_UpdateFindingsRefinement_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import chronicle_v1 + + +def sample_update_findings_refinement(): + # Create a client + client = chronicle_v1.FindingsRefinementServiceClient() + + # Initialize request argument(s) + request = chronicle_v1.UpdateFindingsRefinementRequest() + + # Make the request + response = client.update_findings_refinement(request=request) + + # Handle the response + print(response) + + +# [END chronicle_v1_generated_FindingsRefinementService_UpdateFindingsRefinement_sync] diff --git a/packages/google-cloud-chronicle/samples/generated_samples/snippet_metadata_google.cloud.chronicle.v1.json b/packages/google-cloud-chronicle/samples/generated_samples/snippet_metadata_google.cloud.chronicle.v1.json index 261d56eda421..3a61fb1710bb 100644 --- a/packages/google-cloud-chronicle/samples/generated_samples/snippet_metadata_google.cloud.chronicle.v1.json +++ b/packages/google-cloud-chronicle/samples/generated_samples/snippet_metadata_google.cloud.chronicle.v1.json @@ -6605,6 +6605,1479 @@ ], "title": "chronicle_v1_generated_featured_content_native_dashboard_service_list_featured_content_native_dashboards_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient", + "shortName": "FindingsRefinementServiceAsyncClient" + }, + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient.compute_all_findings_refinement_activities", + "method": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService.ComputeAllFindingsRefinementActivities", + "service": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService", + "shortName": "FindingsRefinementService" + }, + "shortName": "ComputeAllFindingsRefinementActivities" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.chronicle_v1.types.ComputeAllFindingsRefinementActivitiesRequest" + }, + { + "name": "instance", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.chronicle_v1.types.ComputeAllFindingsRefinementActivitiesResponse", + "shortName": "compute_all_findings_refinement_activities" + }, + "description": "Sample for ComputeAllFindingsRefinementActivities", + "file": "chronicle_v1_generated_findings_refinement_service_compute_all_findings_refinement_activities_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chronicle_v1_generated_FindingsRefinementService_ComputeAllFindingsRefinementActivities_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chronicle_v1_generated_findings_refinement_service_compute_all_findings_refinement_activities_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceClient", + "shortName": "FindingsRefinementServiceClient" + }, + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceClient.compute_all_findings_refinement_activities", + "method": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService.ComputeAllFindingsRefinementActivities", + "service": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService", + "shortName": "FindingsRefinementService" + }, + "shortName": "ComputeAllFindingsRefinementActivities" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.chronicle_v1.types.ComputeAllFindingsRefinementActivitiesRequest" + }, + { + "name": "instance", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.chronicle_v1.types.ComputeAllFindingsRefinementActivitiesResponse", + "shortName": "compute_all_findings_refinement_activities" + }, + "description": "Sample for ComputeAllFindingsRefinementActivities", + "file": "chronicle_v1_generated_findings_refinement_service_compute_all_findings_refinement_activities_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chronicle_v1_generated_FindingsRefinementService_ComputeAllFindingsRefinementActivities_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chronicle_v1_generated_findings_refinement_service_compute_all_findings_refinement_activities_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient", + "shortName": "FindingsRefinementServiceAsyncClient" + }, + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient.compute_findings_refinement_activity", + "method": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService.ComputeFindingsRefinementActivity", + "service": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService", + "shortName": "FindingsRefinementService" + }, + "shortName": "ComputeFindingsRefinementActivity" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.chronicle_v1.types.ComputeFindingsRefinementActivityRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.chronicle_v1.types.ComputeFindingsRefinementActivityResponse", + "shortName": "compute_findings_refinement_activity" + }, + "description": "Sample for ComputeFindingsRefinementActivity", + "file": "chronicle_v1_generated_findings_refinement_service_compute_findings_refinement_activity_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chronicle_v1_generated_FindingsRefinementService_ComputeFindingsRefinementActivity_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chronicle_v1_generated_findings_refinement_service_compute_findings_refinement_activity_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceClient", + "shortName": "FindingsRefinementServiceClient" + }, + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceClient.compute_findings_refinement_activity", + "method": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService.ComputeFindingsRefinementActivity", + "service": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService", + "shortName": "FindingsRefinementService" + }, + "shortName": "ComputeFindingsRefinementActivity" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.chronicle_v1.types.ComputeFindingsRefinementActivityRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.chronicle_v1.types.ComputeFindingsRefinementActivityResponse", + "shortName": "compute_findings_refinement_activity" + }, + "description": "Sample for ComputeFindingsRefinementActivity", + "file": "chronicle_v1_generated_findings_refinement_service_compute_findings_refinement_activity_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chronicle_v1_generated_FindingsRefinementService_ComputeFindingsRefinementActivity_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chronicle_v1_generated_findings_refinement_service_compute_findings_refinement_activity_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient", + "shortName": "FindingsRefinementServiceAsyncClient" + }, + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient.create_findings_refinement", + "method": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService.CreateFindingsRefinement", + "service": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService", + "shortName": "FindingsRefinementService" + }, + "shortName": "CreateFindingsRefinement" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.chronicle_v1.types.CreateFindingsRefinementRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "findings_refinement", + "type": "google.cloud.chronicle_v1.types.FindingsRefinement" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.chronicle_v1.types.FindingsRefinement", + "shortName": "create_findings_refinement" + }, + "description": "Sample for CreateFindingsRefinement", + "file": "chronicle_v1_generated_findings_refinement_service_create_findings_refinement_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chronicle_v1_generated_FindingsRefinementService_CreateFindingsRefinement_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chronicle_v1_generated_findings_refinement_service_create_findings_refinement_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceClient", + "shortName": "FindingsRefinementServiceClient" + }, + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceClient.create_findings_refinement", + "method": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService.CreateFindingsRefinement", + "service": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService", + "shortName": "FindingsRefinementService" + }, + "shortName": "CreateFindingsRefinement" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.chronicle_v1.types.CreateFindingsRefinementRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "findings_refinement", + "type": "google.cloud.chronicle_v1.types.FindingsRefinement" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.chronicle_v1.types.FindingsRefinement", + "shortName": "create_findings_refinement" + }, + "description": "Sample for CreateFindingsRefinement", + "file": "chronicle_v1_generated_findings_refinement_service_create_findings_refinement_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chronicle_v1_generated_FindingsRefinementService_CreateFindingsRefinement_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chronicle_v1_generated_findings_refinement_service_create_findings_refinement_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient", + "shortName": "FindingsRefinementServiceAsyncClient" + }, + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient.get_findings_refinement_deployment", + "method": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService.GetFindingsRefinementDeployment", + "service": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService", + "shortName": "FindingsRefinementService" + }, + "shortName": "GetFindingsRefinementDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.chronicle_v1.types.GetFindingsRefinementDeploymentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.chronicle_v1.types.FindingsRefinementDeployment", + "shortName": "get_findings_refinement_deployment" + }, + "description": "Sample for GetFindingsRefinementDeployment", + "file": "chronicle_v1_generated_findings_refinement_service_get_findings_refinement_deployment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chronicle_v1_generated_FindingsRefinementService_GetFindingsRefinementDeployment_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chronicle_v1_generated_findings_refinement_service_get_findings_refinement_deployment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceClient", + "shortName": "FindingsRefinementServiceClient" + }, + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceClient.get_findings_refinement_deployment", + "method": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService.GetFindingsRefinementDeployment", + "service": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService", + "shortName": "FindingsRefinementService" + }, + "shortName": "GetFindingsRefinementDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.chronicle_v1.types.GetFindingsRefinementDeploymentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.chronicle_v1.types.FindingsRefinementDeployment", + "shortName": "get_findings_refinement_deployment" + }, + "description": "Sample for GetFindingsRefinementDeployment", + "file": "chronicle_v1_generated_findings_refinement_service_get_findings_refinement_deployment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chronicle_v1_generated_FindingsRefinementService_GetFindingsRefinementDeployment_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chronicle_v1_generated_findings_refinement_service_get_findings_refinement_deployment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient", + "shortName": "FindingsRefinementServiceAsyncClient" + }, + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient.get_findings_refinement", + "method": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService.GetFindingsRefinement", + "service": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService", + "shortName": "FindingsRefinementService" + }, + "shortName": "GetFindingsRefinement" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.chronicle_v1.types.GetFindingsRefinementRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.chronicle_v1.types.FindingsRefinement", + "shortName": "get_findings_refinement" + }, + "description": "Sample for GetFindingsRefinement", + "file": "chronicle_v1_generated_findings_refinement_service_get_findings_refinement_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chronicle_v1_generated_FindingsRefinementService_GetFindingsRefinement_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chronicle_v1_generated_findings_refinement_service_get_findings_refinement_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceClient", + "shortName": "FindingsRefinementServiceClient" + }, + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceClient.get_findings_refinement", + "method": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService.GetFindingsRefinement", + "service": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService", + "shortName": "FindingsRefinementService" + }, + "shortName": "GetFindingsRefinement" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.chronicle_v1.types.GetFindingsRefinementRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.chronicle_v1.types.FindingsRefinement", + "shortName": "get_findings_refinement" + }, + "description": "Sample for GetFindingsRefinement", + "file": "chronicle_v1_generated_findings_refinement_service_get_findings_refinement_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chronicle_v1_generated_FindingsRefinementService_GetFindingsRefinement_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chronicle_v1_generated_findings_refinement_service_get_findings_refinement_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient", + "shortName": "FindingsRefinementServiceAsyncClient" + }, + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient.list_all_findings_refinement_deployments", + "method": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService.ListAllFindingsRefinementDeployments", + "service": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService", + "shortName": "FindingsRefinementService" + }, + "shortName": "ListAllFindingsRefinementDeployments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.chronicle_v1.types.ListAllFindingsRefinementDeploymentsRequest" + }, + { + "name": "instance", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.chronicle_v1.services.findings_refinement_service.pagers.ListAllFindingsRefinementDeploymentsAsyncPager", + "shortName": "list_all_findings_refinement_deployments" + }, + "description": "Sample for ListAllFindingsRefinementDeployments", + "file": "chronicle_v1_generated_findings_refinement_service_list_all_findings_refinement_deployments_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chronicle_v1_generated_FindingsRefinementService_ListAllFindingsRefinementDeployments_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chronicle_v1_generated_findings_refinement_service_list_all_findings_refinement_deployments_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceClient", + "shortName": "FindingsRefinementServiceClient" + }, + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceClient.list_all_findings_refinement_deployments", + "method": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService.ListAllFindingsRefinementDeployments", + "service": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService", + "shortName": "FindingsRefinementService" + }, + "shortName": "ListAllFindingsRefinementDeployments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.chronicle_v1.types.ListAllFindingsRefinementDeploymentsRequest" + }, + { + "name": "instance", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.chronicle_v1.services.findings_refinement_service.pagers.ListAllFindingsRefinementDeploymentsPager", + "shortName": "list_all_findings_refinement_deployments" + }, + "description": "Sample for ListAllFindingsRefinementDeployments", + "file": "chronicle_v1_generated_findings_refinement_service_list_all_findings_refinement_deployments_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chronicle_v1_generated_FindingsRefinementService_ListAllFindingsRefinementDeployments_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chronicle_v1_generated_findings_refinement_service_list_all_findings_refinement_deployments_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient", + "shortName": "FindingsRefinementServiceAsyncClient" + }, + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient.list_findings_refinements", + "method": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService.ListFindingsRefinements", + "service": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService", + "shortName": "FindingsRefinementService" + }, + "shortName": "ListFindingsRefinements" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.chronicle_v1.types.ListFindingsRefinementsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.chronicle_v1.services.findings_refinement_service.pagers.ListFindingsRefinementsAsyncPager", + "shortName": "list_findings_refinements" + }, + "description": "Sample for ListFindingsRefinements", + "file": "chronicle_v1_generated_findings_refinement_service_list_findings_refinements_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chronicle_v1_generated_FindingsRefinementService_ListFindingsRefinements_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chronicle_v1_generated_findings_refinement_service_list_findings_refinements_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceClient", + "shortName": "FindingsRefinementServiceClient" + }, + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceClient.list_findings_refinements", + "method": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService.ListFindingsRefinements", + "service": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService", + "shortName": "FindingsRefinementService" + }, + "shortName": "ListFindingsRefinements" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.chronicle_v1.types.ListFindingsRefinementsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.chronicle_v1.services.findings_refinement_service.pagers.ListFindingsRefinementsPager", + "shortName": "list_findings_refinements" + }, + "description": "Sample for ListFindingsRefinements", + "file": "chronicle_v1_generated_findings_refinement_service_list_findings_refinements_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chronicle_v1_generated_FindingsRefinementService_ListFindingsRefinements_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "chronicle_v1_generated_findings_refinement_service_list_findings_refinements_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient", + "shortName": "FindingsRefinementServiceAsyncClient" + }, + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient.update_findings_refinement_deployment", + "method": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService.UpdateFindingsRefinementDeployment", + "service": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService", + "shortName": "FindingsRefinementService" + }, + "shortName": "UpdateFindingsRefinementDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.chronicle_v1.types.UpdateFindingsRefinementDeploymentRequest" + }, + { + "name": "findings_refinement_deployment", + "type": "google.cloud.chronicle_v1.types.FindingsRefinementDeployment" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.chronicle_v1.types.FindingsRefinementDeployment", + "shortName": "update_findings_refinement_deployment" + }, + "description": "Sample for UpdateFindingsRefinementDeployment", + "file": "chronicle_v1_generated_findings_refinement_service_update_findings_refinement_deployment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chronicle_v1_generated_FindingsRefinementService_UpdateFindingsRefinementDeployment_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": "chronicle_v1_generated_findings_refinement_service_update_findings_refinement_deployment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceClient", + "shortName": "FindingsRefinementServiceClient" + }, + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceClient.update_findings_refinement_deployment", + "method": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService.UpdateFindingsRefinementDeployment", + "service": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService", + "shortName": "FindingsRefinementService" + }, + "shortName": "UpdateFindingsRefinementDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.chronicle_v1.types.UpdateFindingsRefinementDeploymentRequest" + }, + { + "name": "findings_refinement_deployment", + "type": "google.cloud.chronicle_v1.types.FindingsRefinementDeployment" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.chronicle_v1.types.FindingsRefinementDeployment", + "shortName": "update_findings_refinement_deployment" + }, + "description": "Sample for UpdateFindingsRefinementDeployment", + "file": "chronicle_v1_generated_findings_refinement_service_update_findings_refinement_deployment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chronicle_v1_generated_FindingsRefinementService_UpdateFindingsRefinementDeployment_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": "chronicle_v1_generated_findings_refinement_service_update_findings_refinement_deployment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient", + "shortName": "FindingsRefinementServiceAsyncClient" + }, + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceAsyncClient.update_findings_refinement", + "method": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService.UpdateFindingsRefinement", + "service": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService", + "shortName": "FindingsRefinementService" + }, + "shortName": "UpdateFindingsRefinement" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.chronicle_v1.types.UpdateFindingsRefinementRequest" + }, + { + "name": "findings_refinement", + "type": "google.cloud.chronicle_v1.types.FindingsRefinement" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.chronicle_v1.types.FindingsRefinement", + "shortName": "update_findings_refinement" + }, + "description": "Sample for UpdateFindingsRefinement", + "file": "chronicle_v1_generated_findings_refinement_service_update_findings_refinement_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chronicle_v1_generated_FindingsRefinementService_UpdateFindingsRefinement_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": "chronicle_v1_generated_findings_refinement_service_update_findings_refinement_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceClient", + "shortName": "FindingsRefinementServiceClient" + }, + "fullName": "google.cloud.chronicle_v1.FindingsRefinementServiceClient.update_findings_refinement", + "method": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService.UpdateFindingsRefinement", + "service": { + "fullName": "google.cloud.chronicle.v1.FindingsRefinementService", + "shortName": "FindingsRefinementService" + }, + "shortName": "UpdateFindingsRefinement" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.chronicle_v1.types.UpdateFindingsRefinementRequest" + }, + { + "name": "findings_refinement", + "type": "google.cloud.chronicle_v1.types.FindingsRefinement" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.chronicle_v1.types.FindingsRefinement", + "shortName": "update_findings_refinement" + }, + "description": "Sample for UpdateFindingsRefinement", + "file": "chronicle_v1_generated_findings_refinement_service_update_findings_refinement_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "chronicle_v1_generated_FindingsRefinementService_UpdateFindingsRefinement_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": "chronicle_v1_generated_findings_refinement_service_update_findings_refinement_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-chronicle/tests/unit/gapic/chronicle_v1/test_findings_refinement_service.py b/packages/google-cloud-chronicle/tests/unit/gapic/chronicle_v1/test_findings_refinement_service.py new file mode 100644 index 000000000000..a2274fc465b3 --- /dev/null +++ b/packages/google-cloud-chronicle/tests/unit/gapic/chronicle_v1/test_findings_refinement_service.py @@ -0,0 +1,11289 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.auth +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.type.interval_pb2 as interval_pb2 # type: ignore +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account + +from google.cloud.chronicle_v1.services.findings_refinement_service import ( + FindingsRefinementServiceAsyncClient, + FindingsRefinementServiceClient, + pagers, + transports, +) +from google.cloud.chronicle_v1.types import findings_refinement +from google.cloud.chronicle_v1.types import ( + findings_refinement as gcc_findings_refinement, +) + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +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" + custom_endpoint = ".custom" + + assert FindingsRefinementServiceClient._get_default_mtls_endpoint(None) is None + assert ( + FindingsRefinementServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + FindingsRefinementServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + FindingsRefinementServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + FindingsRefinementServiceClient._get_default_mtls_endpoint( + sandbox_mtls_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + FindingsRefinementServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + assert ( + FindingsRefinementServiceClient._get_default_mtls_endpoint(custom_endpoint) + == custom_endpoint + ) + + +def test__read_environment_variables(): + assert FindingsRefinementServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert FindingsRefinementServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert FindingsRefinementServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + FindingsRefinementServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert FindingsRefinementServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert FindingsRefinementServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert FindingsRefinementServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert FindingsRefinementServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + FindingsRefinementServiceClient._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 FindingsRefinementServiceClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=True + ): + assert FindingsRefinementServiceClient._use_client_cert_effective() is True + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=False + ): + assert FindingsRefinementServiceClient._use_client_cert_effective() is False + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert FindingsRefinementServiceClient._use_client_cert_effective() is True + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): + assert FindingsRefinementServiceClient._use_client_cert_effective() is False + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert FindingsRefinementServiceClient._use_client_cert_effective() is True + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} + ): + assert FindingsRefinementServiceClient._use_client_cert_effective() is False + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert FindingsRefinementServiceClient._use_client_cert_effective() is True + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} + ): + assert FindingsRefinementServiceClient._use_client_cert_effective() is False + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert FindingsRefinementServiceClient._use_client_cert_effective() is False + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + with pytest.raises(ValueError): + FindingsRefinementServiceClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + assert FindingsRefinementServiceClient._use_client_cert_effective() is False + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert ( + FindingsRefinementServiceClient._use_client_cert_effective() + is False + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert FindingsRefinementServiceClient._get_client_cert_source(None, False) is None + assert ( + FindingsRefinementServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + FindingsRefinementServiceClient._get_client_cert_source( + mock_provided_cert_source, True + ) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + FindingsRefinementServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + FindingsRefinementServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + FindingsRefinementServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(FindingsRefinementServiceClient), +) +@mock.patch.object( + FindingsRefinementServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(FindingsRefinementServiceAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = FindingsRefinementServiceClient._DEFAULT_UNIVERSE + default_endpoint = ( + FindingsRefinementServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) + mock_universe = "bar.com" + mock_endpoint = FindingsRefinementServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + FindingsRefinementServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + FindingsRefinementServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == FindingsRefinementServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + FindingsRefinementServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + FindingsRefinementServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == FindingsRefinementServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + FindingsRefinementServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == FindingsRefinementServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + FindingsRefinementServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + FindingsRefinementServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + FindingsRefinementServiceClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + FindingsRefinementServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + FindingsRefinementServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + FindingsRefinementServiceClient._get_universe_domain(None, None) + == FindingsRefinementServiceClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + FindingsRefinementServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = FindingsRefinementServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = FindingsRefinementServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (FindingsRefinementServiceClient, "grpc"), + (FindingsRefinementServiceAsyncClient, "grpc_asyncio"), + (FindingsRefinementServiceClient, "rest"), + ], +) +def test_findings_refinement_service_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "chronicle.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://chronicle.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.FindingsRefinementServiceGrpcTransport, "grpc"), + (transports.FindingsRefinementServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.FindingsRefinementServiceRestTransport, "rest"), + ], +) +def test_findings_refinement_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (FindingsRefinementServiceClient, "grpc"), + (FindingsRefinementServiceAsyncClient, "grpc_asyncio"), + (FindingsRefinementServiceClient, "rest"), + ], +) +def test_findings_refinement_service_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "chronicle.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://chronicle.googleapis.com" + ) + + +def test_findings_refinement_service_client_get_transport_class(): + transport = FindingsRefinementServiceClient.get_transport_class() + available_transports = [ + transports.FindingsRefinementServiceGrpcTransport, + transports.FindingsRefinementServiceRestTransport, + ] + assert transport in available_transports + + transport = FindingsRefinementServiceClient.get_transport_class("grpc") + assert transport == transports.FindingsRefinementServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + FindingsRefinementServiceClient, + transports.FindingsRefinementServiceGrpcTransport, + "grpc", + ), + ( + FindingsRefinementServiceAsyncClient, + transports.FindingsRefinementServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + FindingsRefinementServiceClient, + transports.FindingsRefinementServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + FindingsRefinementServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(FindingsRefinementServiceClient), +) +@mock.patch.object( + FindingsRefinementServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(FindingsRefinementServiceAsyncClient), +) +def test_findings_refinement_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object( + FindingsRefinementServiceClient, "get_transport_class" + ) as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object( + FindingsRefinementServiceClient, "get_transport_class" + ) as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check 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 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", + [ + ( + FindingsRefinementServiceClient, + transports.FindingsRefinementServiceGrpcTransport, + "grpc", + "true", + ), + ( + FindingsRefinementServiceAsyncClient, + transports.FindingsRefinementServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + FindingsRefinementServiceClient, + transports.FindingsRefinementServiceGrpcTransport, + "grpc", + "false", + ), + ( + FindingsRefinementServiceAsyncClient, + transports.FindingsRefinementServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + FindingsRefinementServiceClient, + transports.FindingsRefinementServiceRestTransport, + "rest", + "true", + ), + ( + FindingsRefinementServiceClient, + transports.FindingsRefinementServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + FindingsRefinementServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(FindingsRefinementServiceClient), +) +@mock.patch.object( + FindingsRefinementServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(FindingsRefinementServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_findings_refinement_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", + [FindingsRefinementServiceClient, FindingsRefinementServiceAsyncClient], +) +@mock.patch.object( + FindingsRefinementServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FindingsRefinementServiceClient), +) +@mock.patch.object( + FindingsRefinementServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FindingsRefinementServiceAsyncClient), +) +def test_findings_refinement_service_client_get_mtls_endpoint_and_cert_source( + client_class, +): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + 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 cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # 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`" + ) + + +@pytest.mark.parametrize( + "client_class", + [FindingsRefinementServiceClient, FindingsRefinementServiceAsyncClient], +) +@mock.patch.object( + FindingsRefinementServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(FindingsRefinementServiceClient), +) +@mock.patch.object( + FindingsRefinementServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(FindingsRefinementServiceAsyncClient), +) +def test_findings_refinement_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = FindingsRefinementServiceClient._DEFAULT_UNIVERSE + default_endpoint = ( + FindingsRefinementServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) + mock_universe = "bar.com" + mock_endpoint = FindingsRefinementServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + 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", + [ + ( + FindingsRefinementServiceClient, + transports.FindingsRefinementServiceGrpcTransport, + "grpc", + ), + ( + FindingsRefinementServiceAsyncClient, + transports.FindingsRefinementServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + FindingsRefinementServiceClient, + transports.FindingsRefinementServiceRestTransport, + "rest", + ), + ], +) +def test_findings_refinement_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + FindingsRefinementServiceClient, + transports.FindingsRefinementServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + FindingsRefinementServiceAsyncClient, + transports.FindingsRefinementServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + FindingsRefinementServiceClient, + transports.FindingsRefinementServiceRestTransport, + "rest", + None, + ), + ], +) +def test_findings_refinement_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_findings_refinement_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.chronicle_v1.services.findings_refinement_service.transports.FindingsRefinementServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = FindingsRefinementServiceClient( + 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", + [ + ( + FindingsRefinementServiceClient, + transports.FindingsRefinementServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + FindingsRefinementServiceAsyncClient, + transports.FindingsRefinementServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_findings_refinement_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "chronicle.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/chronicle", + "https://www.googleapis.com/auth/chronicle.readonly", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=None, + default_host="chronicle.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.GetFindingsRefinementRequest(), + {}, + ], +) +def test_get_findings_refinement(request_type, transport: str = "grpc"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_findings_refinement), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = findings_refinement.FindingsRefinement( + name="name_value", + display_name="display_name_value", + type_=findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION, + query="query_value", + ) + response = client.get_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = findings_refinement.GetFindingsRefinementRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, findings_refinement.FindingsRefinement) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert ( + response.type_ == findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION + ) + assert response.query == "query_value" + + +def test_get_findings_refinement_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = findings_refinement.GetFindingsRefinementRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_findings_refinement), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_findings_refinement(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.GetFindingsRefinementRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_findings_refinement_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_findings_refinement + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_findings_refinement + ] = mock_rpc + request = {} + client.get_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_findings_refinement(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_findings_refinement_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_findings_refinement + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_findings_refinement + ] = mock_rpc + + request = {} + await client.get_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_findings_refinement(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.GetFindingsRefinementRequest(), + {}, + ], +) +async def test_get_findings_refinement_async( + request_type, transport: str = "grpc_asyncio" +): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_findings_refinement), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.FindingsRefinement( + name="name_value", + display_name="display_name_value", + type_=findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION, + query="query_value", + ) + ) + response = await client.get_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = findings_refinement.GetFindingsRefinementRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, findings_refinement.FindingsRefinement) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert ( + response.type_ == findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION + ) + assert response.query == "query_value" + + +def test_get_findings_refinement_field_headers(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = findings_refinement.GetFindingsRefinementRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_findings_refinement), "__call__" + ) as call: + call.return_value = findings_refinement.FindingsRefinement() + client.get_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_findings_refinement_field_headers_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = findings_refinement.GetFindingsRefinementRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_findings_refinement), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.FindingsRefinement() + ) + await client.get_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_findings_refinement_flattened(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_findings_refinement), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = findings_refinement.FindingsRefinement() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_findings_refinement( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_findings_refinement_flattened_error(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_findings_refinement( + findings_refinement.GetFindingsRefinementRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_findings_refinement_flattened_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_findings_refinement), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = findings_refinement.FindingsRefinement() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.FindingsRefinement() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_findings_refinement( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_findings_refinement_flattened_error_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_findings_refinement( + findings_refinement.GetFindingsRefinementRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.ListFindingsRefinementsRequest(), + {}, + ], +) +def test_list_findings_refinements(request_type, transport: str = "grpc"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_refinements), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = findings_refinement.ListFindingsRefinementsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_findings_refinements(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = findings_refinement.ListFindingsRefinementsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsRefinementsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_findings_refinements_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = findings_refinement.ListFindingsRefinementsRequest( + 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_findings_refinements), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_findings_refinements(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.ListFindingsRefinementsRequest( + parent="parent_value", + page_token="page_token_value", + ) + assert args[0] == request_msg + + +def test_list_findings_refinements_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap 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_refinements + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.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_refinements + ] = mock_rpc + request = {} + client.list_findings_refinements(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_findings_refinements(request) + + # Establish that a new wrapper was 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_refinements_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all 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_refinements + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_findings_refinements + ] = mock_rpc + + request = {} + await client.list_findings_refinements(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_findings_refinements(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.ListFindingsRefinementsRequest(), + {}, + ], +) +async def test_list_findings_refinements_async( + request_type, transport: str = "grpc_asyncio" +): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty 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_refinements), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.ListFindingsRefinementsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_findings_refinements(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = findings_refinement.ListFindingsRefinementsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsRefinementsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_findings_refinements_field_headers(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = findings_refinement.ListFindingsRefinementsRequest() + + 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_refinements), "__call__" + ) as call: + call.return_value = findings_refinement.ListFindingsRefinementsResponse() + client.list_findings_refinements(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was 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_refinements_field_headers_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = findings_refinement.ListFindingsRefinementsRequest() + + 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_refinements), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.ListFindingsRefinementsResponse() + ) + await client.list_findings_refinements(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that 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_refinements_flattened(): + client = FindingsRefinementServiceClient( + 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_refinements), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = findings_refinement.ListFindingsRefinementsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_findings_refinements( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_refinements_flattened_error(): + client = FindingsRefinementServiceClient( + credentials=ga_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_refinements( + findings_refinement.ListFindingsRefinementsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_findings_refinements_flattened_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings_refinements), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = findings_refinement.ListFindingsRefinementsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.ListFindingsRefinementsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_findings_refinements( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_refinements_flattened_error_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_findings_refinements( + findings_refinement.ListFindingsRefinementsRequest(), + parent="parent_value", + ) + + +def test_list_findings_refinements_pager(transport_name: str = "grpc"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.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_refinements), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + findings_refinement.ListFindingsRefinementsResponse( + findings_refinements=[ + findings_refinement.FindingsRefinement(), + findings_refinement.FindingsRefinement(), + findings_refinement.FindingsRefinement(), + ], + next_page_token="abc", + ), + findings_refinement.ListFindingsRefinementsResponse( + findings_refinements=[], + next_page_token="def", + ), + findings_refinement.ListFindingsRefinementsResponse( + findings_refinements=[ + findings_refinement.FindingsRefinement(), + ], + next_page_token="ghi", + ), + findings_refinement.ListFindingsRefinementsResponse( + findings_refinements=[ + findings_refinement.FindingsRefinement(), + findings_refinement.FindingsRefinement(), + ], + ), + 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_refinements( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, findings_refinement.FindingsRefinement) for i in results + ) + + +def test_list_findings_refinements_pages(transport_name: str = "grpc"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.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_refinements), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + findings_refinement.ListFindingsRefinementsResponse( + findings_refinements=[ + findings_refinement.FindingsRefinement(), + findings_refinement.FindingsRefinement(), + findings_refinement.FindingsRefinement(), + ], + next_page_token="abc", + ), + findings_refinement.ListFindingsRefinementsResponse( + findings_refinements=[], + next_page_token="def", + ), + findings_refinement.ListFindingsRefinementsResponse( + findings_refinements=[ + findings_refinement.FindingsRefinement(), + ], + next_page_token="ghi", + ), + findings_refinement.ListFindingsRefinementsResponse( + findings_refinements=[ + findings_refinement.FindingsRefinement(), + findings_refinement.FindingsRefinement(), + ], + ), + RuntimeError, + ) + pages = list(client.list_findings_refinements(request={}).pages) + 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_refinements_async_pager(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings_refinements), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + findings_refinement.ListFindingsRefinementsResponse( + findings_refinements=[ + findings_refinement.FindingsRefinement(), + findings_refinement.FindingsRefinement(), + findings_refinement.FindingsRefinement(), + ], + next_page_token="abc", + ), + findings_refinement.ListFindingsRefinementsResponse( + findings_refinements=[], + next_page_token="def", + ), + findings_refinement.ListFindingsRefinementsResponse( + findings_refinements=[ + findings_refinement.FindingsRefinement(), + ], + next_page_token="ghi", + ), + findings_refinement.ListFindingsRefinementsResponse( + findings_refinements=[ + findings_refinement.FindingsRefinement(), + findings_refinement.FindingsRefinement(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_findings_refinements( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, findings_refinement.FindingsRefinement) for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_findings_refinements_async_pages(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_findings_refinements), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + findings_refinement.ListFindingsRefinementsResponse( + findings_refinements=[ + findings_refinement.FindingsRefinement(), + findings_refinement.FindingsRefinement(), + findings_refinement.FindingsRefinement(), + ], + next_page_token="abc", + ), + findings_refinement.ListFindingsRefinementsResponse( + findings_refinements=[], + next_page_token="def", + ), + findings_refinement.ListFindingsRefinementsResponse( + findings_refinements=[ + findings_refinement.FindingsRefinement(), + ], + next_page_token="ghi", + ), + findings_refinement.ListFindingsRefinementsResponse( + findings_refinements=[ + findings_refinement.FindingsRefinement(), + findings_refinement.FindingsRefinement(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_findings_refinements(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + gcc_findings_refinement.CreateFindingsRefinementRequest(), + {}, + ], +) +def test_create_findings_refinement(request_type, transport: str = "grpc"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_findings_refinement), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_findings_refinement.FindingsRefinement( + name="name_value", + display_name="display_name_value", + type_=gcc_findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION, + query="query_value", + ) + response = client.create_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcc_findings_refinement.CreateFindingsRefinementRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_findings_refinement.FindingsRefinement) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert ( + response.type_ + == gcc_findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION + ) + assert response.query == "query_value" + + +def test_create_findings_refinement_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcc_findings_refinement.CreateFindingsRefinementRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_findings_refinement), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_findings_refinement(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcc_findings_refinement.CreateFindingsRefinementRequest( + parent="parent_value", + ) + assert args[0] == request_msg + + +def test_create_findings_refinement_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_findings_refinement + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_findings_refinement + ] = mock_rpc + request = {} + client.create_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_findings_refinement(request) + + # Establish that a new wrapper 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_findings_refinement_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_findings_refinement + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_findings_refinement + ] = mock_rpc + + request = {} + await client.create_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_findings_refinement(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + gcc_findings_refinement.CreateFindingsRefinementRequest(), + {}, + ], +) +async def test_create_findings_refinement_async( + request_type, transport: str = "grpc_asyncio" +): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_findings_refinement), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_findings_refinement.FindingsRefinement( + name="name_value", + display_name="display_name_value", + type_=gcc_findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION, + query="query_value", + ) + ) + response = await client.create_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcc_findings_refinement.CreateFindingsRefinementRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_findings_refinement.FindingsRefinement) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert ( + response.type_ + == gcc_findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION + ) + assert response.query == "query_value" + + +def test_create_findings_refinement_field_headers(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcc_findings_refinement.CreateFindingsRefinementRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_findings_refinement), "__call__" + ) as call: + call.return_value = gcc_findings_refinement.FindingsRefinement() + client.create_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_findings_refinement_field_headers_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcc_findings_refinement.CreateFindingsRefinementRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_findings_refinement), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_findings_refinement.FindingsRefinement() + ) + await client.create_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_findings_refinement_flattened(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_findings_refinement), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_findings_refinement.FindingsRefinement() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_findings_refinement( + parent="parent_value", + findings_refinement=gcc_findings_refinement.FindingsRefinement( + name="name_value" + ), + ) + + # Establish that the underlying call was made with the expected + # request object 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].findings_refinement + mock_val = gcc_findings_refinement.FindingsRefinement(name="name_value") + assert arg == mock_val + + +def test_create_findings_refinement_flattened_error(): + client = FindingsRefinementServiceClient( + credentials=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_findings_refinement( + gcc_findings_refinement.CreateFindingsRefinementRequest(), + parent="parent_value", + findings_refinement=gcc_findings_refinement.FindingsRefinement( + name="name_value" + ), + ) + + +@pytest.mark.asyncio +async def test_create_findings_refinement_flattened_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_findings_refinement), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_findings_refinement.FindingsRefinement() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_findings_refinement.FindingsRefinement() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_findings_refinement( + parent="parent_value", + findings_refinement=gcc_findings_refinement.FindingsRefinement( + name="name_value" + ), + ) + + # Establish that the underlying call was made with the expected + # request 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].findings_refinement + mock_val = gcc_findings_refinement.FindingsRefinement(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_findings_refinement_flattened_error_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_findings_refinement( + gcc_findings_refinement.CreateFindingsRefinementRequest(), + parent="parent_value", + findings_refinement=gcc_findings_refinement.FindingsRefinement( + name="name_value" + ), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcc_findings_refinement.UpdateFindingsRefinementRequest(), + {}, + ], +) +def test_update_findings_refinement(request_type, transport: str = "grpc"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_findings_refinement), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_findings_refinement.FindingsRefinement( + name="name_value", + display_name="display_name_value", + type_=gcc_findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION, + query="query_value", + ) + response = client.update_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcc_findings_refinement.UpdateFindingsRefinementRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_findings_refinement.FindingsRefinement) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert ( + response.type_ + == gcc_findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION + ) + assert response.query == "query_value" + + +def test_update_findings_refinement_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = gcc_findings_refinement.UpdateFindingsRefinementRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_findings_refinement), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_findings_refinement(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcc_findings_refinement.UpdateFindingsRefinementRequest() + assert args[0] == request_msg + + +def test_update_findings_refinement_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_findings_refinement + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_findings_refinement + ] = mock_rpc + request = {} + client.update_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_findings_refinement(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_findings_refinement_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_findings_refinement + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_findings_refinement + ] = mock_rpc + + request = {} + await client.update_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_findings_refinement(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + gcc_findings_refinement.UpdateFindingsRefinementRequest(), + {}, + ], +) +async def test_update_findings_refinement_async( + request_type, transport: str = "grpc_asyncio" +): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_findings_refinement), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_findings_refinement.FindingsRefinement( + name="name_value", + display_name="display_name_value", + type_=gcc_findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION, + query="query_value", + ) + ) + response = await client.update_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcc_findings_refinement.UpdateFindingsRefinementRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_findings_refinement.FindingsRefinement) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert ( + response.type_ + == gcc_findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION + ) + assert response.query == "query_value" + + +def test_update_findings_refinement_field_headers(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcc_findings_refinement.UpdateFindingsRefinementRequest() + + request.findings_refinement.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_findings_refinement), "__call__" + ) as call: + call.return_value = gcc_findings_refinement.FindingsRefinement() + client.update_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "findings_refinement.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_findings_refinement_field_headers_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcc_findings_refinement.UpdateFindingsRefinementRequest() + + request.findings_refinement.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_findings_refinement), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_findings_refinement.FindingsRefinement() + ) + await client.update_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "findings_refinement.name=name_value", + ) in kw["metadata"] + + +def test_update_findings_refinement_flattened(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_findings_refinement), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_findings_refinement.FindingsRefinement() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_findings_refinement( + findings_refinement=gcc_findings_refinement.FindingsRefinement( + name="name_value" + ), + update_mask=field_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].findings_refinement + mock_val = gcc_findings_refinement.FindingsRefinement(name="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_findings_refinement_flattened_error(): + client = FindingsRefinementServiceClient( + credentials=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_findings_refinement( + gcc_findings_refinement.UpdateFindingsRefinementRequest(), + findings_refinement=gcc_findings_refinement.FindingsRefinement( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_findings_refinement_flattened_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_findings_refinement), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_findings_refinement.FindingsRefinement() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_findings_refinement.FindingsRefinement() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_findings_refinement( + findings_refinement=gcc_findings_refinement.FindingsRefinement( + name="name_value" + ), + update_mask=field_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].findings_refinement + mock_val = gcc_findings_refinement.FindingsRefinement(name="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_findings_refinement_flattened_error_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_findings_refinement( + gcc_findings_refinement.UpdateFindingsRefinementRequest(), + findings_refinement=gcc_findings_refinement.FindingsRefinement( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.GetFindingsRefinementDeploymentRequest(), + {}, + ], +) +def test_get_findings_refinement_deployment(request_type, transport: str = "grpc"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_findings_refinement_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = findings_refinement.FindingsRefinementDeployment( + name="name_value", + enabled=True, + archived=True, + ) + response = client.get_findings_refinement_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = findings_refinement.GetFindingsRefinementDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, findings_refinement.FindingsRefinementDeployment) + assert response.name == "name_value" + assert response.enabled is True + assert response.archived is True + + +def test_get_findings_refinement_deployment_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = findings_refinement.GetFindingsRefinementDeploymentRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_findings_refinement_deployment), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_findings_refinement_deployment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.GetFindingsRefinementDeploymentRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_findings_refinement_deployment_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_findings_refinement_deployment + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_findings_refinement_deployment + ] = mock_rpc + request = {} + client.get_findings_refinement_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_findings_refinement_deployment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_findings_refinement_deployment_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_findings_refinement_deployment + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_findings_refinement_deployment + ] = mock_rpc + + request = {} + await client.get_findings_refinement_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_findings_refinement_deployment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.GetFindingsRefinementDeploymentRequest(), + {}, + ], +) +async def test_get_findings_refinement_deployment_async( + request_type, transport: str = "grpc_asyncio" +): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_findings_refinement_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.FindingsRefinementDeployment( + name="name_value", + enabled=True, + archived=True, + ) + ) + response = await client.get_findings_refinement_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = findings_refinement.GetFindingsRefinementDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, findings_refinement.FindingsRefinementDeployment) + assert response.name == "name_value" + assert response.enabled is True + assert response.archived is True + + +def test_get_findings_refinement_deployment_field_headers(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = findings_refinement.GetFindingsRefinementDeploymentRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_findings_refinement_deployment), "__call__" + ) as call: + call.return_value = findings_refinement.FindingsRefinementDeployment() + client.get_findings_refinement_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_findings_refinement_deployment_field_headers_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = findings_refinement.GetFindingsRefinementDeploymentRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_findings_refinement_deployment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.FindingsRefinementDeployment() + ) + await client.get_findings_refinement_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_findings_refinement_deployment_flattened(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_findings_refinement_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = findings_refinement.FindingsRefinementDeployment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_findings_refinement_deployment( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_findings_refinement_deployment_flattened_error(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_findings_refinement_deployment( + findings_refinement.GetFindingsRefinementDeploymentRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_findings_refinement_deployment_flattened_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_findings_refinement_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = findings_refinement.FindingsRefinementDeployment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.FindingsRefinementDeployment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_findings_refinement_deployment( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_findings_refinement_deployment_flattened_error_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_findings_refinement_deployment( + findings_refinement.GetFindingsRefinementDeploymentRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.UpdateFindingsRefinementDeploymentRequest(), + {}, + ], +) +def test_update_findings_refinement_deployment(request_type, transport: str = "grpc"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_findings_refinement_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = findings_refinement.FindingsRefinementDeployment( + name="name_value", + enabled=True, + archived=True, + ) + response = client.update_findings_refinement_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = findings_refinement.UpdateFindingsRefinementDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, findings_refinement.FindingsRefinementDeployment) + assert response.name == "name_value" + assert response.enabled is True + assert response.archived is True + + +def test_update_findings_refinement_deployment_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = findings_refinement.UpdateFindingsRefinementDeploymentRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_findings_refinement_deployment), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_findings_refinement_deployment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.UpdateFindingsRefinementDeploymentRequest() + assert args[0] == request_msg + + +def test_update_findings_refinement_deployment_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_findings_refinement_deployment + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_findings_refinement_deployment + ] = mock_rpc + request = {} + client.update_findings_refinement_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_findings_refinement_deployment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_findings_refinement_deployment_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_findings_refinement_deployment + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_findings_refinement_deployment + ] = mock_rpc + + request = {} + await client.update_findings_refinement_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_findings_refinement_deployment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.UpdateFindingsRefinementDeploymentRequest(), + {}, + ], +) +async def test_update_findings_refinement_deployment_async( + request_type, transport: str = "grpc_asyncio" +): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_findings_refinement_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.FindingsRefinementDeployment( + name="name_value", + enabled=True, + archived=True, + ) + ) + response = await client.update_findings_refinement_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = findings_refinement.UpdateFindingsRefinementDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, findings_refinement.FindingsRefinementDeployment) + assert response.name == "name_value" + assert response.enabled is True + assert response.archived is True + + +def test_update_findings_refinement_deployment_field_headers(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = findings_refinement.UpdateFindingsRefinementDeploymentRequest() + + request.findings_refinement_deployment.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_findings_refinement_deployment), "__call__" + ) as call: + call.return_value = findings_refinement.FindingsRefinementDeployment() + client.update_findings_refinement_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "findings_refinement_deployment.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_findings_refinement_deployment_field_headers_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = findings_refinement.UpdateFindingsRefinementDeploymentRequest() + + request.findings_refinement_deployment.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_findings_refinement_deployment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.FindingsRefinementDeployment() + ) + await client.update_findings_refinement_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "findings_refinement_deployment.name=name_value", + ) in kw["metadata"] + + +def test_update_findings_refinement_deployment_flattened(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_findings_refinement_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = findings_refinement.FindingsRefinementDeployment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_findings_refinement_deployment( + findings_refinement_deployment=findings_refinement.FindingsRefinementDeployment( + detection_exclusion_application=findings_refinement.DetectionExclusionApplication( + curated_rule_sets=["curated_rule_sets_value"] + ) + ), + update_mask=field_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].findings_refinement_deployment + mock_val = findings_refinement.FindingsRefinementDeployment( + detection_exclusion_application=findings_refinement.DetectionExclusionApplication( + curated_rule_sets=["curated_rule_sets_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_findings_refinement_deployment_flattened_error(): + client = FindingsRefinementServiceClient( + credentials=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_findings_refinement_deployment( + findings_refinement.UpdateFindingsRefinementDeploymentRequest(), + findings_refinement_deployment=findings_refinement.FindingsRefinementDeployment( + detection_exclusion_application=findings_refinement.DetectionExclusionApplication( + curated_rule_sets=["curated_rule_sets_value"] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_findings_refinement_deployment_flattened_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_findings_refinement_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = findings_refinement.FindingsRefinementDeployment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.FindingsRefinementDeployment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_findings_refinement_deployment( + findings_refinement_deployment=findings_refinement.FindingsRefinementDeployment( + detection_exclusion_application=findings_refinement.DetectionExclusionApplication( + curated_rule_sets=["curated_rule_sets_value"] + ) + ), + update_mask=field_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].findings_refinement_deployment + mock_val = findings_refinement.FindingsRefinementDeployment( + detection_exclusion_application=findings_refinement.DetectionExclusionApplication( + curated_rule_sets=["curated_rule_sets_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_findings_refinement_deployment_flattened_error_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_findings_refinement_deployment( + findings_refinement.UpdateFindingsRefinementDeploymentRequest(), + findings_refinement_deployment=findings_refinement.FindingsRefinementDeployment( + detection_exclusion_application=findings_refinement.DetectionExclusionApplication( + curated_rule_sets=["curated_rule_sets_value"] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.ListAllFindingsRefinementDeploymentsRequest(), + {}, + ], +) +def test_list_all_findings_refinement_deployments( + request_type, transport: str = "grpc" +): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_all_findings_refinement_deployments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + next_page_token="next_page_token_value", + ) + ) + response = client.list_all_findings_refinement_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = findings_refinement.ListAllFindingsRefinementDeploymentsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAllFindingsRefinementDeploymentsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_all_findings_refinement_deployments_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = findings_refinement.ListAllFindingsRefinementDeploymentsRequest( + instance="instance_value", + page_token="page_token_value", + filter="filter_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_all_findings_refinement_deployments), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_all_findings_refinement_deployments(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.ListAllFindingsRefinementDeploymentsRequest( + instance="instance_value", + page_token="page_token_value", + filter="filter_value", + ) + assert args[0] == request_msg + + +def test_list_all_findings_refinement_deployments_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_all_findings_refinement_deployments + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_all_findings_refinement_deployments + ] = mock_rpc + request = {} + client.list_all_findings_refinement_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_all_findings_refinement_deployments(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_all_findings_refinement_deployments_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_all_findings_refinement_deployments + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_all_findings_refinement_deployments + ] = mock_rpc + + request = {} + await client.list_all_findings_refinement_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_all_findings_refinement_deployments(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.ListAllFindingsRefinementDeploymentsRequest(), + {}, + ], +) +async def test_list_all_findings_refinement_deployments_async( + request_type, transport: str = "grpc_asyncio" +): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_all_findings_refinement_deployments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_all_findings_refinement_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = findings_refinement.ListAllFindingsRefinementDeploymentsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAllFindingsRefinementDeploymentsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_all_findings_refinement_deployments_field_headers(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = findings_refinement.ListAllFindingsRefinementDeploymentsRequest() + + request.instance = "instance_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_all_findings_refinement_deployments), "__call__" + ) as call: + call.return_value = ( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse() + ) + client.list_all_findings_refinement_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "instance=instance_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_all_findings_refinement_deployments_field_headers_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = findings_refinement.ListAllFindingsRefinementDeploymentsRequest() + + request.instance = "instance_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_all_findings_refinement_deployments), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse() + ) + await client.list_all_findings_refinement_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "instance=instance_value", + ) in kw["metadata"] + + +def test_list_all_findings_refinement_deployments_flattened(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_all_findings_refinement_deployments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_all_findings_refinement_deployments( + instance="instance_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].instance + mock_val = "instance_value" + assert arg == mock_val + + +def test_list_all_findings_refinement_deployments_flattened_error(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_all_findings_refinement_deployments( + findings_refinement.ListAllFindingsRefinementDeploymentsRequest(), + instance="instance_value", + ) + + +@pytest.mark.asyncio +async def test_list_all_findings_refinement_deployments_flattened_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_all_findings_refinement_deployments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_all_findings_refinement_deployments( + instance="instance_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].instance + mock_val = "instance_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_all_findings_refinement_deployments_flattened_error_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_all_findings_refinement_deployments( + findings_refinement.ListAllFindingsRefinementDeploymentsRequest(), + instance="instance_value", + ) + + +def test_list_all_findings_refinement_deployments_pager(transport_name: str = "grpc"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_all_findings_refinement_deployments), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + all_findings_refinement_deployments=[ + findings_refinement.FindingsRefinementDeployment(), + findings_refinement.FindingsRefinementDeployment(), + findings_refinement.FindingsRefinementDeployment(), + ], + next_page_token="abc", + ), + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + all_findings_refinement_deployments=[], + next_page_token="def", + ), + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + all_findings_refinement_deployments=[ + findings_refinement.FindingsRefinementDeployment(), + ], + next_page_token="ghi", + ), + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + all_findings_refinement_deployments=[ + findings_refinement.FindingsRefinementDeployment(), + findings_refinement.FindingsRefinementDeployment(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("instance", ""),)), + ) + pager = client.list_all_findings_refinement_deployments( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, findings_refinement.FindingsRefinementDeployment) + for i in results + ) + + +def test_list_all_findings_refinement_deployments_pages(transport_name: str = "grpc"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_all_findings_refinement_deployments), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + all_findings_refinement_deployments=[ + findings_refinement.FindingsRefinementDeployment(), + findings_refinement.FindingsRefinementDeployment(), + findings_refinement.FindingsRefinementDeployment(), + ], + next_page_token="abc", + ), + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + all_findings_refinement_deployments=[], + next_page_token="def", + ), + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + all_findings_refinement_deployments=[ + findings_refinement.FindingsRefinementDeployment(), + ], + next_page_token="ghi", + ), + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + all_findings_refinement_deployments=[ + findings_refinement.FindingsRefinementDeployment(), + findings_refinement.FindingsRefinementDeployment(), + ], + ), + RuntimeError, + ) + pages = list(client.list_all_findings_refinement_deployments(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_all_findings_refinement_deployments_async_pager(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_all_findings_refinement_deployments), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + all_findings_refinement_deployments=[ + findings_refinement.FindingsRefinementDeployment(), + findings_refinement.FindingsRefinementDeployment(), + findings_refinement.FindingsRefinementDeployment(), + ], + next_page_token="abc", + ), + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + all_findings_refinement_deployments=[], + next_page_token="def", + ), + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + all_findings_refinement_deployments=[ + findings_refinement.FindingsRefinementDeployment(), + ], + next_page_token="ghi", + ), + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + all_findings_refinement_deployments=[ + findings_refinement.FindingsRefinementDeployment(), + findings_refinement.FindingsRefinementDeployment(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_all_findings_refinement_deployments( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, findings_refinement.FindingsRefinementDeployment) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_all_findings_refinement_deployments_async_pages(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_all_findings_refinement_deployments), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + all_findings_refinement_deployments=[ + findings_refinement.FindingsRefinementDeployment(), + findings_refinement.FindingsRefinementDeployment(), + findings_refinement.FindingsRefinementDeployment(), + ], + next_page_token="abc", + ), + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + all_findings_refinement_deployments=[], + next_page_token="def", + ), + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + all_findings_refinement_deployments=[ + findings_refinement.FindingsRefinementDeployment(), + ], + next_page_token="ghi", + ), + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + all_findings_refinement_deployments=[ + findings_refinement.FindingsRefinementDeployment(), + findings_refinement.FindingsRefinementDeployment(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_all_findings_refinement_deployments(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.ComputeFindingsRefinementActivityRequest(), + {}, + ], +) +def test_compute_findings_refinement_activity(request_type, transport: str = "grpc"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_findings_refinement_activity), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + findings_refinement.ComputeFindingsRefinementActivityResponse() + ) + response = client.compute_findings_refinement_activity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = findings_refinement.ComputeFindingsRefinementActivityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, findings_refinement.ComputeFindingsRefinementActivityResponse + ) + + +def test_compute_findings_refinement_activity_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = findings_refinement.ComputeFindingsRefinementActivityRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_findings_refinement_activity), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.compute_findings_refinement_activity(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.ComputeFindingsRefinementActivityRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_compute_findings_refinement_activity_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.compute_findings_refinement_activity + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.compute_findings_refinement_activity + ] = mock_rpc + request = {} + client.compute_findings_refinement_activity(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.compute_findings_refinement_activity(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_compute_findings_refinement_activity_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.compute_findings_refinement_activity + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.compute_findings_refinement_activity + ] = mock_rpc + + request = {} + await client.compute_findings_refinement_activity(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.compute_findings_refinement_activity(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.ComputeFindingsRefinementActivityRequest(), + {}, + ], +) +async def test_compute_findings_refinement_activity_async( + request_type, transport: str = "grpc_asyncio" +): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_findings_refinement_activity), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.ComputeFindingsRefinementActivityResponse() + ) + response = await client.compute_findings_refinement_activity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = findings_refinement.ComputeFindingsRefinementActivityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, findings_refinement.ComputeFindingsRefinementActivityResponse + ) + + +def test_compute_findings_refinement_activity_field_headers(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = findings_refinement.ComputeFindingsRefinementActivityRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_findings_refinement_activity), "__call__" + ) as call: + call.return_value = ( + findings_refinement.ComputeFindingsRefinementActivityResponse() + ) + client.compute_findings_refinement_activity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_compute_findings_refinement_activity_field_headers_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = findings_refinement.ComputeFindingsRefinementActivityRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_findings_refinement_activity), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.ComputeFindingsRefinementActivityResponse() + ) + await client.compute_findings_refinement_activity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_compute_findings_refinement_activity_flattened(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_findings_refinement_activity), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + findings_refinement.ComputeFindingsRefinementActivityResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.compute_findings_refinement_activity( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_compute_findings_refinement_activity_flattened_error(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.compute_findings_refinement_activity( + findings_refinement.ComputeFindingsRefinementActivityRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_compute_findings_refinement_activity_flattened_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_findings_refinement_activity), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + findings_refinement.ComputeFindingsRefinementActivityResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.ComputeFindingsRefinementActivityResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.compute_findings_refinement_activity( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_compute_findings_refinement_activity_flattened_error_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.compute_findings_refinement_activity( + findings_refinement.ComputeFindingsRefinementActivityRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.ComputeAllFindingsRefinementActivitiesRequest(), + {}, + ], +) +def test_compute_all_findings_refinement_activities( + request_type, transport: str = "grpc" +): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_all_findings_refinement_activities), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse() + ) + response = client.compute_all_findings_refinement_activities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = findings_refinement.ComputeAllFindingsRefinementActivitiesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, findings_refinement.ComputeAllFindingsRefinementActivitiesResponse + ) + + +def test_compute_all_findings_refinement_activities_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = findings_refinement.ComputeAllFindingsRefinementActivitiesRequest( + instance="instance_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_all_findings_refinement_activities), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.compute_all_findings_refinement_activities(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.ComputeAllFindingsRefinementActivitiesRequest( + instance="instance_value", + ) + assert args[0] == request_msg + + +def test_compute_all_findings_refinement_activities_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.compute_all_findings_refinement_activities + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.compute_all_findings_refinement_activities + ] = mock_rpc + request = {} + client.compute_all_findings_refinement_activities(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.compute_all_findings_refinement_activities(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_compute_all_findings_refinement_activities_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.compute_all_findings_refinement_activities + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.compute_all_findings_refinement_activities + ] = mock_rpc + + request = {} + await client.compute_all_findings_refinement_activities(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.compute_all_findings_refinement_activities(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.ComputeAllFindingsRefinementActivitiesRequest(), + {}, + ], +) +async def test_compute_all_findings_refinement_activities_async( + request_type, transport: str = "grpc_asyncio" +): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_all_findings_refinement_activities), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse() + ) + response = await client.compute_all_findings_refinement_activities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = findings_refinement.ComputeAllFindingsRefinementActivitiesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, findings_refinement.ComputeAllFindingsRefinementActivitiesResponse + ) + + +def test_compute_all_findings_refinement_activities_field_headers(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = findings_refinement.ComputeAllFindingsRefinementActivitiesRequest() + + request.instance = "instance_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_all_findings_refinement_activities), "__call__" + ) as call: + call.return_value = ( + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse() + ) + client.compute_all_findings_refinement_activities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "instance=instance_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_compute_all_findings_refinement_activities_field_headers_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = findings_refinement.ComputeAllFindingsRefinementActivitiesRequest() + + request.instance = "instance_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_all_findings_refinement_activities), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse() + ) + await client.compute_all_findings_refinement_activities(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "instance=instance_value", + ) in kw["metadata"] + + +def test_compute_all_findings_refinement_activities_flattened(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_all_findings_refinement_activities), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.compute_all_findings_refinement_activities( + instance="instance_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].instance + mock_val = "instance_value" + assert arg == mock_val + + +def test_compute_all_findings_refinement_activities_flattened_error(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.compute_all_findings_refinement_activities( + findings_refinement.ComputeAllFindingsRefinementActivitiesRequest(), + instance="instance_value", + ) + + +@pytest.mark.asyncio +async def test_compute_all_findings_refinement_activities_flattened_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.compute_all_findings_refinement_activities), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.compute_all_findings_refinement_activities( + instance="instance_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].instance + mock_val = "instance_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_compute_all_findings_refinement_activities_flattened_error_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.compute_all_findings_refinement_activities( + findings_refinement.ComputeAllFindingsRefinementActivitiesRequest(), + instance="instance_value", + ) + + +def test_get_findings_refinement_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_findings_refinement + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_findings_refinement + ] = mock_rpc + + request = {} + client.get_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_findings_refinement(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_findings_refinement_rest_required_fields( + request_type=findings_refinement.GetFindingsRefinementRequest, +): + transport_class = transports.FindingsRefinementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_findings_refinement._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_findings_refinement._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = findings_refinement.FindingsRefinement() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = findings_refinement.FindingsRefinement.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_findings_refinement(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_findings_refinement_rest_unset_required_fields(): + transport = transports.FindingsRefinementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_findings_refinement._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_findings_refinement_rest_flattened(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = findings_refinement.FindingsRefinement() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3/findingsRefinements/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = findings_refinement.FindingsRefinement.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_findings_refinement(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/instances/*/findingsRefinements/*}" + % client.transport._host, + args[1], + ) + + +def test_get_findings_refinement_rest_flattened_error(transport: str = "rest"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_findings_refinement( + findings_refinement.GetFindingsRefinementRequest(), + name="name_value", + ) + + +def test_list_findings_refinements_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap 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_refinements + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.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_refinements + ] = mock_rpc + + request = {} + client.list_findings_refinements(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_findings_refinements(request) + + # Establish that 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_refinements_rest_required_fields( + request_type=findings_refinement.ListFindingsRefinementsRequest, +): + transport_class = transports.FindingsRefinementServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.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_refinements._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_refinements._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 = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = findings_refinement.ListFindingsRefinementsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = findings_refinement.ListFindingsRefinementsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_findings_refinements(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_findings_refinements_rest_unset_required_fields(): + transport = transports.FindingsRefinementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_findings_refinements._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_findings_refinements_rest_flattened(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = findings_refinement.ListFindingsRefinementsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = findings_refinement.ListFindingsRefinementsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_findings_refinements(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/instances/*}/findingsRefinements" + % client.transport._host, + args[1], + ) + + +def test_list_findings_refinements_rest_flattened_error(transport: str = "rest"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.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_refinements( + findings_refinement.ListFindingsRefinementsRequest(), + parent="parent_value", + ) + + +def test_list_findings_refinements_rest_pager(transport: str = "rest"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + findings_refinement.ListFindingsRefinementsResponse( + findings_refinements=[ + findings_refinement.FindingsRefinement(), + findings_refinement.FindingsRefinement(), + findings_refinement.FindingsRefinement(), + ], + next_page_token="abc", + ), + findings_refinement.ListFindingsRefinementsResponse( + findings_refinements=[], + next_page_token="def", + ), + findings_refinement.ListFindingsRefinementsResponse( + findings_refinements=[ + findings_refinement.FindingsRefinement(), + ], + next_page_token="ghi", + ), + findings_refinement.ListFindingsRefinementsResponse( + findings_refinements=[ + findings_refinement.FindingsRefinement(), + findings_refinement.FindingsRefinement(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + findings_refinement.ListFindingsRefinementsResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/instances/sample3" + } + + pager = client.list_findings_refinements(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, findings_refinement.FindingsRefinement) for i in results + ) + + pages = list(client.list_findings_refinements(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_findings_refinement_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_findings_refinement + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_findings_refinement + ] = mock_rpc + + request = {} + client.create_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_findings_refinement(request) + + # Establish 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_findings_refinement_rest_required_fields( + request_type=gcc_findings_refinement.CreateFindingsRefinementRequest, +): + transport_class = transports.FindingsRefinementServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_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_findings_refinement._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_findings_refinement._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 = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcc_findings_refinement.FindingsRefinement() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_findings_refinement.FindingsRefinement.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_findings_refinement(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_findings_refinement_rest_unset_required_fields(): + transport = transports.FindingsRefinementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_findings_refinement._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "findingsRefinement", + ) + ) + ) + + +def test_create_findings_refinement_rest_flattened(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_findings_refinement.FindingsRefinement() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + findings_refinement=gcc_findings_refinement.FindingsRefinement( + name="name_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcc_findings_refinement.FindingsRefinement.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_findings_refinement(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/instances/*}/findingsRefinements" + % client.transport._host, + args[1], + ) + + +def test_create_findings_refinement_rest_flattened_error(transport: str = "rest"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.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_findings_refinement( + gcc_findings_refinement.CreateFindingsRefinementRequest(), + parent="parent_value", + findings_refinement=gcc_findings_refinement.FindingsRefinement( + name="name_value" + ), + ) + + +def test_update_findings_refinement_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_findings_refinement + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_findings_refinement + ] = mock_rpc + + request = {} + client.update_findings_refinement(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_findings_refinement(request) + + # Establish 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_findings_refinement_rest_required_fields( + request_type=gcc_findings_refinement.UpdateFindingsRefinementRequest, +): + transport_class = transports.FindingsRefinementServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_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_findings_refinement._get_unset_required_fields(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_findings_refinement._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 = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcc_findings_refinement.FindingsRefinement() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = gcc_findings_refinement.FindingsRefinement.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_findings_refinement(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_findings_refinement_rest_unset_required_fields(): + transport = transports.FindingsRefinementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_findings_refinement._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("findingsRefinement",))) + + +def test_update_findings_refinement_rest_flattened(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_findings_refinement.FindingsRefinement() + + # get arguments that satisfy an http rule for this method + sample_request = { + "findings_refinement": { + "name": "projects/sample1/locations/sample2/instances/sample3/findingsRefinements/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + findings_refinement=gcc_findings_refinement.FindingsRefinement( + 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 = gcc_findings_refinement.FindingsRefinement.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_findings_refinement(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{findings_refinement.name=projects/*/locations/*/instances/*/findingsRefinements/*}" + % client.transport._host, + args[1], + ) + + +def test_update_findings_refinement_rest_flattened_error(transport: str = "rest"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.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_findings_refinement( + gcc_findings_refinement.UpdateFindingsRefinementRequest(), + findings_refinement=gcc_findings_refinement.FindingsRefinement( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_get_findings_refinement_deployment_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_findings_refinement_deployment + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_findings_refinement_deployment + ] = mock_rpc + + request = {} + client.get_findings_refinement_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_findings_refinement_deployment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_findings_refinement_deployment_rest_required_fields( + request_type=findings_refinement.GetFindingsRefinementDeploymentRequest, +): + transport_class = transports.FindingsRefinementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_findings_refinement_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_findings_refinement_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = findings_refinement.FindingsRefinementDeployment() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = findings_refinement.FindingsRefinementDeployment.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_findings_refinement_deployment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_findings_refinement_deployment_rest_unset_required_fields(): + transport = transports.FindingsRefinementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.get_findings_refinement_deployment._get_unset_required_fields({}) + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_findings_refinement_deployment_rest_flattened(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = findings_refinement.FindingsRefinementDeployment() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3/findingsRefinements/sample4/deployment" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = findings_refinement.FindingsRefinementDeployment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_findings_refinement_deployment(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/instances/*/findingsRefinements/*/deployment}" + % client.transport._host, + args[1], + ) + + +def test_get_findings_refinement_deployment_rest_flattened_error( + transport: str = "rest", +): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_findings_refinement_deployment( + findings_refinement.GetFindingsRefinementDeploymentRequest(), + name="name_value", + ) + + +def test_update_findings_refinement_deployment_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_findings_refinement_deployment + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_findings_refinement_deployment + ] = mock_rpc + + request = {} + client.update_findings_refinement_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_findings_refinement_deployment(request) + + # Establish 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_findings_refinement_deployment_rest_required_fields( + request_type=findings_refinement.UpdateFindingsRefinementDeploymentRequest, +): + transport_class = transports.FindingsRefinementServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_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_findings_refinement_deployment._get_unset_required_fields( + 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_findings_refinement_deployment._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 = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = findings_refinement.FindingsRefinementDeployment() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 = findings_refinement.FindingsRefinementDeployment.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_findings_refinement_deployment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_findings_refinement_deployment_rest_unset_required_fields(): + transport = transports.FindingsRefinementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.update_findings_refinement_deployment._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "findingsRefinementDeployment", + "updateMask", + ) + ) + ) + + +def test_update_findings_refinement_deployment_rest_flattened(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = findings_refinement.FindingsRefinementDeployment() + + # get arguments that satisfy an http rule for this method + sample_request = { + "findings_refinement_deployment": { + "name": "projects/sample1/locations/sample2/instances/sample3/findingsRefinements/sample4/deployment" + } + } + + # get truthy value for each flattened field + mock_args = dict( + findings_refinement_deployment=findings_refinement.FindingsRefinementDeployment( + detection_exclusion_application=findings_refinement.DetectionExclusionApplication( + curated_rule_sets=["curated_rule_sets_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 = findings_refinement.FindingsRefinementDeployment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_findings_refinement_deployment(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{findings_refinement_deployment.name=projects/*/locations/*/instances/*/findingsRefinements/*/deployment}" + % client.transport._host, + args[1], + ) + + +def test_update_findings_refinement_deployment_rest_flattened_error( + transport: str = "rest", +): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.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_findings_refinement_deployment( + findings_refinement.UpdateFindingsRefinementDeploymentRequest(), + findings_refinement_deployment=findings_refinement.FindingsRefinementDeployment( + detection_exclusion_application=findings_refinement.DetectionExclusionApplication( + curated_rule_sets=["curated_rule_sets_value"] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_list_all_findings_refinement_deployments_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_all_findings_refinement_deployments + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_all_findings_refinement_deployments + ] = mock_rpc + + request = {} + client.list_all_findings_refinement_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_all_findings_refinement_deployments(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_all_findings_refinement_deployments_rest_required_fields( + request_type=findings_refinement.ListAllFindingsRefinementDeploymentsRequest, +): + transport_class = transports.FindingsRefinementServiceRestTransport + + request_init = {} + request_init["instance"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_all_findings_refinement_deployments._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["instance"] = "instance_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_all_findings_refinement_deployments._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 "instance" in jsonified_request + assert jsonified_request["instance"] == "instance_value" + + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = findings_refinement.ListAllFindingsRefinementDeploymentsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_all_findings_refinement_deployments(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_all_findings_refinement_deployments_rest_unset_required_fields(): + transport = transports.FindingsRefinementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.list_all_findings_refinement_deployments._get_unset_required_fields( + {} + ) + ) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("instance",)) + ) + + +def test_list_all_findings_refinement_deployments_rest_flattened(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = ( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse() + ) + + # get arguments that satisfy an http rule for this method + sample_request = { + "instance": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + instance="instance_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = ( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_all_findings_refinement_deployments(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{instance=projects/*/locations/*/instances/*}:listAllFindingsRefinementDeployments" + % client.transport._host, + args[1], + ) + + +def test_list_all_findings_refinement_deployments_rest_flattened_error( + transport: str = "rest", +): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.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_all_findings_refinement_deployments( + findings_refinement.ListAllFindingsRefinementDeploymentsRequest(), + instance="instance_value", + ) + + +def test_list_all_findings_refinement_deployments_rest_pager(transport: str = "rest"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + all_findings_refinement_deployments=[ + findings_refinement.FindingsRefinementDeployment(), + findings_refinement.FindingsRefinementDeployment(), + findings_refinement.FindingsRefinementDeployment(), + ], + next_page_token="abc", + ), + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + all_findings_refinement_deployments=[], + next_page_token="def", + ), + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + all_findings_refinement_deployments=[ + findings_refinement.FindingsRefinementDeployment(), + ], + next_page_token="ghi", + ), + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + all_findings_refinement_deployments=[ + findings_refinement.FindingsRefinementDeployment(), + findings_refinement.FindingsRefinementDeployment(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "instance": "projects/sample1/locations/sample2/instances/sample3" + } + + pager = client.list_all_findings_refinement_deployments(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, findings_refinement.FindingsRefinementDeployment) + for i in results + ) + + pages = list( + client.list_all_findings_refinement_deployments( + request=sample_request + ).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_compute_findings_refinement_activity_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.compute_findings_refinement_activity + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.compute_findings_refinement_activity + ] = mock_rpc + + request = {} + client.compute_findings_refinement_activity(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.compute_findings_refinement_activity(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_compute_findings_refinement_activity_rest_required_fields( + request_type=findings_refinement.ComputeFindingsRefinementActivityRequest, +): + transport_class = transports.FindingsRefinementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).compute_findings_refinement_activity._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).compute_findings_refinement_activity._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = findings_refinement.ComputeFindingsRefinementActivityResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + findings_refinement.ComputeFindingsRefinementActivityResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.compute_findings_refinement_activity(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_compute_findings_refinement_activity_rest_unset_required_fields(): + transport = transports.FindingsRefinementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.compute_findings_refinement_activity._get_unset_required_fields({}) + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_compute_findings_refinement_activity_rest_flattened(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = findings_refinement.ComputeFindingsRefinementActivityResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3/findingsRefinements/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = findings_refinement.ComputeFindingsRefinementActivityResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.compute_findings_refinement_activity(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/instances/*/findingsRefinements/*}:computeFindingsRefinementActivity" + % client.transport._host, + args[1], + ) + + +def test_compute_findings_refinement_activity_rest_flattened_error( + transport: str = "rest", +): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.compute_findings_refinement_activity( + findings_refinement.ComputeFindingsRefinementActivityRequest(), + name="name_value", + ) + + +def test_compute_all_findings_refinement_activities_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.compute_all_findings_refinement_activities + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.compute_all_findings_refinement_activities + ] = mock_rpc + + request = {} + client.compute_all_findings_refinement_activities(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.compute_all_findings_refinement_activities(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_compute_all_findings_refinement_activities_rest_required_fields( + request_type=findings_refinement.ComputeAllFindingsRefinementActivitiesRequest, +): + transport_class = transports.FindingsRefinementServiceRestTransport + + request_init = {} + request_init["instance"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).compute_all_findings_refinement_activities._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["instance"] = "instance_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).compute_all_findings_refinement_activities._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "instance" in jsonified_request + assert jsonified_request["instance"] == "instance_value" + + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = findings_refinement.ComputeAllFindingsRefinementActivitiesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.compute_all_findings_refinement_activities(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_compute_all_findings_refinement_activities_rest_unset_required_fields(): + transport = transports.FindingsRefinementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.compute_all_findings_refinement_activities._get_unset_required_fields( + {} + ) + ) + assert set(unset_fields) == (set(()) & set(("instance",))) + + +def test_compute_all_findings_refinement_activities_rest_flattened(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = ( + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse() + ) + + # get arguments that satisfy an http rule for this method + sample_request = { + "instance": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + instance="instance_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = ( + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.compute_all_findings_refinement_activities(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{instance=projects/*/locations/*/instances/*}:computeAllFindingsRefinementActivities" + % client.transport._host, + args[1], + ) + + +def test_compute_all_findings_refinement_activities_rest_flattened_error( + transport: str = "rest", +): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.compute_all_findings_refinement_activities( + findings_refinement.ComputeAllFindingsRefinementActivitiesRequest(), + instance="instance_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.FindingsRefinementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.FindingsRefinementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FindingsRefinementServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.FindingsRefinementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = FindingsRefinementServiceClient( + 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 = FindingsRefinementServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.FindingsRefinementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FindingsRefinementServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.FindingsRefinementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = FindingsRefinementServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.FindingsRefinementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.FindingsRefinementServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FindingsRefinementServiceGrpcTransport, + transports.FindingsRefinementServiceGrpcAsyncIOTransport, + transports.FindingsRefinementServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = FindingsRefinementServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_findings_refinement_empty_call_grpc(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_findings_refinement), "__call__" + ) as call: + call.return_value = findings_refinement.FindingsRefinement() + client.get_findings_refinement(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.GetFindingsRefinementRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_findings_refinements_empty_call_grpc(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_findings_refinements), "__call__" + ) as call: + call.return_value = findings_refinement.ListFindingsRefinementsResponse() + client.list_findings_refinements(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.ListFindingsRefinementsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_findings_refinement_empty_call_grpc(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_findings_refinement), "__call__" + ) as call: + call.return_value = gcc_findings_refinement.FindingsRefinement() + client.create_findings_refinement(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcc_findings_refinement.CreateFindingsRefinementRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_findings_refinement_empty_call_grpc(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_findings_refinement), "__call__" + ) as call: + call.return_value = gcc_findings_refinement.FindingsRefinement() + client.update_findings_refinement(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcc_findings_refinement.UpdateFindingsRefinementRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_findings_refinement_deployment_empty_call_grpc(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_findings_refinement_deployment), "__call__" + ) as call: + call.return_value = findings_refinement.FindingsRefinementDeployment() + client.get_findings_refinement_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.GetFindingsRefinementDeploymentRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_findings_refinement_deployment_empty_call_grpc(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_findings_refinement_deployment), "__call__" + ) as call: + call.return_value = findings_refinement.FindingsRefinementDeployment() + client.update_findings_refinement_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.UpdateFindingsRefinementDeploymentRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_all_findings_refinement_deployments_empty_call_grpc(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_all_findings_refinement_deployments), "__call__" + ) as call: + call.return_value = ( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse() + ) + client.list_all_findings_refinement_deployments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.ListAllFindingsRefinementDeploymentsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_compute_findings_refinement_activity_empty_call_grpc(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.compute_findings_refinement_activity), "__call__" + ) as call: + call.return_value = ( + findings_refinement.ComputeFindingsRefinementActivityResponse() + ) + client.compute_findings_refinement_activity(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.ComputeFindingsRefinementActivityRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_compute_all_findings_refinement_activities_empty_call_grpc(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.compute_all_findings_refinement_activities), "__call__" + ) as call: + call.return_value = ( + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse() + ) + client.compute_all_findings_refinement_activities(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + findings_refinement.ComputeAllFindingsRefinementActivitiesRequest() + ) + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = FindingsRefinementServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_findings_refinement_empty_call_grpc_asyncio(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_findings_refinement), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.FindingsRefinement( + name="name_value", + display_name="display_name_value", + type_=findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION, + query="query_value", + ) + ) + await client.get_findings_refinement(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.GetFindingsRefinementRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_findings_refinements_empty_call_grpc_asyncio(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_findings_refinements), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.ListFindingsRefinementsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_findings_refinements(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.ListFindingsRefinementsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_findings_refinement_empty_call_grpc_asyncio(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_findings_refinement), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_findings_refinement.FindingsRefinement( + name="name_value", + display_name="display_name_value", + type_=gcc_findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION, + query="query_value", + ) + ) + await client.create_findings_refinement(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcc_findings_refinement.CreateFindingsRefinementRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_findings_refinement_empty_call_grpc_asyncio(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_findings_refinement), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_findings_refinement.FindingsRefinement( + name="name_value", + display_name="display_name_value", + type_=gcc_findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION, + query="query_value", + ) + ) + await client.update_findings_refinement(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcc_findings_refinement.UpdateFindingsRefinementRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_findings_refinement_deployment_empty_call_grpc_asyncio(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_findings_refinement_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.FindingsRefinementDeployment( + name="name_value", + enabled=True, + archived=True, + ) + ) + await client.get_findings_refinement_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.GetFindingsRefinementDeploymentRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_findings_refinement_deployment_empty_call_grpc_asyncio(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_findings_refinement_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.FindingsRefinementDeployment( + name="name_value", + enabled=True, + archived=True, + ) + ) + await client.update_findings_refinement_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.UpdateFindingsRefinementDeploymentRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_all_findings_refinement_deployments_empty_call_grpc_asyncio(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_all_findings_refinement_deployments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_all_findings_refinement_deployments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.ListAllFindingsRefinementDeploymentsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_compute_findings_refinement_activity_empty_call_grpc_asyncio(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.compute_findings_refinement_activity), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.ComputeFindingsRefinementActivityResponse() + ) + await client.compute_findings_refinement_activity(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.ComputeFindingsRefinementActivityRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_compute_all_findings_refinement_activities_empty_call_grpc_asyncio(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.compute_all_findings_refinement_activities), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse() + ) + await client.compute_all_findings_refinement_activities(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + findings_refinement.ComputeAllFindingsRefinementActivitiesRequest() + ) + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = FindingsRefinementServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_findings_refinement_rest_bad_request( + request_type=findings_refinement.GetFindingsRefinementRequest, +): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/findingsRefinements/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_findings_refinement(request) + + +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.GetFindingsRefinementRequest, + dict, + ], +) +def test_get_findings_refinement_rest_call_success(request_type): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/findingsRefinements/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = findings_refinement.FindingsRefinement( + name="name_value", + display_name="display_name_value", + type_=findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION, + query="query_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = findings_refinement.FindingsRefinement.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_findings_refinement(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, findings_refinement.FindingsRefinement) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert ( + response.type_ == findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION + ) + assert response.query == "query_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_findings_refinement_rest_interceptors(null_interceptor): + transport = transports.FindingsRefinementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.FindingsRefinementServiceRestInterceptor(), + ) + client = FindingsRefinementServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "post_get_findings_refinement", + ) as post, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "post_get_findings_refinement_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "pre_get_findings_refinement", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = findings_refinement.GetFindingsRefinementRequest.pb( + findings_refinement.GetFindingsRefinementRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = findings_refinement.FindingsRefinement.to_json( + findings_refinement.FindingsRefinement() + ) + req.return_value.content = return_value + + request = findings_refinement.GetFindingsRefinementRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = findings_refinement.FindingsRefinement() + post_with_metadata.return_value = ( + findings_refinement.FindingsRefinement(), + metadata, + ) + + client.get_findings_refinement( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_findings_refinements_rest_bad_request( + request_type=findings_refinement.ListFindingsRefinementsRequest, +): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_findings_refinements(request) + + +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.ListFindingsRefinementsRequest, + dict, + ], +) +def test_list_findings_refinements_rest_call_success(request_type): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/instances/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 = findings_refinement.ListFindingsRefinementsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = findings_refinement.ListFindingsRefinementsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_findings_refinements(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsRefinementsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_findings_refinements_rest_interceptors(null_interceptor): + transport = transports.FindingsRefinementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.FindingsRefinementServiceRestInterceptor(), + ) + client = FindingsRefinementServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "post_list_findings_refinements", + ) as post, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "post_list_findings_refinements_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "pre_list_findings_refinements", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = findings_refinement.ListFindingsRefinementsRequest.pb( + findings_refinement.ListFindingsRefinementsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = findings_refinement.ListFindingsRefinementsResponse.to_json( + findings_refinement.ListFindingsRefinementsResponse() + ) + req.return_value.content = return_value + + request = findings_refinement.ListFindingsRefinementsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = findings_refinement.ListFindingsRefinementsResponse() + post_with_metadata.return_value = ( + findings_refinement.ListFindingsRefinementsResponse(), + metadata, + ) + + client.list_findings_refinements( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_findings_refinement_rest_bad_request( + request_type=gcc_findings_refinement.CreateFindingsRefinementRequest, +): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_findings_refinement(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcc_findings_refinement.CreateFindingsRefinementRequest, + dict, + ], +) +def test_create_findings_refinement_rest_call_success(request_type): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/instances/sample3"} + request_init["findings_refinement"] = { + "name": "name_value", + "display_name": "display_name_value", + "type_": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "query": "query_value", + "outcome_filters": [ + { + "outcome_variable": "outcome_variable_value", + "outcome_value": "outcome_value_value", + "outcome_filter_operator": 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 = gcc_findings_refinement.CreateFindingsRefinementRequest.meta.fields[ + "findings_refinement" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["findings_refinement"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["findings_refinement"][field])): + del request_init["findings_refinement"][field][i][subfield] + else: + del request_init["findings_refinement"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_findings_refinement.FindingsRefinement( + name="name_value", + display_name="display_name_value", + type_=gcc_findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION, + query="query_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_findings_refinement.FindingsRefinement.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_findings_refinement(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_findings_refinement.FindingsRefinement) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert ( + response.type_ + == gcc_findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION + ) + assert response.query == "query_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_findings_refinement_rest_interceptors(null_interceptor): + transport = transports.FindingsRefinementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.FindingsRefinementServiceRestInterceptor(), + ) + client = FindingsRefinementServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "post_create_findings_refinement", + ) as post, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "post_create_findings_refinement_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "pre_create_findings_refinement", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcc_findings_refinement.CreateFindingsRefinementRequest.pb( + gcc_findings_refinement.CreateFindingsRefinementRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcc_findings_refinement.FindingsRefinement.to_json( + gcc_findings_refinement.FindingsRefinement() + ) + req.return_value.content = return_value + + request = gcc_findings_refinement.CreateFindingsRefinementRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcc_findings_refinement.FindingsRefinement() + post_with_metadata.return_value = ( + gcc_findings_refinement.FindingsRefinement(), + metadata, + ) + + client.create_findings_refinement( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_findings_refinement_rest_bad_request( + request_type=gcc_findings_refinement.UpdateFindingsRefinementRequest, +): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "findings_refinement": { + "name": "projects/sample1/locations/sample2/instances/sample3/findingsRefinements/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_findings_refinement(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcc_findings_refinement.UpdateFindingsRefinementRequest, + dict, + ], +) +def test_update_findings_refinement_rest_call_success(request_type): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "findings_refinement": { + "name": "projects/sample1/locations/sample2/instances/sample3/findingsRefinements/sample4" + } + } + request_init["findings_refinement"] = { + "name": "projects/sample1/locations/sample2/instances/sample3/findingsRefinements/sample4", + "display_name": "display_name_value", + "type_": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "query": "query_value", + "outcome_filters": [ + { + "outcome_variable": "outcome_variable_value", + "outcome_value": "outcome_value_value", + "outcome_filter_operator": 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 = gcc_findings_refinement.UpdateFindingsRefinementRequest.meta.fields[ + "findings_refinement" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["findings_refinement"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["findings_refinement"][field])): + del request_init["findings_refinement"][field][i][subfield] + else: + del request_init["findings_refinement"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_findings_refinement.FindingsRefinement( + name="name_value", + display_name="display_name_value", + type_=gcc_findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION, + query="query_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_findings_refinement.FindingsRefinement.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_findings_refinement(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_findings_refinement.FindingsRefinement) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert ( + response.type_ + == gcc_findings_refinement.FindingsRefinementType.DETECTION_EXCLUSION + ) + assert response.query == "query_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_findings_refinement_rest_interceptors(null_interceptor): + transport = transports.FindingsRefinementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.FindingsRefinementServiceRestInterceptor(), + ) + client = FindingsRefinementServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "post_update_findings_refinement", + ) as post, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "post_update_findings_refinement_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "pre_update_findings_refinement", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcc_findings_refinement.UpdateFindingsRefinementRequest.pb( + gcc_findings_refinement.UpdateFindingsRefinementRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcc_findings_refinement.FindingsRefinement.to_json( + gcc_findings_refinement.FindingsRefinement() + ) + req.return_value.content = return_value + + request = gcc_findings_refinement.UpdateFindingsRefinementRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcc_findings_refinement.FindingsRefinement() + post_with_metadata.return_value = ( + gcc_findings_refinement.FindingsRefinement(), + metadata, + ) + + client.update_findings_refinement( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_findings_refinement_deployment_rest_bad_request( + request_type=findings_refinement.GetFindingsRefinementDeploymentRequest, +): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/findingsRefinements/sample4/deployment" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_findings_refinement_deployment(request) + + +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.GetFindingsRefinementDeploymentRequest, + dict, + ], +) +def test_get_findings_refinement_deployment_rest_call_success(request_type): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/findingsRefinements/sample4/deployment" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = findings_refinement.FindingsRefinementDeployment( + name="name_value", + enabled=True, + archived=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = findings_refinement.FindingsRefinementDeployment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_findings_refinement_deployment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, findings_refinement.FindingsRefinementDeployment) + assert response.name == "name_value" + assert response.enabled is True + assert response.archived is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_findings_refinement_deployment_rest_interceptors(null_interceptor): + transport = transports.FindingsRefinementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.FindingsRefinementServiceRestInterceptor(), + ) + client = FindingsRefinementServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "post_get_findings_refinement_deployment", + ) as post, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "post_get_findings_refinement_deployment_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "pre_get_findings_refinement_deployment", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = findings_refinement.GetFindingsRefinementDeploymentRequest.pb( + findings_refinement.GetFindingsRefinementDeploymentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = findings_refinement.FindingsRefinementDeployment.to_json( + findings_refinement.FindingsRefinementDeployment() + ) + req.return_value.content = return_value + + request = findings_refinement.GetFindingsRefinementDeploymentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = findings_refinement.FindingsRefinementDeployment() + post_with_metadata.return_value = ( + findings_refinement.FindingsRefinementDeployment(), + metadata, + ) + + client.get_findings_refinement_deployment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_findings_refinement_deployment_rest_bad_request( + request_type=findings_refinement.UpdateFindingsRefinementDeploymentRequest, +): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "findings_refinement_deployment": { + "name": "projects/sample1/locations/sample2/instances/sample3/findingsRefinements/sample4/deployment" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_findings_refinement_deployment(request) + + +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.UpdateFindingsRefinementDeploymentRequest, + dict, + ], +) +def test_update_findings_refinement_deployment_rest_call_success(request_type): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "findings_refinement_deployment": { + "name": "projects/sample1/locations/sample2/instances/sample3/findingsRefinements/sample4/deployment" + } + } + request_init["findings_refinement_deployment"] = { + "detection_exclusion_application": { + "curated_rule_sets": [ + "curated_rule_sets_value1", + "curated_rule_sets_value2", + ], + "curated_rules": ["curated_rules_value1", "curated_rules_value2"], + "rules": ["rules_value1", "rules_value2"], + "deleted_curated_rule_sets": [ + "deleted_curated_rule_sets_value1", + "deleted_curated_rule_sets_value2", + ], + }, + "name": "projects/sample1/locations/sample2/instances/sample3/findingsRefinements/sample4/deployment", + "enabled": True, + "archived": True, + "update_time": {"seconds": 751, "nanos": 543}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = ( + findings_refinement.UpdateFindingsRefinementDeploymentRequest.meta.fields[ + "findings_refinement_deployment" + ] + ) + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "findings_refinement_deployment" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["findings_refinement_deployment"][field]) + ): + del request_init["findings_refinement_deployment"][field][i][ + subfield + ] + else: + del request_init["findings_refinement_deployment"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = findings_refinement.FindingsRefinementDeployment( + name="name_value", + enabled=True, + archived=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = findings_refinement.FindingsRefinementDeployment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_findings_refinement_deployment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, findings_refinement.FindingsRefinementDeployment) + assert response.name == "name_value" + assert response.enabled is True + assert response.archived is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_findings_refinement_deployment_rest_interceptors(null_interceptor): + transport = transports.FindingsRefinementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.FindingsRefinementServiceRestInterceptor(), + ) + client = FindingsRefinementServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "post_update_findings_refinement_deployment", + ) as post, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "post_update_findings_refinement_deployment_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "pre_update_findings_refinement_deployment", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = findings_refinement.UpdateFindingsRefinementDeploymentRequest.pb( + findings_refinement.UpdateFindingsRefinementDeploymentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = findings_refinement.FindingsRefinementDeployment.to_json( + findings_refinement.FindingsRefinementDeployment() + ) + req.return_value.content = return_value + + request = findings_refinement.UpdateFindingsRefinementDeploymentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = findings_refinement.FindingsRefinementDeployment() + post_with_metadata.return_value = ( + findings_refinement.FindingsRefinementDeployment(), + metadata, + ) + + client.update_findings_refinement_deployment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_all_findings_refinement_deployments_rest_bad_request( + request_type=findings_refinement.ListAllFindingsRefinementDeploymentsRequest, +): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"instance": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_all_findings_refinement_deployments(request) + + +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.ListAllFindingsRefinementDeploymentsRequest, + dict, + ], +) +def test_list_all_findings_refinement_deployments_rest_call_success(request_type): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"instance": "projects/sample1/locations/sample2/instances/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 = findings_refinement.ListAllFindingsRefinementDeploymentsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_all_findings_refinement_deployments(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAllFindingsRefinementDeploymentsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_all_findings_refinement_deployments_rest_interceptors(null_interceptor): + transport = transports.FindingsRefinementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.FindingsRefinementServiceRestInterceptor(), + ) + client = FindingsRefinementServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "post_list_all_findings_refinement_deployments", + ) as post, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "post_list_all_findings_refinement_deployments_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "pre_list_all_findings_refinement_deployments", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = findings_refinement.ListAllFindingsRefinementDeploymentsRequest.pb( + findings_refinement.ListAllFindingsRefinementDeploymentsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = ( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse.to_json( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse() + ) + ) + req.return_value.content = return_value + + request = findings_refinement.ListAllFindingsRefinementDeploymentsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse() + ) + post_with_metadata.return_value = ( + findings_refinement.ListAllFindingsRefinementDeploymentsResponse(), + metadata, + ) + + client.list_all_findings_refinement_deployments( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_compute_findings_refinement_activity_rest_bad_request( + request_type=findings_refinement.ComputeFindingsRefinementActivityRequest, +): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/findingsRefinements/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.compute_findings_refinement_activity(request) + + +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.ComputeFindingsRefinementActivityRequest, + dict, + ], +) +def test_compute_findings_refinement_activity_rest_call_success(request_type): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/findingsRefinements/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = findings_refinement.ComputeFindingsRefinementActivityResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = findings_refinement.ComputeFindingsRefinementActivityResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.compute_findings_refinement_activity(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, findings_refinement.ComputeFindingsRefinementActivityResponse + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_compute_findings_refinement_activity_rest_interceptors(null_interceptor): + transport = transports.FindingsRefinementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.FindingsRefinementServiceRestInterceptor(), + ) + client = FindingsRefinementServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "post_compute_findings_refinement_activity", + ) as post, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "post_compute_findings_refinement_activity_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "pre_compute_findings_refinement_activity", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = findings_refinement.ComputeFindingsRefinementActivityRequest.pb( + findings_refinement.ComputeFindingsRefinementActivityRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = ( + findings_refinement.ComputeFindingsRefinementActivityResponse.to_json( + findings_refinement.ComputeFindingsRefinementActivityResponse() + ) + ) + req.return_value.content = return_value + + request = findings_refinement.ComputeFindingsRefinementActivityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + findings_refinement.ComputeFindingsRefinementActivityResponse() + ) + post_with_metadata.return_value = ( + findings_refinement.ComputeFindingsRefinementActivityResponse(), + metadata, + ) + + client.compute_findings_refinement_activity( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_compute_all_findings_refinement_activities_rest_bad_request( + request_type=findings_refinement.ComputeAllFindingsRefinementActivitiesRequest, +): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"instance": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.compute_all_findings_refinement_activities(request) + + +@pytest.mark.parametrize( + "request_type", + [ + findings_refinement.ComputeAllFindingsRefinementActivitiesRequest, + dict, + ], +) +def test_compute_all_findings_refinement_activities_rest_call_success(request_type): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"instance": "projects/sample1/locations/sample2/instances/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 = ( + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse() + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.compute_all_findings_refinement_activities(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, findings_refinement.ComputeAllFindingsRefinementActivitiesResponse + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_compute_all_findings_refinement_activities_rest_interceptors(null_interceptor): + transport = transports.FindingsRefinementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.FindingsRefinementServiceRestInterceptor(), + ) + client = FindingsRefinementServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "post_compute_all_findings_refinement_activities", + ) as post, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "post_compute_all_findings_refinement_activities_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.FindingsRefinementServiceRestInterceptor, + "pre_compute_all_findings_refinement_activities", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = ( + findings_refinement.ComputeAllFindingsRefinementActivitiesRequest.pb( + findings_refinement.ComputeAllFindingsRefinementActivitiesRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = ( + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse.to_json( + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse() + ) + ) + req.return_value.content = return_value + + request = findings_refinement.ComputeAllFindingsRefinementActivitiesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse() + ) + post_with_metadata.return_value = ( + findings_refinement.ComputeAllFindingsRefinementActivitiesResponse(), + metadata, + ) + + client.compute_all_findings_refinement_activities( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/instances/sample3/operations/sample4" + }, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/operations/sample4" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/instances/sample3/operations/sample4" + }, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/operations/sample4" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/instances/sample3/operations/sample4" + }, + request, + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/operations/sample4" + } + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/instances/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_findings_refinement_empty_call_rest(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_findings_refinement), "__call__" + ) as call: + client.get_findings_refinement(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.GetFindingsRefinementRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_findings_refinements_empty_call_rest(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_findings_refinements), "__call__" + ) as call: + client.list_findings_refinements(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.ListFindingsRefinementsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_findings_refinement_empty_call_rest(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_findings_refinement), "__call__" + ) as call: + client.create_findings_refinement(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcc_findings_refinement.CreateFindingsRefinementRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_findings_refinement_empty_call_rest(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_findings_refinement), "__call__" + ) as call: + client.update_findings_refinement(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcc_findings_refinement.UpdateFindingsRefinementRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_findings_refinement_deployment_empty_call_rest(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_findings_refinement_deployment), "__call__" + ) as call: + client.get_findings_refinement_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.GetFindingsRefinementDeploymentRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_findings_refinement_deployment_empty_call_rest(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_findings_refinement_deployment), "__call__" + ) as call: + client.update_findings_refinement_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.UpdateFindingsRefinementDeploymentRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_all_findings_refinement_deployments_empty_call_rest(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_all_findings_refinement_deployments), "__call__" + ) as call: + client.list_all_findings_refinement_deployments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.ListAllFindingsRefinementDeploymentsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_compute_findings_refinement_activity_empty_call_rest(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.compute_findings_refinement_activity), "__call__" + ) as call: + client.compute_findings_refinement_activity(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = findings_refinement.ComputeFindingsRefinementActivityRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_compute_all_findings_refinement_activities_empty_call_rest(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.compute_all_findings_refinement_activities), "__call__" + ) as call: + client.compute_all_findings_refinement_activities(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + findings_refinement.ComputeAllFindingsRefinementActivitiesRequest() + ) + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.FindingsRefinementServiceGrpcTransport, + ) + + +def test_findings_refinement_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.FindingsRefinementServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_findings_refinement_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.chronicle_v1.services.findings_refinement_service.transports.FindingsRefinementServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.FindingsRefinementServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get_findings_refinement", + "list_findings_refinements", + "create_findings_refinement", + "update_findings_refinement", + "get_findings_refinement_deployment", + "update_findings_refinement_deployment", + "list_all_findings_refinement_deployments", + "compute_findings_refinement_activity", + "compute_all_findings_refinement_activities", + "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() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_findings_refinement_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch( + "google.cloud.chronicle_v1.services.findings_refinement_service.transports.FindingsRefinementServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FindingsRefinementServiceTransport( + 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/chronicle", + "https://www.googleapis.com/auth/chronicle.readonly", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_findings_refinement_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch( + "google.cloud.chronicle_v1.services.findings_refinement_service.transports.FindingsRefinementServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FindingsRefinementServiceTransport() + adc.assert_called_once() + + +def test_findings_refinement_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + FindingsRefinementServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/chronicle", + "https://www.googleapis.com/auth/chronicle.readonly", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FindingsRefinementServiceGrpcTransport, + transports.FindingsRefinementServiceGrpcAsyncIOTransport, + ], +) +def test_findings_refinement_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/chronicle", + "https://www.googleapis.com/auth/chronicle.readonly", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FindingsRefinementServiceGrpcTransport, + transports.FindingsRefinementServiceGrpcAsyncIOTransport, + transports.FindingsRefinementServiceRestTransport, + ], +) +def test_findings_refinement_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FindingsRefinementServiceGrpcTransport, grpc_helpers), + (transports.FindingsRefinementServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_findings_refinement_service_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "chronicle.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/chronicle", + "https://www.googleapis.com/auth/chronicle.readonly", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=["1", "2"], + default_host="chronicle.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FindingsRefinementServiceGrpcTransport, + transports.FindingsRefinementServiceGrpcAsyncIOTransport, + ], +) +def test_findings_refinement_service_grpc_transport_client_cert_source_for_mtls( + transport_class, +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_findings_refinement_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.FindingsRefinementServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_findings_refinement_service_host_no_port(transport_name): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="chronicle.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "chronicle.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://chronicle.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_findings_refinement_service_host_with_port(transport_name): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="chronicle.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "chronicle.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://chronicle.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_findings_refinement_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = FindingsRefinementServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = FindingsRefinementServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_findings_refinement._session + session2 = client2.transport.get_findings_refinement._session + assert session1 != session2 + session1 = client1.transport.list_findings_refinements._session + session2 = client2.transport.list_findings_refinements._session + assert session1 != session2 + session1 = client1.transport.create_findings_refinement._session + session2 = client2.transport.create_findings_refinement._session + assert session1 != session2 + session1 = client1.transport.update_findings_refinement._session + session2 = client2.transport.update_findings_refinement._session + assert session1 != session2 + session1 = client1.transport.get_findings_refinement_deployment._session + session2 = client2.transport.get_findings_refinement_deployment._session + assert session1 != session2 + session1 = client1.transport.update_findings_refinement_deployment._session + session2 = client2.transport.update_findings_refinement_deployment._session + assert session1 != session2 + session1 = client1.transport.list_all_findings_refinement_deployments._session + session2 = client2.transport.list_all_findings_refinement_deployments._session + assert session1 != session2 + session1 = client1.transport.compute_findings_refinement_activity._session + session2 = client2.transport.compute_findings_refinement_activity._session + assert session1 != session2 + session1 = client1.transport.compute_all_findings_refinement_activities._session + session2 = client2.transport.compute_all_findings_refinement_activities._session + assert session1 != session2 + + +def test_findings_refinement_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FindingsRefinementServiceGrpcTransport( + 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_findings_refinement_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FindingsRefinementServiceGrpcAsyncIOTransport( + 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.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [ + transports.FindingsRefinementServiceGrpcTransport, + transports.FindingsRefinementServiceGrpcAsyncIOTransport, + ], +) +def test_findings_refinement_service_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.FindingsRefinementServiceGrpcTransport, + transports.FindingsRefinementServiceGrpcAsyncIOTransport, + ], +) +def test_findings_refinement_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_curated_rule_path(): + project = "squid" + location = "clam" + instance = "whelk" + curatedRule = "octopus" + expected = "projects/{project}/locations/{location}/instances/{instance}/curatedRules/{curatedRule}".format( + project=project, + location=location, + instance=instance, + curatedRule=curatedRule, + ) + actual = FindingsRefinementServiceClient.curated_rule_path( + project, location, instance, curatedRule + ) + assert expected == actual + + +def test_parse_curated_rule_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "instance": "cuttlefish", + "curatedRule": "mussel", + } + path = FindingsRefinementServiceClient.curated_rule_path(**expected) + + # Check that the path construction is reversible. + actual = FindingsRefinementServiceClient.parse_curated_rule_path(path) + assert expected == actual + + +def test_curated_rule_set_path(): + project = "winkle" + location = "nautilus" + instance = "scallop" + category = "abalone" + rule_set = "squid" + expected = "projects/{project}/locations/{location}/instances/{instance}/curatedRuleSetCategories/{category}/curatedRuleSets/{rule_set}".format( + project=project, + location=location, + instance=instance, + category=category, + rule_set=rule_set, + ) + actual = FindingsRefinementServiceClient.curated_rule_set_path( + project, location, instance, category, rule_set + ) + assert expected == actual + + +def test_parse_curated_rule_set_path(): + expected = { + "project": "clam", + "location": "whelk", + "instance": "octopus", + "category": "oyster", + "rule_set": "nudibranch", + } + path = FindingsRefinementServiceClient.curated_rule_set_path(**expected) + + # Check that the path construction is reversible. + actual = FindingsRefinementServiceClient.parse_curated_rule_set_path(path) + assert expected == actual + + +def test_findings_refinement_path(): + project = "cuttlefish" + location = "mussel" + instance = "winkle" + findings_refinement = "nautilus" + expected = "projects/{project}/locations/{location}/instances/{instance}/findingsRefinements/{findings_refinement}".format( + project=project, + location=location, + instance=instance, + findings_refinement=findings_refinement, + ) + actual = FindingsRefinementServiceClient.findings_refinement_path( + project, location, instance, findings_refinement + ) + assert expected == actual + + +def test_parse_findings_refinement_path(): + expected = { + "project": "scallop", + "location": "abalone", + "instance": "squid", + "findings_refinement": "clam", + } + path = FindingsRefinementServiceClient.findings_refinement_path(**expected) + + # Check that the path construction is reversible. + actual = FindingsRefinementServiceClient.parse_findings_refinement_path(path) + assert expected == actual + + +def test_findings_refinement_deployment_path(): + project = "whelk" + location = "octopus" + instance = "oyster" + findings_refinement = "nudibranch" + expected = "projects/{project}/locations/{location}/instances/{instance}/findingsRefinements/{findings_refinement}/deployment".format( + project=project, + location=location, + instance=instance, + findings_refinement=findings_refinement, + ) + actual = FindingsRefinementServiceClient.findings_refinement_deployment_path( + project, location, instance, findings_refinement + ) + assert expected == actual + + +def test_parse_findings_refinement_deployment_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "instance": "winkle", + "findings_refinement": "nautilus", + } + path = FindingsRefinementServiceClient.findings_refinement_deployment_path( + **expected + ) + + # Check that the path construction is reversible. + actual = FindingsRefinementServiceClient.parse_findings_refinement_deployment_path( + path + ) + assert expected == actual + + +def test_instance_path(): + project = "scallop" + location = "abalone" + instance = "squid" + expected = "projects/{project}/locations/{location}/instances/{instance}".format( + project=project, + location=location, + instance=instance, + ) + actual = FindingsRefinementServiceClient.instance_path(project, location, instance) + assert expected == actual + + +def test_parse_instance_path(): + expected = { + "project": "clam", + "location": "whelk", + "instance": "octopus", + } + path = FindingsRefinementServiceClient.instance_path(**expected) + + # Check that the path construction is reversible. + actual = FindingsRefinementServiceClient.parse_instance_path(path) + assert expected == actual + + +def test_rule_path(): + project = "oyster" + location = "nudibranch" + instance = "cuttlefish" + rule = "mussel" + expected = "projects/{project}/locations/{location}/instances/{instance}/rules/{rule}".format( + project=project, + location=location, + instance=instance, + rule=rule, + ) + actual = FindingsRefinementServiceClient.rule_path( + project, location, instance, rule + ) + assert expected == actual + + +def test_parse_rule_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "instance": "scallop", + "rule": "abalone", + } + path = FindingsRefinementServiceClient.rule_path(**expected) + + # Check that the path construction is reversible. + actual = FindingsRefinementServiceClient.parse_rule_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = FindingsRefinementServiceClient.common_billing_account_path( + billing_account + ) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = FindingsRefinementServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = FindingsRefinementServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = FindingsRefinementServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = FindingsRefinementServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = FindingsRefinementServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = FindingsRefinementServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = FindingsRefinementServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = FindingsRefinementServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = FindingsRefinementServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = FindingsRefinementServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = FindingsRefinementServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = FindingsRefinementServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = FindingsRefinementServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = FindingsRefinementServiceClient.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.FindingsRefinementServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.FindingsRefinementServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = FindingsRefinementServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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 = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional 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 = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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 = FindingsRefinementServiceClient( + 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 = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_delete_operation_flattened(): + client = FindingsRefinementServiceClient( + 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 + + client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +@pytest.mark.asyncio +async def test_delete_operation_flattened_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.DeleteOperationRequest() + + +def test_cancel_operation(transport: str = "grpc"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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 = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional 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 = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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 = FindingsRefinementServiceClient( + 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 = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation_flattened(): + client = FindingsRefinementServiceClient( + 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 + + client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +@pytest.mark.asyncio +async def test_cancel_operation_flattened_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.CancelOperationRequest() + + +def test_get_operation(transport: str = "grpc"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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 = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional 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 = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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 = FindingsRefinementServiceClient( + 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 = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation_flattened(): + client = FindingsRefinementServiceClient( + 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() + + client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +@pytest.mark.asyncio +async def test_get_operation_flattened_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.GetOperationRequest() + + +def test_list_operations(transport: str = "grpc"): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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 = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional 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 = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value 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 = FindingsRefinementServiceClient( + 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 = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations_flattened(): + client = FindingsRefinementServiceClient( + 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() + + client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +@pytest.mark.asyncio +async def test_list_operations_flattened_async(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == operations_pb2.ListOperationsRequest() + + +def test_transport_close_grpc(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = FindingsRefinementServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = FindingsRefinementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = FindingsRefinementServiceClient( + 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", + [ + ( + FindingsRefinementServiceClient, + transports.FindingsRefinementServiceGrpcTransport, + ), + ( + FindingsRefinementServiceAsyncClient, + transports.FindingsRefinementServiceGrpcAsyncIOTransport, + ), + ], +) +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-dataform/google/cloud/dataform_v1/services/dataform/async_client.py b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/async_client.py index 5ce702197067..53f09aab8936 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/async_client.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/async_client.py @@ -104,6 +104,10 @@ class DataformAsyncClient: ) folder_path = staticmethod(DataformClient.folder_path) parse_folder_path = staticmethod(DataformClient.parse_folder_path) + git_repository_link_path = staticmethod(DataformClient.git_repository_link_path) + parse_git_repository_link_path = staticmethod( + DataformClient.parse_git_repository_link_path + ) notebook_runtime_template_path = staticmethod( DataformClient.notebook_runtime_template_path ) @@ -996,8 +1000,9 @@ async def sample_query_team_folder_contents(): request (Optional[Union[google.cloud.dataform_v1.types.QueryTeamFolderContentsRequest, dict]]): The request object. ``QueryTeamFolderContents`` request message. team_folder (:class:`str`): - Required. Name of the team_folder whose contents to - list. Format: ``projects/*/locations/*/teamFolders/*``. + Required. Resource name of the TeamFolder to list + contents for. Format: + ``projects/*/locations/*/teamFolders/*``. This corresponds to the ``team_folder`` field on the ``request`` instance; if ``request`` is provided, this @@ -1832,8 +1837,8 @@ async def sample_query_folder_contents(): request (Optional[Union[google.cloud.dataform_v1.types.QueryFolderContentsRequest, dict]]): The request object. ``QueryFolderContents`` request message. folder (:class:`str`): - Required. Name of the folder whose contents to list. - Format: projects/*/locations/*/folders/\* + Required. Resource name of the Folder to list contents + for. Format: projects/*/locations/*/folders/\* This corresponds to the ``folder`` field on the ``request`` instance; if ``request`` is provided, this @@ -1959,8 +1964,8 @@ async def sample_query_user_root_contents(): request (Optional[Union[google.cloud.dataform_v1.types.QueryUserRootContentsRequest, dict]]): The request object. ``QueryUserRootContents`` request message. location (:class:`str`): - Required. Location of the user root folder whose - contents to list. Format: projects/*/locations/* + Required. Location of the user root folder to list + contents for. Format: projects/*/locations/* This corresponds to the ``location`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/client.py b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/client.py index e73876f05ce1..0f4c154d2b8b 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/client.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/client.py @@ -358,6 +358,30 @@ def parse_folder_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def git_repository_link_path( + project: str, + location: str, + connection: str, + git_repository_link: str, + ) -> str: + """Returns a fully-qualified git_repository_link string.""" + return "projects/{project}/locations/{location}/connections/{connection}/gitRepositoryLinks/{git_repository_link}".format( + project=project, + location=location, + connection=connection, + git_repository_link=git_repository_link, + ) + + @staticmethod + def parse_git_repository_link_path(path: str) -> Dict[str, str]: + """Parses a git_repository_link path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/connections/(?P.+?)/gitRepositoryLinks/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def notebook_runtime_template_path( project: str, @@ -1667,8 +1691,9 @@ def sample_query_team_folder_contents(): request (Union[google.cloud.dataform_v1.types.QueryTeamFolderContentsRequest, dict]): The request object. ``QueryTeamFolderContents`` request message. team_folder (str): - Required. Name of the team_folder whose contents to - list. Format: ``projects/*/locations/*/teamFolders/*``. + Required. Resource name of the TeamFolder to list + contents for. Format: + ``projects/*/locations/*/teamFolders/*``. This corresponds to the ``team_folder`` field on the ``request`` instance; if ``request`` is provided, this @@ -2485,8 +2510,8 @@ def sample_query_folder_contents(): request (Union[google.cloud.dataform_v1.types.QueryFolderContentsRequest, dict]): The request object. ``QueryFolderContents`` request message. folder (str): - Required. Name of the folder whose contents to list. - Format: projects/*/locations/*/folders/\* + Required. Resource name of the Folder to list contents + for. Format: projects/*/locations/*/folders/\* This corresponds to the ``folder`` field on the ``request`` instance; if ``request`` is provided, this @@ -2609,8 +2634,8 @@ def sample_query_user_root_contents(): request (Union[google.cloud.dataform_v1.types.QueryUserRootContentsRequest, dict]): The request object. ``QueryUserRootContents`` request message. location (str): - Required. Location of the user root folder whose - contents to list. Format: projects/*/locations/* + Required. Location of the user root folder to list + contents for. Format: projects/*/locations/* This corresponds to the ``location`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1/types/dataform.py b/packages/google-cloud-dataform/google/cloud/dataform_v1/types/dataform.py index 739dc3157363..382ba9371e8a 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1/types/dataform.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1/types/dataform.py @@ -172,7 +172,7 @@ class DirectoryContentsView(proto.Enum): Values: DIRECTORY_CONTENTS_VIEW_UNSPECIFIED (0): - The default / unset value. Defaults to + The default unset value. Defaults to DIRECTORY_CONTENTS_VIEW_BASIC. DIRECTORY_CONTENTS_VIEW_BASIC (1): Includes only the file or directory name. @@ -284,12 +284,18 @@ class Repository(proto.Message): class GitRemoteSettings(proto.Message): r"""Controls Git remote configuration for a repository. + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: url (str): Required. The Git remote's URL. default_branch (str): - Required. The Git remote's default branch - name. + Optional. The Git remote's default branch name. If not set, + ``main`` will be used. + effective_default_branch (str): + Output only. The Git remote's effective default branch name. + This is the default branch name of the Git remote if it is + set, otherwise it is ``main``. authentication_token_secret_version (str): Optional. The name of the Secret Manager secret version to use as an authentication token for Git operations. Must be @@ -297,6 +303,12 @@ class GitRemoteSettings(proto.Message): ssh_authentication_config (google.cloud.dataform_v1.types.Repository.GitRemoteSettings.SshAuthenticationConfig): Optional. Authentication fields for remote uris using SSH protocol. + git_repository_link (str): + Optional. Resource name for the ``GitRepositoryLink`` used + for machine credentials. Must be in the format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*`` + + This field is a member of `oneof`_ ``_git_repository_link``. token_status (google.cloud.dataform_v1.types.Repository.GitRemoteSettings.TokenStatus): Output only. Deprecated: The field does not contain any token status information. @@ -355,6 +367,10 @@ class SshAuthenticationConfig(proto.Message): proto.STRING, number=2, ) + effective_default_branch: str = proto.Field( + proto.STRING, + number=9, + ) authentication_token_secret_version: str = proto.Field( proto.STRING, number=3, @@ -364,6 +380,11 @@ class SshAuthenticationConfig(proto.Message): number=5, message="Repository.GitRemoteSettings.SshAuthenticationConfig", ) + git_repository_link: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) token_status: "Repository.GitRemoteSettings.TokenStatus" = proto.Field( proto.ENUM, number=4, @@ -1740,11 +1761,15 @@ class DirectoryEntry(proto.Message): Attributes: file (str): - A file in the directory. + A file in the directory. The path is returned + including the full folder structure from the + root. This field is a member of `oneof`_ ``entry``. directory (str): - A child directory in the directory. + A child directory in the directory. The path + is returned including the full folder structure + from the root. This field is a member of `oneof`_ ``entry``. metadata (google.cloud.dataform_v1.types.FilesystemEntryMetadata): @@ -4511,11 +4536,11 @@ class NotebookAction(proto.Message): Output only. The code contents of a Notebook to be run. job_id (str): - Output only. The ID of the Vertex job that - executed the notebook in contents and also the - ID used for the outputs created in Google Cloud - Storage buckets. Only set once the job has - started to run. + Output only. The ID of the Gemini Enterprise + Agent Platform job that executed the notebook in + contents and also the ID used for the outputs + created in Google Cloud Storage buckets. Only + set once the job has started to run. """ contents: str = proto.Field( @@ -4909,9 +4934,8 @@ class Folder(proto.Message): name. This should take the format: projects/{project}/locations/{location}/folders/{folder}, projects/{project}/locations/{location}/teamFolders/{teamFolder}, - or just projects/{project}/locations/{location} - if this is a root Folder. This field can only be - updated through MoveFolder. + or just "" if this is a root Folder. This field + can only be updated through MoveFolder. team_folder_name (str): Output only. The resource name of the TeamFolder that this Folder is associated with. @@ -5216,8 +5240,8 @@ class QueryFolderContentsRequest(proto.Message): Attributes: folder (str): - Required. Name of the folder whose contents to list. Format: - projects/*/locations/*/folders/\* + Required. Resource name of the Folder to list contents for. + Format: projects/*/locations/*/folders/\* page_size (int): Optional. Maximum number of paths to return. The server may return fewer items than @@ -5338,8 +5362,8 @@ class QueryUserRootContentsRequest(proto.Message): Attributes: location (str): - Required. Location of the user root folder whose contents to - list. Format: projects/*/locations/* + Required. Location of the user root folder to list contents + for. Format: projects/*/locations/* page_size (int): Optional. Maximum number of paths to return. The server may return fewer items than @@ -5599,8 +5623,8 @@ class QueryTeamFolderContentsRequest(proto.Message): Attributes: team_folder (str): - Required. Name of the team_folder whose contents to list. - Format: ``projects/*/locations/*/teamFolders/*``. + Required. Resource name of the TeamFolder to list contents + for. Format: ``projects/*/locations/*/teamFolders/*``. page_size (int): Optional. Maximum number of paths to return. The server may return fewer items than @@ -5724,10 +5748,10 @@ class SearchTeamFoldersRequest(proto.Message): Required. Location in which to query TeamFolders. Format: ``projects/*/locations/*``. page_size (int): - Optional. Maximum number of TeamFolders to - return. The server may return fewer items than - requested. If unspecified, the server will pick - an appropriate default. + Optional. Maximum number of ``TeamFolders`` to return. The + server may return fewer items than requested. If + unspecified, the server will pick a default of ``page_size`` + = 50. page_token (str): Optional. Page token received from a previous ``SearchTeamFolders`` call. Provide this to retrieve the diff --git a/packages/google-cloud-dataform/tests/unit/gapic/dataform_v1/test_dataform.py b/packages/google-cloud-dataform/tests/unit/gapic/dataform_v1/test_dataform.py index 81e4f50cb6f7..dc14a0852b7b 100644 --- a/packages/google-cloud-dataform/tests/unit/gapic/dataform_v1/test_dataform.py +++ b/packages/google-cloud-dataform/tests/unit/gapic/dataform_v1/test_dataform.py @@ -46844,11 +46844,13 @@ def test_create_repository_rest_call_success(request_type): "git_remote_settings": { "url": "url_value", "default_branch": "default_branch_value", + "effective_default_branch": "effective_default_branch_value", "authentication_token_secret_version": "authentication_token_secret_version_value", "ssh_authentication_config": { "user_private_key_secret_version": "user_private_key_secret_version_value", "host_public_key": "host_public_key_value", }, + "git_repository_link": "git_repository_link_value", "token_status": 1, }, "npmrc_environment_variables_secret_version": "npmrc_environment_variables_secret_version_value", @@ -47095,11 +47097,13 @@ def test_update_repository_rest_call_success(request_type): "git_remote_settings": { "url": "url_value", "default_branch": "default_branch_value", + "effective_default_branch": "effective_default_branch_value", "authentication_token_secret_version": "authentication_token_secret_version_value", "ssh_authentication_config": { "user_private_key_secret_version": "user_private_key_secret_version_value", "host_public_key": "host_public_key_value", }, + "git_repository_link": "git_repository_link_value", "token_status": 1, }, "npmrc_environment_variables_secret_version": "npmrc_environment_variables_secret_version_value", @@ -57967,10 +57971,41 @@ def test_parse_folder_path(): assert expected == actual -def test_notebook_runtime_template_path(): +def test_git_repository_link_path(): project = "squid" location = "clam" - notebook_runtime_template = "whelk" + connection = "whelk" + git_repository_link = "octopus" + expected = "projects/{project}/locations/{location}/connections/{connection}/gitRepositoryLinks/{git_repository_link}".format( + project=project, + location=location, + connection=connection, + git_repository_link=git_repository_link, + ) + actual = DataformClient.git_repository_link_path( + project, location, connection, git_repository_link + ) + assert expected == actual + + +def test_parse_git_repository_link_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "connection": "cuttlefish", + "git_repository_link": "mussel", + } + path = DataformClient.git_repository_link_path(**expected) + + # Check that the path construction is reversible. + actual = DataformClient.parse_git_repository_link_path(path) + assert expected == actual + + +def test_notebook_runtime_template_path(): + project = "winkle" + location = "nautilus" + notebook_runtime_template = "scallop" expected = "projects/{project}/locations/{location}/notebookRuntimeTemplates/{notebook_runtime_template}".format( project=project, location=location, @@ -57984,9 +58019,9 @@ def test_notebook_runtime_template_path(): def test_parse_notebook_runtime_template_path(): expected = { - "project": "octopus", - "location": "oyster", - "notebook_runtime_template": "nudibranch", + "project": "abalone", + "location": "squid", + "notebook_runtime_template": "clam", } path = DataformClient.notebook_runtime_template_path(**expected) @@ -57996,10 +58031,10 @@ def test_parse_notebook_runtime_template_path(): def test_release_config_path(): - project = "cuttlefish" - location = "mussel" - repository = "winkle" - release_config = "nautilus" + project = "whelk" + location = "octopus" + repository = "oyster" + release_config = "nudibranch" expected = "projects/{project}/locations/{location}/repositories/{repository}/releaseConfigs/{release_config}".format( project=project, location=location, @@ -58014,10 +58049,10 @@ def test_release_config_path(): def test_parse_release_config_path(): expected = { - "project": "scallop", - "location": "abalone", - "repository": "squid", - "release_config": "clam", + "project": "cuttlefish", + "location": "mussel", + "repository": "winkle", + "release_config": "nautilus", } path = DataformClient.release_config_path(**expected) @@ -58027,9 +58062,9 @@ def test_parse_release_config_path(): def test_repository_path(): - project = "whelk" - location = "octopus" - repository = "oyster" + project = "scallop" + location = "abalone" + repository = "squid" expected = ( "projects/{project}/locations/{location}/repositories/{repository}".format( project=project, @@ -58043,9 +58078,9 @@ def test_repository_path(): def test_parse_repository_path(): expected = { - "project": "nudibranch", - "location": "cuttlefish", - "repository": "mussel", + "project": "clam", + "location": "whelk", + "repository": "octopus", } path = DataformClient.repository_path(**expected) @@ -58055,9 +58090,9 @@ def test_parse_repository_path(): def test_secret_version_path(): - project = "winkle" - secret = "nautilus" - version = "scallop" + project = "oyster" + secret = "nudibranch" + version = "cuttlefish" expected = "projects/{project}/secrets/{secret}/versions/{version}".format( project=project, secret=secret, @@ -58069,9 +58104,9 @@ def test_secret_version_path(): def test_parse_secret_version_path(): expected = { - "project": "abalone", - "secret": "squid", - "version": "clam", + "project": "mussel", + "secret": "winkle", + "version": "nautilus", } path = DataformClient.secret_version_path(**expected) @@ -58081,9 +58116,9 @@ def test_parse_secret_version_path(): def test_team_folder_path(): - project = "whelk" - location = "octopus" - team_folder = "oyster" + project = "scallop" + location = "abalone" + team_folder = "squid" expected = ( "projects/{project}/locations/{location}/teamFolders/{team_folder}".format( project=project, @@ -58097,9 +58132,9 @@ def test_team_folder_path(): def test_parse_team_folder_path(): expected = { - "project": "nudibranch", - "location": "cuttlefish", - "team_folder": "mussel", + "project": "clam", + "location": "whelk", + "team_folder": "octopus", } path = DataformClient.team_folder_path(**expected) @@ -58109,10 +58144,10 @@ def test_parse_team_folder_path(): def test_workflow_config_path(): - project = "winkle" - location = "nautilus" - repository = "scallop" - workflow_config = "abalone" + project = "oyster" + location = "nudibranch" + repository = "cuttlefish" + workflow_config = "mussel" expected = "projects/{project}/locations/{location}/repositories/{repository}/workflowConfigs/{workflow_config}".format( project=project, location=location, @@ -58127,10 +58162,10 @@ def test_workflow_config_path(): def test_parse_workflow_config_path(): expected = { - "project": "squid", - "location": "clam", - "repository": "whelk", - "workflow_config": "octopus", + "project": "winkle", + "location": "nautilus", + "repository": "scallop", + "workflow_config": "abalone", } path = DataformClient.workflow_config_path(**expected) @@ -58140,10 +58175,10 @@ def test_parse_workflow_config_path(): def test_workflow_invocation_path(): - project = "oyster" - location = "nudibranch" - repository = "cuttlefish" - workflow_invocation = "mussel" + project = "squid" + location = "clam" + repository = "whelk" + workflow_invocation = "octopus" expected = "projects/{project}/locations/{location}/repositories/{repository}/workflowInvocations/{workflow_invocation}".format( project=project, location=location, @@ -58158,10 +58193,10 @@ def test_workflow_invocation_path(): def test_parse_workflow_invocation_path(): expected = { - "project": "winkle", - "location": "nautilus", - "repository": "scallop", - "workflow_invocation": "abalone", + "project": "oyster", + "location": "nudibranch", + "repository": "cuttlefish", + "workflow_invocation": "mussel", } path = DataformClient.workflow_invocation_path(**expected) @@ -58171,10 +58206,10 @@ def test_parse_workflow_invocation_path(): def test_workspace_path(): - project = "squid" - location = "clam" - repository = "whelk" - workspace = "octopus" + project = "winkle" + location = "nautilus" + repository = "scallop" + workspace = "abalone" expected = "projects/{project}/locations/{location}/repositories/{repository}/workspaces/{workspace}".format( project=project, location=location, @@ -58187,10 +58222,10 @@ def test_workspace_path(): def test_parse_workspace_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "repository": "cuttlefish", - "workspace": "mussel", + "project": "squid", + "location": "clam", + "repository": "whelk", + "workspace": "octopus", } path = DataformClient.workspace_path(**expected) @@ -58200,7 +58235,7 @@ def test_parse_workspace_path(): def test_common_billing_account_path(): - billing_account = "winkle" + billing_account = "oyster" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -58210,7 +58245,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nautilus", + "billing_account": "nudibranch", } path = DataformClient.common_billing_account_path(**expected) @@ -58220,7 +58255,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "scallop" + folder = "cuttlefish" expected = "folders/{folder}".format( folder=folder, ) @@ -58230,7 +58265,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "abalone", + "folder": "mussel", } path = DataformClient.common_folder_path(**expected) @@ -58240,7 +58275,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "squid" + organization = "winkle" expected = "organizations/{organization}".format( organization=organization, ) @@ -58250,7 +58285,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "clam", + "organization": "nautilus", } path = DataformClient.common_organization_path(**expected) @@ -58260,7 +58295,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "whelk" + project = "scallop" expected = "projects/{project}".format( project=project, ) @@ -58270,7 +58305,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "octopus", + "project": "abalone", } path = DataformClient.common_project_path(**expected) @@ -58280,8 +58315,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "oyster" - location = "nudibranch" + project = "squid" + location = "clam" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -58292,8 +58327,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "cuttlefish", - "location": "mussel", + "project": "whelk", + "location": "octopus", } path = DataformClient.common_location_path(**expected) diff --git a/packages/google-cloud-dataproc/google/cloud/dataproc/__init__.py b/packages/google-cloud-dataproc/google/cloud/dataproc/__init__.py index f478b42e296e..e0d7004d9dc8 100644 --- a/packages/google-cloud-dataproc/google/cloud/dataproc/__init__.py +++ b/packages/google-cloud-dataproc/google/cloud/dataproc/__init__.py @@ -91,6 +91,7 @@ ) from google.cloud.dataproc_v1.types.clusters import ( AcceleratorConfig, + AttachedDiskConfig, AutoscalingConfig, AuxiliaryNodeGroup, AuxiliaryServicesConfig, @@ -277,6 +278,7 @@ "SparkRBatch", "SparkSqlBatch", "AcceleratorConfig", + "AttachedDiskConfig", "AutoscalingConfig", "AuxiliaryNodeGroup", "AuxiliaryServicesConfig", diff --git a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/__init__.py b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/__init__.py index 0743d394c587..47610bde3dbd 100644 --- a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/__init__.py +++ b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/__init__.py @@ -76,6 +76,7 @@ ) from .types.clusters import ( AcceleratorConfig, + AttachedDiskConfig, AutoscalingConfig, AuxiliaryNodeGroup, AuxiliaryServicesConfig, @@ -316,6 +317,7 @@ def _get_version(dependency_name): "SessionTemplateControllerAsyncClient", "WorkflowTemplateServiceAsyncClient", "AcceleratorConfig", + "AttachedDiskConfig", "AuthenticationConfig", "AutoscalingConfig", "AutoscalingPolicy", diff --git a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/types/__init__.py b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/types/__init__.py index f269529ae192..66bf6f238263 100644 --- a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/types/__init__.py +++ b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/types/__init__.py @@ -40,6 +40,7 @@ ) from .clusters import ( AcceleratorConfig, + AttachedDiskConfig, AutoscalingConfig, AuxiliaryNodeGroup, AuxiliaryServicesConfig, @@ -210,6 +211,7 @@ "SparkRBatch", "SparkSqlBatch", "AcceleratorConfig", + "AttachedDiskConfig", "AutoscalingConfig", "AuxiliaryNodeGroup", "AuxiliaryServicesConfig", diff --git a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/types/clusters.py b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/types/clusters.py index 8aff97ba7039..235f17b2db2c 100644 --- a/packages/google-cloud-dataproc/google/cloud/dataproc_v1/types/clusters.py +++ b/packages/google-cloud-dataproc/google/cloud/dataproc_v1/types/clusters.py @@ -46,6 +46,7 @@ "InstanceFlexibilityPolicy", "AcceleratorConfig", "DiskConfig", + "AttachedDiskConfig", "AuxiliaryNodeGroup", "NodeGroup", "NodeInitializationAction", @@ -1305,6 +1306,14 @@ class InstanceSelection(proto.Message): to next rank based on availability. Machine types and instance selections with the same priority have the same preference. + disk_config (google.cloud.dataproc_v1.types.DiskConfig): + Optional. Disk configuration to apply to the + instances in this instance selection. If + specified on any entry in instanceSelectionList, + then it must be specified on every entry in + instanceSelectionList and the + instanceGroupConfig must not specify any + diskConfig. """ machine_types: MutableSequence[str] = proto.RepeatedField( @@ -1315,6 +1324,11 @@ class InstanceSelection(proto.Message): proto.INT32, number=2, ) + disk_config: "DiskConfig" = proto.Field( + proto.MESSAGE, + number=3, + message="DiskConfig", + ) class InstanceSelectionResult(proto.Message): r"""Defines a mapping from machine types to the number of VMs @@ -1403,19 +1417,19 @@ class AcceleratorConfig(proto.Message): class DiskConfig(proto.Message): - r"""Specifies the config of disk options for a group of VM - instances. + r"""Specifies the config of boot disk and attached disk options + for a group of VM instances. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: boot_disk_type (str): - Optional. Type of the boot disk (default is "pd-standard"). - Valid values: "pd-balanced" (Persistent Disk Balanced Solid - State Drive), "pd-ssd" (Persistent Disk Solid State Drive), - or "pd-standard" (Persistent Disk Hard Disk Drive). See - `Disk + Optional. Type of the boot disk (default is + ``pd-standard``). Valid values: ``pd-balanced`` (Persistent + Disk Balanced Solid State Drive), ``pd-ssd`` (Persistent + Disk Solid State Drive), or ``pd-standard`` (Persistent Disk + Hard Disk Drive). See `Disk types `__. boot_disk_size_gb (int): Optional. Size in GB of the boot disk @@ -1432,25 +1446,31 @@ class DiskConfig(proto.Message): Note: Local SSD options may vary by machine type and number of vCPUs selected. local_ssd_interface (str): - Optional. Interface type of local SSDs (default is "scsi"). - Valid values: "scsi" (Small Computer System Interface), - "nvme" (Non-Volatile Memory Express). See `local SSD + Optional. Interface type of local SSDs (default is + ``scsi``). Valid values: ``scsi`` (Small Computer System + Interface), ``nvme`` (Non-Volatile Memory Express). See + `local SSD performance `__. boot_disk_provisioned_iops (int): Optional. Indicates how many IOPS to provision for the disk. This sets the number of I/O operations per second that the - disk can handle. Note: This field is only supported if - boot_disk_type is hyperdisk-balanced. + disk can handle. **This field is supported only if + [boot_disk_type][google.cloud.dataproc.v1.DiskConfig.boot_disk_type] + is ``hyperdisk-balanced``.** This field is a member of `oneof`_ ``_boot_disk_provisioned_iops``. boot_disk_provisioned_throughput (int): Optional. Indicates how much throughput to provision for the disk. This sets the number of throughput mb per second that the disk can handle. Values must be greater than or equal to - 1. Note: This field is only supported if boot_disk_type is - hyperdisk-balanced. + 1. **This field is supported only if + [boot_disk_type][google.cloud.dataproc.v1.DiskConfig.boot_disk_type] + is ``hyperdisk-balanced``.** This field is a member of `oneof`_ ``_boot_disk_provisioned_throughput``. + attached_disk_configs (MutableSequence[google.cloud.dataproc_v1.types.AttachedDiskConfig]): + Optional. A list of attached disk configs for + a group of VM instances. """ boot_disk_type: str = proto.Field( @@ -1479,6 +1499,84 @@ class DiskConfig(proto.Message): number=6, optional=True, ) + attached_disk_configs: MutableSequence["AttachedDiskConfig"] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message="AttachedDiskConfig", + ) + + +class AttachedDiskConfig(proto.Message): + r"""Specifies the config of attached disk options for single VM + instance. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + disk_type (google.cloud.dataproc_v1.types.AttachedDiskConfig.DiskType): + Optional. Disk type. + disk_size_gb (int): + Optional. Disk size in GB. + provisioned_iops (int): + Optional. Indicates how many IOPS to + provision for the attached disk. This sets the + number of I/O operations per second that the + disk can handle. See + https://cloud.google.com/compute/docs/disks/hyperdisks#hyperdisk-features + + This field is a member of `oneof`_ ``_provisioned_iops``. + provisioned_throughput (int): + Optional. Indicates how much throughput to + provision for the attached disk. This sets the + number of throughput mb per second that the disk + can handle. See + https://cloud.google.com/compute/docs/disks/hyperdisks#hyperdisk-features + + This field is a member of `oneof`_ ``_provisioned_throughput``. + """ + + class DiskType(proto.Enum): + r""" + + Values: + DISK_TYPE_UNSPECIFIED (0): + Required unspecified disk type. + HYPERDISK_BALANCED (1): + Hyperdisk Balanced disk type. + HYPERDISK_EXTREME (2): + Hyperdisk Extreme disk type. + HYPERDISK_ML (3): + Hyperdisk ML disk type. + HYPERDISK_THROUGHPUT (4): + Hyperdisk Throughput disk type. + """ + + DISK_TYPE_UNSPECIFIED = 0 + HYPERDISK_BALANCED = 1 + HYPERDISK_EXTREME = 2 + HYPERDISK_ML = 3 + HYPERDISK_THROUGHPUT = 4 + + disk_type: DiskType = proto.Field( + proto.ENUM, + number=1, + enum=DiskType, + ) + disk_size_gb: int = proto.Field( + proto.INT32, + number=2, + ) + provisioned_iops: int = proto.Field( + proto.INT64, + number=3, + optional=True, + ) + provisioned_throughput: int = proto.Field( + proto.INT64, + number=4, + optional=True, + ) class AuxiliaryNodeGroup(proto.Message): diff --git a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_cluster_controller.py b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_cluster_controller.py index 026ebf0a39ed..9346d7335163 100644 --- a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_cluster_controller.py +++ b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_cluster_controller.py @@ -6420,6 +6420,14 @@ def test_create_cluster_rest_call_success(request_type): "local_ssd_interface": "local_ssd_interface_value", "boot_disk_provisioned_iops": 2793, "boot_disk_provisioned_throughput": 3464, + "attached_disk_configs": [ + { + "disk_type": 1, + "disk_size_gb": 1261, + "provisioned_iops": 1740, + "provisioned_throughput": 2411, + } + ], }, "is_preemptible": True, "preemptibility": 1, @@ -6448,6 +6456,7 @@ def test_create_cluster_rest_call_success(request_type): "machine_types_value2", ], "rank": 428, + "disk_config": {}, } ], "instance_selection_results": [ @@ -6844,6 +6853,14 @@ def test_update_cluster_rest_call_success(request_type): "local_ssd_interface": "local_ssd_interface_value", "boot_disk_provisioned_iops": 2793, "boot_disk_provisioned_throughput": 3464, + "attached_disk_configs": [ + { + "disk_type": 1, + "disk_size_gb": 1261, + "provisioned_iops": 1740, + "provisioned_throughput": 2411, + } + ], }, "is_preemptible": True, "preemptibility": 1, @@ -6872,6 +6889,7 @@ def test_update_cluster_rest_call_success(request_type): "machine_types_value2", ], "rank": 428, + "disk_config": {}, } ], "instance_selection_results": [ diff --git a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_node_group_controller.py b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_node_group_controller.py index 1b2ebd91131f..ace124f91eb5 100644 --- a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_node_group_controller.py +++ b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_node_group_controller.py @@ -3354,6 +3354,14 @@ def test_create_node_group_rest_call_success(request_type): "local_ssd_interface": "local_ssd_interface_value", "boot_disk_provisioned_iops": 2793, "boot_disk_provisioned_throughput": 3464, + "attached_disk_configs": [ + { + "disk_type": 1, + "disk_size_gb": 1261, + "provisioned_iops": 1740, + "provisioned_throughput": 2411, + } + ], }, "is_preemptible": True, "preemptibility": 1, @@ -3382,6 +3390,7 @@ def test_create_node_group_rest_call_success(request_type): "machine_types_value2", ], "rank": 428, + "disk_config": {}, } ], "instance_selection_results": [ diff --git a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_workflow_template_service.py b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_workflow_template_service.py index eba33660ce14..26ee211fbaac 100644 --- a/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_workflow_template_service.py +++ b/packages/google-cloud-dataproc/tests/unit/gapic/dataproc_v1/test_workflow_template_service.py @@ -6058,6 +6058,14 @@ def test_create_workflow_template_rest_call_success(request_type): "local_ssd_interface": "local_ssd_interface_value", "boot_disk_provisioned_iops": 2793, "boot_disk_provisioned_throughput": 3464, + "attached_disk_configs": [ + { + "disk_type": 1, + "disk_size_gb": 1261, + "provisioned_iops": 1740, + "provisioned_throughput": 2411, + } + ], }, "is_preemptible": True, "preemptibility": 1, @@ -6086,6 +6094,7 @@ def test_create_workflow_template_rest_call_success(request_type): "machine_types_value2", ], "rank": 428, + "disk_config": {}, } ], "instance_selection_results": [ @@ -6856,6 +6865,14 @@ def test_instantiate_inline_workflow_template_rest_call_success(request_type): "local_ssd_interface": "local_ssd_interface_value", "boot_disk_provisioned_iops": 2793, "boot_disk_provisioned_throughput": 3464, + "attached_disk_configs": [ + { + "disk_type": 1, + "disk_size_gb": 1261, + "provisioned_iops": 1740, + "provisioned_throughput": 2411, + } + ], }, "is_preemptible": True, "preemptibility": 1, @@ -6884,6 +6901,7 @@ def test_instantiate_inline_workflow_template_rest_call_success(request_type): "machine_types_value2", ], "rank": 428, + "disk_config": {}, } ], "instance_selection_results": [ @@ -7372,6 +7390,14 @@ def test_update_workflow_template_rest_call_success(request_type): "local_ssd_interface": "local_ssd_interface_value", "boot_disk_provisioned_iops": 2793, "boot_disk_provisioned_throughput": 3464, + "attached_disk_configs": [ + { + "disk_type": 1, + "disk_size_gb": 1261, + "provisioned_iops": 1740, + "provisioned_throughput": 2411, + } + ], }, "is_preemptible": True, "preemptibility": 1, @@ -7400,6 +7426,7 @@ def test_update_workflow_template_rest_call_success(request_type): "machine_types_value2", ], "rank": 428, + "disk_config": {}, } ], "instance_selection_results": [ diff --git a/packages/google-cloud-datastore/google/cloud/datastore_v1/__init__.py b/packages/google-cloud-datastore/google/cloud/datastore_v1/__init__.py index 7017a18c095c..2607dee6689d 100644 --- a/packages/google-cloud-datastore/google/cloud/datastore_v1/__init__.py +++ b/packages/google-cloud-datastore/google/cloud/datastore_v1/__init__.py @@ -39,6 +39,7 @@ PropertyMask, PropertyTransform, ReadOptions, + RequestOptions, ReserveIdsRequest, ReserveIdsResponse, RollbackRequest, @@ -196,6 +197,7 @@ def _get_version(dependency_name): "Query", "QueryResultBatch", "ReadOptions", + "RequestOptions", "ReserveIdsRequest", "ReserveIdsResponse", "RollbackRequest", diff --git a/packages/google-cloud-datastore/google/cloud/datastore_v1/types/__init__.py b/packages/google-cloud-datastore/google/cloud/datastore_v1/types/__init__.py index 5369641b03ec..879dd25da5c3 100644 --- a/packages/google-cloud-datastore/google/cloud/datastore_v1/types/__init__.py +++ b/packages/google-cloud-datastore/google/cloud/datastore_v1/types/__init__.py @@ -31,6 +31,7 @@ PropertyMask, PropertyTransform, ReadOptions, + RequestOptions, ReserveIdsRequest, ReserveIdsResponse, RollbackRequest, @@ -87,6 +88,7 @@ "PropertyMask", "PropertyTransform", "ReadOptions", + "RequestOptions", "ReserveIdsRequest", "ReserveIdsResponse", "RollbackRequest", diff --git a/packages/google-cloud-datastore/google/cloud/datastore_v1/types/datastore.py b/packages/google-cloud-datastore/google/cloud/datastore_v1/types/datastore.py index e1fc76b9308d..f1b4ced73ae9 100644 --- a/packages/google-cloud-datastore/google/cloud/datastore_v1/types/datastore.py +++ b/packages/google-cloud-datastore/google/cloud/datastore_v1/types/datastore.py @@ -48,6 +48,7 @@ "PropertyMask", "ReadOptions", "TransactionOptions", + "RequestOptions", }, ) @@ -78,6 +79,8 @@ class LookupRequest(proto.Message): [LookupResponse.found.entity.properties][]. The entity's key is always returned. + request_options (google.cloud.datastore_v1.types.RequestOptions): + Optional. The options for this request. """ project_id: str = proto.Field( @@ -103,6 +106,11 @@ class LookupRequest(proto.Message): number=5, message="PropertyMask", ) + request_options: "RequestOptions" = proto.Field( + proto.MESSAGE, + number=10, + message="RequestOptions", + ) class LookupResponse(proto.Message): @@ -210,6 +218,8 @@ class RunQueryRequest(proto.Message): set, additional query statistics will be returned. If not, only query results will be returned. + request_options (google.cloud.datastore_v1.types.RequestOptions): + Optional. The options for this request. """ project_id: str = proto.Field( @@ -252,6 +262,11 @@ class RunQueryRequest(proto.Message): number=12, message=query_profile.ExplainOptions, ) + request_options: "RequestOptions" = proto.Field( + proto.MESSAGE, + number=13, + message="RequestOptions", + ) class RunQueryResponse(proto.Message): @@ -260,7 +275,12 @@ class RunQueryResponse(proto.Message): Attributes: batch (google.cloud.datastore_v1.types.QueryResultBatch): - A batch of query results (always present). + A batch of query results. This is always present unless + running a query under explain-only mode: + [RunQueryRequest.explain_options][google.datastore.v1.RunQueryRequest.explain_options] + was provided and + [ExplainOptions.analyze][google.datastore.v1.ExplainOptions.analyze] + was set to false. query (google.cloud.datastore_v1.types.Query): The parsed form of the ``GqlQuery`` from the request, if it was set. @@ -342,6 +362,8 @@ class RunAggregationQueryRequest(proto.Message): set, additional query statistics will be returned. If not, only query results will be returned. + request_options (google.cloud.datastore_v1.types.RequestOptions): + Optional. The options for this request. """ project_id: str = proto.Field( @@ -379,6 +401,11 @@ class RunAggregationQueryRequest(proto.Message): number=11, message=query_profile.ExplainOptions, ) + request_options: "RequestOptions" = proto.Field( + proto.MESSAGE, + number=12, + message="RequestOptions", + ) class RunAggregationQueryResponse(proto.Message): @@ -443,6 +470,8 @@ class BeginTransactionRequest(proto.Message): string '' to refer the default database. transaction_options (google.cloud.datastore_v1.types.TransactionOptions): Options for a new transaction. + request_options (google.cloud.datastore_v1.types.RequestOptions): + Optional. The options for this request. """ project_id: str = proto.Field( @@ -458,6 +487,11 @@ class BeginTransactionRequest(proto.Message): number=10, message="TransactionOptions", ) + request_options: "RequestOptions" = proto.Field( + proto.MESSAGE, + number=11, + message="RequestOptions", + ) class BeginTransactionResponse(proto.Message): @@ -491,6 +525,8 @@ class RollbackRequest(proto.Message): transaction (bytes): Required. The transaction identifier, returned by a call to [Datastore.BeginTransaction][google.datastore.v1.Datastore.BeginTransaction]. + request_options (google.cloud.datastore_v1.types.RequestOptions): + Optional. The options for this request. """ project_id: str = proto.Field( @@ -505,6 +541,11 @@ class RollbackRequest(proto.Message): proto.BYTES, number=1, ) + request_options: "RequestOptions" = proto.Field( + proto.MESSAGE, + number=10, + message="RequestOptions", + ) class RollbackResponse(proto.Message): @@ -568,6 +609,8 @@ class CommitRequest(proto.Message): When mode is ``NON_TRANSACTIONAL``, no two mutations may affect a single entity. + request_options (google.cloud.datastore_v1.types.RequestOptions): + Optional. The options for this request. """ class Mode(proto.Enum): @@ -618,6 +661,11 @@ class Mode(proto.Enum): number=6, message="Mutation", ) + request_options: "RequestOptions" = proto.Field( + proto.MESSAGE, + number=11, + message="RequestOptions", + ) class CommitResponse(proto.Message): @@ -670,6 +718,8 @@ class AllocateIdsRequest(proto.Message): Required. A list of keys with incomplete key paths for which to allocate IDs. No key may be reserved/read-only. + request_options (google.cloud.datastore_v1.types.RequestOptions): + Optional. The options for this request. """ project_id: str = proto.Field( @@ -685,6 +735,11 @@ class AllocateIdsRequest(proto.Message): number=1, message=entity.Key, ) + request_options: "RequestOptions" = proto.Field( + proto.MESSAGE, + number=10, + message="RequestOptions", + ) class AllocateIdsResponse(proto.Message): @@ -722,6 +777,8 @@ class ReserveIdsRequest(proto.Message): Required. A list of keys with complete key paths whose numeric IDs should not be auto-allocated. + request_options (google.cloud.datastore_v1.types.RequestOptions): + Optional. The options for this request. """ project_id: str = proto.Field( @@ -737,6 +794,11 @@ class ReserveIdsRequest(proto.Message): number=1, message=entity.Key, ) + request_options: "RequestOptions" = proto.Field( + proto.MESSAGE, + number=10, + message="RequestOptions", + ) class ReserveIdsResponse(proto.Message): @@ -1318,4 +1380,24 @@ class ReadOnly(proto.Message): ) +class RequestOptions(proto.Message): + r"""Options for a request. + + Attributes: + request_tags (MutableSequence[str]): + Optional. The request tags for the request. + The tags are processed as follows: + + - Truncated to 510 characters. + - Filtered out if empty. + - Deduplicated. + - Limited to 50 tags. + """ + + request_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-datastore/google/cloud/datastore_v1/types/query.py b/packages/google-cloud-datastore/google/cloud/datastore_v1/types/query.py index 524d66bfb688..386f5b076f69 100644 --- a/packages/google-cloud-datastore/google/cloud/datastore_v1/types/query.py +++ b/packages/google-cloud-datastore/google/cloud/datastore_v1/types/query.py @@ -772,8 +772,9 @@ class FindNearest(proto.Message): when the vectors are more similar, the comparison is inverted. - For EUCLIDEAN, COSINE: WHERE distance <= distance_threshold - For DOT_PRODUCT: WHERE distance >= distance_threshold + - For EUCLIDEAN, COSINE: WHERE distance <= + distance_threshold + - For DOT_PRODUCT: WHERE distance >= distance_threshold """ class DistanceMeasure(proto.Enum): diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/audio_config.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/audio_config.py index 0e455b9dc087..5b95bad6b4b1 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/audio_config.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/audio_config.py @@ -441,6 +441,10 @@ class InputAudioConfig(proto.Message): only for streaming methods. Note: When specified, InputAudioConfig.single_utterance takes precedence over StreamingDetectIntentRequest.single_utterance. + enable_voice_activity_events (bool): + Optional. If ``true``, responses with voice activity speech + events will be returned as they are detected. Note: This + setting is relevant only for streaming methods. disable_no_speech_recognized_event (bool): Only used in [Participants.AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent] @@ -501,6 +505,10 @@ class InputAudioConfig(proto.Message): proto.BOOL, number=8, ) + enable_voice_activity_events: bool = proto.Field( + proto.BOOL, + number=27, + ) disable_no_speech_recognized_event: bool = proto.Field( proto.BOOL, number=14, diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation.py index 5be10d3de70f..24ca4bf16d12 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation.py @@ -1587,6 +1587,9 @@ class SearchKnowledgeDebugInfo(proto.Message): search knowledge. service_latency (google.cloud.dialogflow_v2.types.ServiceLatency): The latency of the service. + ces_debug_info (google.protobuf.struct_pb2.Struct): + Optional. Debug info from the Customer + Engagement Suite (CES) execution. """ class SearchKnowledgeBehavior(proto.Message): @@ -1639,6 +1642,11 @@ class SearchKnowledgeBehavior(proto.Message): number=4, message=participant.ServiceLatency, ) + ces_debug_info: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=5, + message=struct_pb2.Struct, + ) class SearchKnowledgeResponse(proto.Message): diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/session.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/session.py index eb576456d28c..938cdaac6c5f 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/session.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/session.py @@ -1020,6 +1020,8 @@ class MessageType(proto.Enum): TRANSCRIPT (1): Message contains a (possibly partial) transcript. + DTMF_DIGITS (3): + Message contains DTMF digits. END_OF_SINGLE_UTTERANCE (2): This event indicates that the server has detected the end of the user's speech utterance and expects no additional @@ -1031,11 +1033,32 @@ class MessageType(proto.Enum): connection. This message is only sent if ``single_utterance`` was set to ``true``, and is not used otherwise. + PARTIAL_DTMF_DIGITS (4): + Message contains DTMF digits. Before a message with + DTMF_DIGITS is sent, a message with PARTIAL_DTMF_DIGITS may + be sent with DTMF digits collected up to the time of + sending, which represents an intermediate result. + SPEECH_ACTIVITY_BEGIN (5): + This event indicates that the server has + detected the beginning of human voice activity + in the stream. This event can be returned + multiple times if speech starts and stops + repeatedly throughout the stream. + SPEECH_ACTIVITY_END (6): + This event indicates that the server has + detected the end of human voice activity in the + stream. This event can be returned multiple + times if speech starts and stops repeatedly + throughout the stream. """ MESSAGE_TYPE_UNSPECIFIED = 0 TRANSCRIPT = 1 + DTMF_DIGITS = 3 END_OF_SINGLE_UTTERANCE = 2 + PARTIAL_DTMF_DIGITS = 4 + SPEECH_ACTIVITY_BEGIN = 5 + SPEECH_ACTIVITY_END = 6 message_type: MessageType = proto.Field( proto.ENUM, diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/tool_call.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/tool_call.py index 9f0636eb61e7..a929866a0bcf 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/tool_call.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/tool_call.py @@ -189,18 +189,18 @@ class ToolCallResult(proto.Message): Optional. The name of the tool's action associated with this call. error (google.cloud.dialogflow_v2.types.ToolCallResult.Error): - The tool call's error. + Optional. The tool call's error. This field is a member of `oneof`_ ``result``. raw_content (bytes): - Only populated if the response content is not - utf-8 encoded. (by definition byte fields are - base64 encoded). + Optional. Only populated if the response + content is not utf-8 encoded. (by definition + byte fields are base64 encoded). This field is a member of `oneof`_ ``result``. content (str): - Only populated if the response content is - utf-8 encoded. + Optional. Only populated if the response + content is utf-8 encoded. This field is a member of `oneof`_ ``result``. create_time (google.protobuf.timestamp_pb2.Timestamp): diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/audio_config.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/audio_config.py index 84d54b30c9d1..1a19964d3ae1 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/audio_config.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/audio_config.py @@ -504,6 +504,10 @@ class InputAudioConfig(proto.Message): only for streaming methods. Note: When specified, InputAudioConfig.single_utterance takes precedence over StreamingDetectIntentRequest.single_utterance. + enable_voice_activity_events (bool): + Optional. If ``true``, responses with voice activity speech + events will be returned as they are detected. Note: This + setting is relevant only for streaming methods. disable_no_speech_recognized_event (bool): Only used in [Participants.AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] @@ -571,6 +575,10 @@ class InputAudioConfig(proto.Message): proto.BOOL, number=8, ) + enable_voice_activity_events: bool = proto.Field( + proto.BOOL, + number=27, + ) disable_no_speech_recognized_event: bool = proto.Field( proto.BOOL, number=14, diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/conversation.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/conversation.py index e55fbb023042..bd8620cd4c6b 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/conversation.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/conversation.py @@ -1658,6 +1658,9 @@ class SearchKnowledgeDebugInfo(proto.Message): search knowledge. service_latency (google.cloud.dialogflow_v2beta1.types.ServiceLatency): The latency of the service. + ces_debug_info (google.protobuf.struct_pb2.Struct): + Optional. Debug info from the Customer + Engagement Suite (CES) execution. """ class SearchKnowledgeBehavior(proto.Message): @@ -1710,6 +1713,11 @@ class SearchKnowledgeBehavior(proto.Message): number=4, message=participant.ServiceLatency, ) + ces_debug_info: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=5, + message=struct_pb2.Struct, + ) class SearchKnowledgeResponse(proto.Message): diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/session.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/session.py index f70d908473bd..694d2e3f5d54 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/session.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/session.py @@ -1232,6 +1232,18 @@ class MessageType(proto.Enum): DTMF_DIGITS is sent, a message with PARTIAL_DTMF_DIGITS may be sent with DTMF digits collected up to the time of sending, which represents an intermediate result. + SPEECH_ACTIVITY_BEGIN (5): + This event indicates that the server has + detected the beginning of human voice activity + in the stream. This event can be returned + multiple times if speech starts and stops + repeatedly throughout the stream. + SPEECH_ACTIVITY_END (6): + This event indicates that the server has + detected the end of human voice activity in the + stream. This event can be returned multiple + times if speech starts and stops repeatedly + throughout the stream. """ MESSAGE_TYPE_UNSPECIFIED = 0 @@ -1239,6 +1251,8 @@ class MessageType(proto.Enum): END_OF_SINGLE_UTTERANCE = 2 DTMF_DIGITS = 3 PARTIAL_DTMF_DIGITS = 4 + SPEECH_ACTIVITY_BEGIN = 5 + SPEECH_ACTIVITY_END = 6 message_type: MessageType = proto.Field( proto.ENUM, diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/tool_call.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/tool_call.py index a9b9b68a64d4..4afe58bb6e8c 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/tool_call.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/tool_call.py @@ -189,18 +189,18 @@ class ToolCallResult(proto.Message): Optional. The name of the tool's action associated with this call. error (google.cloud.dialogflow_v2beta1.types.ToolCallResult.Error): - The tool call's error. + Optional. The tool call's error. This field is a member of `oneof`_ ``result``. raw_content (bytes): - Only populated if the response content is not - utf-8 encoded. (by definition byte fields are - base64 encoded). + Optional. Only populated if the response + content is not utf-8 encoded. (by definition + byte fields are base64 encoded). This field is a member of `oneof`_ ``result``. content (str): - Only populated if the response content is - utf-8 encoded. + Optional. Only populated if the response + content is utf-8 encoded. This field is a member of `oneof`_ ``result``. create_time (google.protobuf.timestamp_pb2.Timestamp): diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/async_client.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/async_client.py index 5c32ca3bee6d..4812bbed46c5 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/async_client.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/async_client.py @@ -2596,7 +2596,7 @@ async def sample_create_import_job(): # Initialize request argument(s) import_job = kms_v1.ImportJob() - import_job.import_method = "RSA_OAEP_4096_SHA256" + import_job.import_method = "HPKE_KEM_XWING_HKDF_SHA256_AES_256_GCM" import_job.protection_level = "HSM_SINGLE_TENANT" request = kms_v1.CreateImportJobRequest( diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py index 61224eacb11a..aff969e7a712 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py @@ -3083,7 +3083,7 @@ def sample_create_import_job(): # Initialize request argument(s) import_job = kms_v1.ImportJob() - import_job.import_method = "RSA_OAEP_4096_SHA256" + import_job.import_method = "HPKE_KEM_XWING_HKDF_SHA256_AES_256_GCM" import_job.protection_level = "HSM_SINGLE_TENANT" request = kms_v1.CreateImportJobRequest( diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/types/resources.py b/packages/google-cloud-kms/google/cloud/kms_v1/types/resources.py index cf95ec1f79ff..66a514691b0b 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/types/resources.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/types/resources.py @@ -1351,6 +1351,12 @@ class ImportJob(proto.Message): prior to import. Only returned if [state][google.cloud.kms.v1.ImportJob.state] is [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE]. + public_key_format (google.cloud.kms_v1.types.PublicKey.PublicKeyFormat): + Output only. Specifies the + [WrappingPublicKey][google.cloud.kms.v1.ImportJob.WrappingPublicKey] + format provided by the customer in the + [KeyManagementService.GetImportJob][google.cloud.kms.v1.KeyManagementService.GetImportJob] + request. attestation (google.cloud.kms_v1.types.KeyOperationAttestation): Output only. Statement that was generated and signed by the key creator (for example, an HSM) at key creation time. Use @@ -1422,6 +1428,36 @@ class ImportMethod(proto.Enum): Due to technical limitations of RSA wrapping, this method cannot be used to wrap RSA keys for import. + HPKE_KEM_ML_KEM_768_HKDF_SHA256_AES_256_GCM (8): + Represents the Hybrid Public Key Encryption (HPKE) Scheme + originally defined in `RFC + 9180 `__. It + involves wrapping the raw key with an ephemeral AES key, + derived with HKDF-SHA256 from an encryption context, that + is, in turn obtained from the receiver’s public key with the + help of the ML-KEM-768 KEM. For more details, see the + `ML-KEM HPKE + standard `__. + HPKE_KEM_ML_KEM_1024_HKDF_SHA256_AES_256_GCM (9): + Represents the Hybrid Public Key Encryption (HPKE) Scheme + originally defined in `RFC + 9180 `__. It + involves wrapping the raw key with an ephemeral AES key, + derived with HKDF-SHA256 from an encryption context, that + is, in turn obtained from the receiver’s public key with the + help of the ML-KEM-1024 KEM. For more details, see the + `ML-KEM HPKE + standard `__. + HPKE_KEM_XWING_HKDF_SHA256_AES_256_GCM (10): + Represents the Hybrid Public Key Encryption (HPKE) Scheme + originally defined in `RFC + 9180 `__. It + involves wrapping the raw key with an ephemeral AES key, + derived with HKDF-SHA256 from an encryption context, that + is, in turn obtained from the receiver’s public key with the + help of the X-Wing hybrid KEM. For more details, see the + `X-Wing + standard `__. """ IMPORT_METHOD_UNSPECIFIED = 0 @@ -1431,6 +1467,9 @@ class ImportMethod(proto.Enum): RSA_OAEP_4096_SHA256_AES_256 = 4 RSA_OAEP_3072_SHA256 = 5 RSA_OAEP_4096_SHA256 = 6 + HPKE_KEM_ML_KEM_768_HKDF_SHA256_AES_256_GCM = 8 + HPKE_KEM_ML_KEM_1024_HKDF_SHA256_AES_256_GCM = 9 + HPKE_KEM_XWING_HKDF_SHA256_AES_256_GCM = 10 class ImportJobState(proto.Enum): r"""The state of the [ImportJob][google.cloud.kms.v1.ImportJob], @@ -1473,13 +1512,32 @@ class WrappingPublicKey(proto.Message): sections for `General Considerations `__ and [Textual Encoding of Subject Public Key Info] - (https://tools.ietf.org/html/rfc7468#section-13). + (https://tools.ietf.org/html/rfc7468#section-13). This field + gets populated by default for RSA-based import methods, if + no public_key_format is specified in the request. If you + want to retrieve the wrapping key of an + [ImportJob][google.cloud.kms.v1.ImportJob] in some other + format, use + [KeyManagementService.GetImportJob][google.cloud.kms.v1.KeyManagementService.GetImportJob] + and set the public_key_format to the desired public key + format. + data (bytes): + Output only. Contains the public key, formatted according to + the + [PublicKey.PublicKeyFormat][google.cloud.kms.v1.PublicKey.PublicKeyFormat] + specified in the + [KeyManagementService.GetImportJob][google.cloud.kms.v1.KeyManagementService.GetImportJob] + request. """ pem: str = proto.Field( proto.STRING, number=1, ) + data: bytes = proto.Field( + proto.BYTES, + number=2, + ) name: str = proto.Field( proto.STRING, @@ -1525,6 +1583,11 @@ class WrappingPublicKey(proto.Message): number=7, message=WrappingPublicKey, ) + public_key_format: "PublicKey.PublicKeyFormat" = proto.Field( + proto.ENUM, + number=12, + enum="PublicKey.PublicKeyFormat", + ) attestation: "KeyOperationAttestation" = proto.Field( proto.MESSAGE, number=8, diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/types/service.py b/packages/google-cloud-kms/google/cloud/kms_v1/types/service.py index 9665096ac2ac..3c513b8ca9c9 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/types/service.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/types/service.py @@ -644,12 +644,29 @@ class GetImportJobRequest(proto.Message): name (str): Required. The [name][google.cloud.kms.v1.ImportJob.name] of the [ImportJob][google.cloud.kms.v1.ImportJob] to get. + public_key_format (google.cloud.kms_v1.types.PublicKey.PublicKeyFormat): + Optional. Specifies the [WrappingPublicKey][] format. If not + specified: + + - For RSA-based import methods, the wrapping key will be + returned in PEM format + - For pure ML-KEM-based import methods, the wrapping key + will be returned in the raw bytes format specified in + FIPS-203 + - For X-Wing-based import methods, the wrapping key will be + returned in the raw bytes format specified in + https://datatracker.ietf.org/doc/draft-connolly-cfrg-xwing-kem. """ name: str = proto.Field( proto.STRING, number=1, ) + public_key_format: resources.PublicKey.PublicKeyFormat = proto.Field( + proto.ENUM, + number=2, + enum=resources.PublicKey.PublicKeyFormat, + ) class GetRetiredResourceRequest(proto.Message): diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_async.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_async.py index 0ddf0ecaabcf..132d33126be0 100644 --- a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_async.py +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_async.py @@ -40,7 +40,7 @@ async def sample_create_import_job(): # Initialize request argument(s) import_job = kms_v1.ImportJob() - import_job.import_method = "RSA_OAEP_4096_SHA256" + import_job.import_method = "HPKE_KEM_XWING_HKDF_SHA256_AES_256_GCM" import_job.protection_level = "HSM_SINGLE_TENANT" request = kms_v1.CreateImportJobRequest( diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_sync.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_sync.py index 6c3d4456d36a..b333cda2f79e 100644 --- a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_sync.py +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_sync.py @@ -40,7 +40,7 @@ def sample_create_import_job(): # Initialize request argument(s) import_job = kms_v1.ImportJob() - import_job.import_method = "RSA_OAEP_4096_SHA256" + import_job.import_method = "HPKE_KEM_XWING_HKDF_SHA256_AES_256_GCM" import_job.protection_level = "HSM_SINGLE_TENANT" request = kms_v1.CreateImportJobRequest( diff --git a/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py b/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py index 4d20ac04502b..b8e4c4960bab 100644 --- a/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py +++ b/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py @@ -5496,6 +5496,7 @@ def test_get_import_job(request_type, transport: str = "grpc"): import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, protection_level=resources.ProtectionLevel.SOFTWARE, state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + public_key_format=resources.PublicKey.PublicKeyFormat.PEM, crypto_key_backend="crypto_key_backend_value", ) response = client.get_import_job(request) @@ -5515,6 +5516,7 @@ def test_get_import_job(request_type, transport: str = "grpc"): ) assert response.protection_level == resources.ProtectionLevel.SOFTWARE assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + assert response.public_key_format == resources.PublicKey.PublicKeyFormat.PEM assert response.crypto_key_backend == "crypto_key_backend_value" @@ -5651,6 +5653,7 @@ async def test_get_import_job_async(request_type, transport: str = "grpc_asyncio import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, protection_level=resources.ProtectionLevel.SOFTWARE, state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + public_key_format=resources.PublicKey.PublicKeyFormat.PEM, crypto_key_backend="crypto_key_backend_value", ) ) @@ -5671,6 +5674,7 @@ async def test_get_import_job_async(request_type, transport: str = "grpc_asyncio ) assert response.protection_level == resources.ProtectionLevel.SOFTWARE assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + assert response.public_key_format == resources.PublicKey.PublicKeyFormat.PEM assert response.crypto_key_backend == "crypto_key_backend_value" @@ -8315,6 +8319,7 @@ def test_create_import_job(request_type, transport: str = "grpc"): import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, protection_level=resources.ProtectionLevel.SOFTWARE, state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + public_key_format=resources.PublicKey.PublicKeyFormat.PEM, crypto_key_backend="crypto_key_backend_value", ) response = client.create_import_job(request) @@ -8334,6 +8339,7 @@ def test_create_import_job(request_type, transport: str = "grpc"): ) assert response.protection_level == resources.ProtectionLevel.SOFTWARE assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + assert response.public_key_format == resources.PublicKey.PublicKeyFormat.PEM assert response.crypto_key_backend == "crypto_key_backend_value" @@ -8478,6 +8484,7 @@ async def test_create_import_job_async(request_type, transport: str = "grpc_asyn import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, protection_level=resources.ProtectionLevel.SOFTWARE, state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + public_key_format=resources.PublicKey.PublicKeyFormat.PEM, crypto_key_backend="crypto_key_backend_value", ) ) @@ -8498,6 +8505,7 @@ async def test_create_import_job_async(request_type, transport: str = "grpc_asyn ) assert response.protection_level == resources.ProtectionLevel.SOFTWARE assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + assert response.public_key_format == resources.PublicKey.PublicKeyFormat.PEM assert response.crypto_key_backend == "crypto_key_backend_value" @@ -15929,6 +15937,8 @@ def test_get_import_job_rest_required_fields(request_type=service.GetImportJobRe unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).get_import_job._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("public_key_format",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -15983,7 +15993,7 @@ def test_get_import_job_rest_unset_required_fields(): ) unset_fields = transport.get_import_job._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + assert set(unset_fields) == (set(("publicKeyFormat",)) & set(("name",))) def test_get_import_job_rest_flattened(): @@ -21285,6 +21295,7 @@ async def test_get_import_job_empty_call_grpc_asyncio(): import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, protection_level=resources.ProtectionLevel.SOFTWARE, state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + public_key_format=resources.PublicKey.PublicKeyFormat.PEM, crypto_key_backend="crypto_key_backend_value", ) ) @@ -21528,6 +21539,7 @@ async def test_create_import_job_empty_call_grpc_asyncio(): import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, protection_level=resources.ProtectionLevel.SOFTWARE, state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + public_key_format=resources.PublicKey.PublicKeyFormat.PEM, crypto_key_backend="crypto_key_backend_value", ) ) @@ -23311,6 +23323,7 @@ def test_get_import_job_rest_call_success(request_type): import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, protection_level=resources.ProtectionLevel.SOFTWARE, state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + public_key_format=resources.PublicKey.PublicKeyFormat.PEM, crypto_key_backend="crypto_key_backend_value", ) @@ -23335,6 +23348,7 @@ def test_get_import_job_rest_call_success(request_type): ) assert response.protection_level == resources.ProtectionLevel.SOFTWARE assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + assert response.public_key_format == resources.PublicKey.PublicKeyFormat.PEM assert response.crypto_key_backend == "crypto_key_backend_value" @@ -24723,7 +24737,8 @@ def test_create_import_job_rest_call_success(request_type): "expire_time": {}, "expire_event_time": {}, "state": 1, - "public_key": {"pem": "pem_value"}, + "public_key": {"pem": "pem_value", "data": b"data_blob"}, + "public_key_format": 1, "attestation": { "format": 3, "content": b"content_blob", @@ -24818,6 +24833,7 @@ def get_message_fields(field): import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, protection_level=resources.ProtectionLevel.SOFTWARE, state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + public_key_format=resources.PublicKey.PublicKeyFormat.PEM, crypto_key_backend="crypto_key_backend_value", ) @@ -24842,6 +24858,7 @@ def get_message_fields(field): ) assert response.protection_level == resources.ProtectionLevel.SOFTWARE assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + assert response.public_key_format == resources.PublicKey.PublicKeyFormat.PEM assert response.crypto_key_backend == "crypto_key_backend_value" diff --git a/packages/google-cloud-modelarmor/google/cloud/modelarmor/__init__.py b/packages/google-cloud-modelarmor/google/cloud/modelarmor/__init__.py index b41a7aadfa95..0ab5cd9168c2 100644 --- a/packages/google-cloud-modelarmor/google/cloud/modelarmor/__init__.py +++ b/packages/google-cloud-modelarmor/google/cloud/modelarmor/__init__.py @@ -43,6 +43,7 @@ MaliciousUriFilterResult, MaliciousUriFilterSettings, MessageItem, + Modality, MultiLanguageDetectionMetadata, PiAndJailbreakFilterResult, PiAndJailbreakFilterSettings, @@ -57,12 +58,15 @@ SanitizeUserPromptResponse, SdpAdvancedConfig, SdpBasicConfig, + SdpContentLocation, SdpDeidentifyResult, SdpFilterResult, SdpFilterSettings, SdpFinding, SdpFindingLikelihood, + SdpImageFindingLocation, SdpInspectResult, + SdpRedactResult, StreamingMode, Template, UpdateFloorSettingRequest, @@ -103,11 +107,14 @@ "SanitizeUserPromptResponse", "SdpAdvancedConfig", "SdpBasicConfig", + "SdpContentLocation", "SdpDeidentifyResult", "SdpFilterResult", "SdpFilterSettings", "SdpFinding", + "SdpImageFindingLocation", "SdpInspectResult", + "SdpRedactResult", "Template", "UpdateFloorSettingRequest", "UpdateTemplateRequest", @@ -117,6 +124,7 @@ "FilterExecutionState", "FilterMatchState", "InvocationResult", + "Modality", "RaiFilterType", "SdpFindingLikelihood", "StreamingMode", diff --git a/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/__init__.py b/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/__init__.py index 89d2dcbb660f..c664e1619db4 100644 --- a/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/__init__.py +++ b/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/__init__.py @@ -45,6 +45,7 @@ MaliciousUriFilterResult, MaliciousUriFilterSettings, MessageItem, + Modality, MultiLanguageDetectionMetadata, PiAndJailbreakFilterResult, PiAndJailbreakFilterSettings, @@ -59,12 +60,15 @@ SanitizeUserPromptResponse, SdpAdvancedConfig, SdpBasicConfig, + SdpContentLocation, SdpDeidentifyResult, SdpFilterResult, SdpFilterSettings, SdpFinding, SdpFindingLikelihood, + SdpImageFindingLocation, SdpInspectResult, + SdpRedactResult, StreamingMode, Template, UpdateFloorSettingRequest, @@ -178,6 +182,7 @@ def _get_version(dependency_name): "MaliciousUriFilterResult", "MaliciousUriFilterSettings", "MessageItem", + "Modality", "ModelArmorClient", "MultiLanguageDetectionMetadata", "PiAndJailbreakFilterResult", @@ -193,12 +198,15 @@ def _get_version(dependency_name): "SanitizeUserPromptResponse", "SdpAdvancedConfig", "SdpBasicConfig", + "SdpContentLocation", "SdpDeidentifyResult", "SdpFilterResult", "SdpFilterSettings", "SdpFinding", "SdpFindingLikelihood", + "SdpImageFindingLocation", "SdpInspectResult", + "SdpRedactResult", "StreamingMode", "Template", "UpdateFloorSettingRequest", diff --git a/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/types/__init__.py b/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/types/__init__.py index 803dc9a29614..8c78342a308c 100644 --- a/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/types/__init__.py +++ b/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/types/__init__.py @@ -34,6 +34,7 @@ MaliciousUriFilterResult, MaliciousUriFilterSettings, MessageItem, + Modality, MultiLanguageDetectionMetadata, PiAndJailbreakFilterResult, PiAndJailbreakFilterSettings, @@ -48,12 +49,15 @@ SanitizeUserPromptResponse, SdpAdvancedConfig, SdpBasicConfig, + SdpContentLocation, SdpDeidentifyResult, SdpFilterResult, SdpFilterSettings, SdpFinding, SdpFindingLikelihood, + SdpImageFindingLocation, SdpInspectResult, + SdpRedactResult, StreamingMode, Template, UpdateFloorSettingRequest, @@ -92,11 +96,14 @@ "SanitizeUserPromptResponse", "SdpAdvancedConfig", "SdpBasicConfig", + "SdpContentLocation", "SdpDeidentifyResult", "SdpFilterResult", "SdpFilterSettings", "SdpFinding", + "SdpImageFindingLocation", "SdpInspectResult", + "SdpRedactResult", "Template", "UpdateFloorSettingRequest", "UpdateTemplateRequest", @@ -106,6 +113,7 @@ "FilterExecutionState", "FilterMatchState", "InvocationResult", + "Modality", "RaiFilterType", "SdpFindingLikelihood", "StreamingMode", diff --git a/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/types/service.py b/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/types/service.py index 7187ce979be8..a3da8c3975bb 100644 --- a/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/types/service.py +++ b/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/types/service.py @@ -31,6 +31,7 @@ "SdpFindingLikelihood", "InvocationResult", "StreamingMode", + "Modality", "Template", "FloorSetting", "AiPlatformFloorSetting", @@ -62,7 +63,10 @@ "DataItem", "ByteDataItem", "SdpDeidentifyResult", + "SdpImageFindingLocation", + "SdpContentLocation", "SdpFinding", + "SdpRedactResult", "PiAndJailbreakFilterResult", "MaliciousUriFilterResult", "VirusScanFilterResult", @@ -223,6 +227,31 @@ class StreamingMode(proto.Enum): STREAMING_MODE_REALTIME = 2 +class Modality(proto.Enum): + r"""This enum is used in the TemplateMetadata message to indicate + the modality supported for sanitize API calls. + + Values: + MODALITY_UNSPECIFIED (0): + Unspecified modality. If specified, all + modalities will be sanitized. + MODALITY_TEXT (1): + Represents text modality. If specified, it + will sanitize text fields, and text extracted + from rich text files (like PDFs, DOCs) and plain + text files (like TXT). + MODALITY_IMAGE (2): + Represents image modality. If specified, it + will sanitize image files. The visual content + and the text content in the image will be + sanitized depending on the filter configuration. + """ + + MODALITY_UNSPECIFIED = 0 + MODALITY_TEXT = 1 + MODALITY_IMAGE = 2 + + class Template(proto.Message): r"""Message describing Template resource @@ -277,6 +306,9 @@ class TemplateMetadata(proto.Message): multi_language_detection (google.cloud.modelarmor_v1.types.Template.TemplateMetadata.MultiLanguageDetection): Optional. Metadata for multi language detection. + modalities (MutableSequence[google.cloud.modelarmor_v1.types.Modality]): + Optional. Specifies the modalities to scan. + If empty, only text modality will be scanned. """ class EnforcementType(proto.Enum): @@ -352,6 +384,11 @@ class MultiLanguageDetection(proto.Message): message="Template.TemplateMetadata.MultiLanguageDetection", ) ) + modalities: MutableSequence["Modality"] = proto.RepeatedField( + proto.ENUM, + number=11, + enum="Modality", + ) name: str = proto.Field( proto.STRING, @@ -879,7 +916,7 @@ class PiAndJailbreakFilterEnforcement(proto.Enum): ENABLED (1): Enabled DISABLED (2): - Enabled + Disabled """ PI_AND_JAILBREAK_FILTER_ENFORCEMENT_UNSPECIFIED = 0 @@ -1427,7 +1464,7 @@ class RaiFilterResult(proto.Message): rai_filter_type_results (MutableMapping[str, google.cloud.modelarmor_v1.types.RaiFilterResult.RaiFilterTypeResult]): The map of RAI filter results where key is RAI filter type - either of "sexually_explicit", "hate_speech", "harassment", - "dangerous". + "dangerous", "violence", "sexually_suggestive". """ class RaiFilterTypeResult(proto.Message): @@ -1503,6 +1540,12 @@ class SdpFilterResult(proto.Message): Sensitive Data Protection Deidentification result if deidentification is performed. + This field is a member of `oneof`_ ``result``. + redact_result (google.cloud.modelarmor_v1.types.SdpRedactResult): + Sensitive Data Protection Redaction result if + redaction is performed. This is primarily used + for image redaction. + This field is a member of `oneof`_ ``result``. """ @@ -1518,6 +1561,12 @@ class SdpFilterResult(proto.Message): oneof="result", message="SdpDeidentifyResult", ) + redact_result: "SdpRedactResult" = proto.Field( + proto.MESSAGE, + number=3, + oneof="result", + message="SdpRedactResult", + ) class SdpInspectResult(proto.Message): @@ -1548,6 +1597,9 @@ class SdpInspectResult(proto.Message): input items were too large, or because the server reached the maximum amount of resources allowed for a single API call. + extracted_image_text (str): + Contains text extracted from the image, if + applicable. """ execution_state: "FilterExecutionState" = proto.Field( @@ -1574,6 +1626,10 @@ class SdpInspectResult(proto.Message): proto.BOOL, number=5, ) + extracted_image_text: str = proto.Field( + proto.STRING, + number=6, + ) class DataItem(proto.Message): @@ -1640,6 +1696,8 @@ class ByteItemType(proto.Enum): TXT CSV (7): CSV + IMAGE (8): + IMAGE """ BYTE_ITEM_TYPE_UNSPECIFIED = 0 @@ -1650,6 +1708,7 @@ class ByteItemType(proto.Enum): POWERPOINT_DOCUMENT = 5 TXT = 6 CSV = 7 + IMAGE = 8 byte_data_type: ByteItemType = proto.Field( proto.ENUM, @@ -1720,6 +1779,89 @@ class SdpDeidentifyResult(proto.Message): ) +class SdpImageFindingLocation(proto.Message): + r"""Location of the finding within an image. + + Attributes: + bounding_boxes (MutableSequence[google.cloud.modelarmor_v1.types.SdpImageFindingLocation.SdpBoundingBox]): + Bounding boxes locating the pixels within the + image containing the finding. + """ + + class SdpBoundingBox(proto.Message): + r"""Bounding box encompassing a finding within an image. + + Attributes: + top (int): + Top coordinate of the bounding box. (0,0) is + upper left. + left (int): + Left coordinate of the bounding box. (0,0) is + upper left. + width (int): + Width of the bounding box in pixels. + height (int): + Height of the bounding box in pixels. + """ + + top: int = proto.Field( + proto.INT32, + number=1, + ) + left: int = proto.Field( + proto.INT32, + number=2, + ) + width: int = proto.Field( + proto.INT32, + number=3, + ) + height: int = proto.Field( + proto.INT32, + number=4, + ) + + bounding_boxes: MutableSequence[SdpBoundingBox] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=SdpBoundingBox, + ) + + +class SdpContentLocation(proto.Message): + r"""Precise location of the finding within a document, record, + image, or metadata container. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + image_finding_location (google.cloud.modelarmor_v1.types.SdpImageFindingLocation): + Location within an image's pixels. + + This field is a member of `oneof`_ ``location``. + container_name (str): + Name of the container where the finding is + located. The top level name is the source file + name or table name. + + Nested names could be absent if the embedded + object has no string identifier (for example, an + image contained within a document). + """ + + image_finding_location: "SdpImageFindingLocation" = proto.Field( + proto.MESSAGE, + number=2, + oneof="location", + message="SdpImageFindingLocation", + ) + container_name: str = proto.Field( + proto.STRING, + number=1, + ) + + class SdpFinding(proto.Message): r"""Finding corresponding to Sensitive Data Protection filter. @@ -1744,11 +1886,23 @@ class SdpFindingLocation(proto.Message): containing element. Note that when the content is not textual, this references the UTF-8 encoded textual representation of the content. + Note: Omitted if content is an image. codepoint_range (google.cloud.modelarmor_v1.types.RangeInfo): Unicode character offsets delimiting the finding. These are relative to the finding's containing element. Provided when the content is text. + Note: Omitted if content is an image. + content_locations (MutableSequence[google.cloud.modelarmor_v1.types.SdpContentLocation]): + List of nested objects pointing to the precise location of + the finding within an image, file or record. + + For example, a single finding might be detected in two + separate bounding boxes within an image (e.g., if it wraps + across a line or is partially obscured). In such cases, + content_locations would contain two SdpContentLocation + entries, each with an image_finding_location pointing to a + different bounding box. """ byte_range: "RangeInfo" = proto.Field( @@ -1761,6 +1915,11 @@ class SdpFindingLocation(proto.Message): number=2, message="RangeInfo", ) + content_locations: MutableSequence["SdpContentLocation"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="SdpContentLocation", + ) info_type: str = proto.Field( proto.STRING, @@ -1778,6 +1937,64 @@ class SdpFindingLocation(proto.Message): ) +class SdpRedactResult(proto.Message): + r"""Sensitive Data Protection Redaction Result. + + Attributes: + execution_state (google.cloud.modelarmor_v1.types.FilterExecutionState): + Output only. Reports whether Sensitive Data + Protection redaction was successfully executed + or not. + message_items (MutableSequence[google.cloud.modelarmor_v1.types.MessageItem]): + Output only. Optional messages corresponding + to the result. A message can provide warnings or + error details. For example, if execution state + is skipped then this field provides related + reason/explanation. + match_state (google.cloud.modelarmor_v1.types.FilterMatchState): + Output only. Match state for Sensitive Data Protection + Redaction. Value is MATCH_FOUND if content is redacted. + redacted_image (bytes): + Output only. The redacted image. The type + will be the same as the original image. + findings (MutableSequence[google.cloud.modelarmor_v1.types.SdpFinding]): + Output only. The findings. This field is populated in the + response only when include_findings in the SDP template is + set to true. + extracted_image_text (str): + The extracted text from the image. + """ + + execution_state: "FilterExecutionState" = proto.Field( + proto.ENUM, + number=1, + enum="FilterExecutionState", + ) + message_items: MutableSequence["MessageItem"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="MessageItem", + ) + match_state: "FilterMatchState" = proto.Field( + proto.ENUM, + number=3, + enum="FilterMatchState", + ) + redacted_image: bytes = proto.Field( + proto.BYTES, + number=4, + ) + findings: MutableSequence["SdpFinding"] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="SdpFinding", + ) + extracted_image_text: str = proto.Field( + proto.STRING, + number=6, + ) + + class PiAndJailbreakFilterResult(proto.Message): r"""Prompt injection and Jailbreak Filter Result. diff --git a/packages/google-cloud-modelarmor/tests/unit/gapic/modelarmor_v1/test_model_armor.py b/packages/google-cloud-modelarmor/tests/unit/gapic/modelarmor_v1/test_model_armor.py index 871aa451e671..6d13215c1602 100644 --- a/packages/google-cloud-modelarmor/tests/unit/gapic/modelarmor_v1/test_model_armor.py +++ b/packages/google-cloud-modelarmor/tests/unit/gapic/modelarmor_v1/test_model_armor.py @@ -7239,6 +7239,7 @@ def test_create_template_rest_call_success(request_type): "log_sanitize_operations": True, "enforcement_type": 1, "multi_language_detection": {"enable_multi_language_detection": True}, + "modalities": [1], }, } # The version of a generated dependency at test runtime may differ from the version used during generation. @@ -7470,6 +7471,7 @@ def test_update_template_rest_call_success(request_type): "log_sanitize_operations": True, "enforcement_type": 1, "multi_language_detection": {"enable_multi_language_detection": True}, + "modalities": [1], }, } # The version of a generated dependency at test runtime may differ from the version used during generation. diff --git a/packages/google-cloud-network-security/google/cloud/network_security_v1/types/security_profile_group.py b/packages/google-cloud-network-security/google/cloud/network_security_v1/types/security_profile_group.py index 80ba73f9c264..22f97f6d49f3 100644 --- a/packages/google-cloud-network-security/google/cloud/network_security_v1/types/security_profile_group.py +++ b/packages/google-cloud-network-security/google/cloud/network_security_v1/types/security_profile_group.py @@ -59,9 +59,8 @@ class SecurityProfileGroup(proto.Message): ensure the client has an up-to-date value before proceeding. data_path_id (int): - Output only. Identifier used by the - data-path. Unique within \{container, - location\}. + Output only. Identifier used by the data-path. Unique within + ``{container, location}``. labels (MutableMapping[str, str]): Optional. Labels as key value pairs. threat_prevention_profile (str): diff --git a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/types/common.py b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/types/common.py index b9f230f9c1fb..e277bda0c277 100644 --- a/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/types/common.py +++ b/packages/google-cloud-saasplatform-saasservicemgmt/google/cloud/saasplatform_saasservicemgmt_v1beta1/types/common.py @@ -210,10 +210,10 @@ class Type(proto.Enum): Condition type is operationError. True when the last unit operation fails with a non-ignorable error. - TYPE_APP_CREATED_OR_ALREADY_EXISTS (5): + TYPE_APP_CREATED_OR_ALREADY_EXISTS (6): Indicates if AppHub app has been created or if Apphub app has already existed. - TYPE_APP_COMPONENTS_REGISTERED (6): + TYPE_APP_COMPONENTS_REGISTERED (7): Indicates if services and workloads have been registered with AppHub. """ @@ -223,8 +223,8 @@ class Type(proto.Enum): TYPE_UPDATING = 2 TYPE_PROVISIONED = 3 TYPE_OPERATION_ERROR = 4 - TYPE_APP_CREATED_OR_ALREADY_EXISTS = 5 - TYPE_APP_COMPONENTS_REGISTERED = 6 + TYPE_APP_CREATED_OR_ALREADY_EXISTS = 6 + TYPE_APP_COMPONENTS_REGISTERED = 7 status: Status = proto.Field( proto.ENUM, diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/async_client.py b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/async_client.py index 3af58b35d185..8b40cea30079 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/async_client.py +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/async_client.py @@ -103,6 +103,12 @@ class SecureSourceManagerAsyncClient: ) hook_path = staticmethod(SecureSourceManagerClient.hook_path) parse_hook_path = staticmethod(SecureSourceManagerClient.parse_hook_path) + inspect_template_path = staticmethod( + SecureSourceManagerClient.inspect_template_path + ) + parse_inspect_template_path = staticmethod( + SecureSourceManagerClient.parse_inspect_template_path + ) instance_path = staticmethod(SecureSourceManagerClient.instance_path) parse_instance_path = staticmethod(SecureSourceManagerClient.parse_instance_path) issue_path = staticmethod(SecureSourceManagerClient.issue_path) @@ -125,6 +131,10 @@ class SecureSourceManagerAsyncClient: parse_repository_path = staticmethod( SecureSourceManagerClient.parse_repository_path ) + service_account_path = staticmethod(SecureSourceManagerClient.service_account_path) + parse_service_account_path = staticmethod( + SecureSourceManagerClient.parse_service_account_path + ) service_attachment_path = staticmethod( SecureSourceManagerClient.service_attachment_path ) diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/client.py b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/client.py index 8db9de78a079..9ac9ddab31e4 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/client.py +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/services/secure_source_manager/client.py @@ -338,6 +338,28 @@ def parse_hook_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def inspect_template_path( + project: str, + location: str, + inspect_template: str, + ) -> str: + """Returns a fully-qualified inspect_template string.""" + return "projects/{project}/locations/{location}/inspectTemplates/{inspect_template}".format( + project=project, + location=location, + inspect_template=inspect_template, + ) + + @staticmethod + def parse_inspect_template_path(path: str) -> Dict[str, str]: + """Parses a inspect_template path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/inspectTemplates/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def instance_path( project: str, @@ -484,6 +506,26 @@ def parse_repository_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def service_account_path( + project: str, + service_account: str, + ) -> str: + """Returns a fully-qualified service_account string.""" + return "projects/{project}/serviceAccounts/{service_account}".format( + project=project, + service_account=service_account, + ) + + @staticmethod + def parse_service_account_path(path: str) -> Dict[str, str]: + """Parses a service_account path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def service_attachment_path( project: str, diff --git a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/types/secure_source_manager.py b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/types/secure_source_manager.py index 4e40b647d2db..a12ad8333565 100644 --- a/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/types/secure_source_manager.py +++ b/packages/google-cloud-securesourcemanager/google/cloud/securesourcemanager_v1/types/secure_source_manager.py @@ -425,6 +425,12 @@ class Repository(proto.Message): initial_config (google.cloud.securesourcemanager_v1.types.Repository.InitialConfig): Input only. Initial configurations for the repository. + service_account (str): + Optional. Repository level service account + (BYOSA). + scan_config (google.cloud.securesourcemanager_v1.types.Repository.ScanConfig): + Optional. Provides configuration for + scanning. """ class URIs(proto.Message): @@ -684,6 +690,41 @@ class InitialConfig(proto.Message): number=4, ) + class ScanConfig(proto.Message): + r"""Configuration for scanning. + + Attributes: + secret_scan_config (google.cloud.securesourcemanager_v1.types.Repository.ScanConfig.SecretScanConfig): + Optional. Configuration for secret scanning. + """ + + class SecretScanConfig(proto.Message): + r"""Configuration for secret scanning. + + Attributes: + enabled (bool): + Optional. Enables secret scanning for the + repository. + inspect_template (str): + Optional. The DLP inspect template to use for + secret scanning. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + inspect_template: str = proto.Field( + proto.STRING, + number=2, + ) + + secret_scan_config: "Repository.ScanConfig.SecretScanConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="Repository.ScanConfig.SecretScanConfig", + ) + name: str = proto.Field( proto.STRING, number=1, @@ -724,6 +765,15 @@ class InitialConfig(proto.Message): number=10, message=InitialConfig, ) + service_account: str = proto.Field( + proto.STRING, + number=11, + ) + scan_config: ScanConfig = proto.Field( + proto.MESSAGE, + number=13, + message=ScanConfig, + ) class Hook(proto.Message): diff --git a/packages/google-cloud-securesourcemanager/tests/unit/gapic/securesourcemanager_v1/test_secure_source_manager.py b/packages/google-cloud-securesourcemanager/tests/unit/gapic/securesourcemanager_v1/test_secure_source_manager.py index 3faca52052c5..3ae48789b5f2 100644 --- a/packages/google-cloud-securesourcemanager/tests/unit/gapic/securesourcemanager_v1/test_secure_source_manager.py +++ b/packages/google-cloud-securesourcemanager/tests/unit/gapic/securesourcemanager_v1/test_secure_source_manager.py @@ -3515,6 +3515,7 @@ def test_get_repository(request_type, transport: str = "grpc"): instance="instance_value", uid="uid_value", etag="etag_value", + service_account="service_account_value", ) response = client.get_repository(request) @@ -3531,6 +3532,7 @@ def test_get_repository(request_type, transport: str = "grpc"): assert response.instance == "instance_value" assert response.uid == "uid_value" assert response.etag == "etag_value" + assert response.service_account == "service_account_value" def test_get_repository_non_empty_request_with_auto_populated_field(): @@ -3667,6 +3669,7 @@ async def test_get_repository_async(request_type, transport: str = "grpc_asyncio instance="instance_value", uid="uid_value", etag="etag_value", + service_account="service_account_value", ) ) response = await client.get_repository(request) @@ -3684,6 +3687,7 @@ async def test_get_repository_async(request_type, transport: str = "grpc_asyncio assert response.instance == "instance_value" assert response.uid == "uid_value" assert response.etag == "etag_value" + assert response.service_account == "service_account_value" def test_get_repository_field_headers(): @@ -33064,6 +33068,7 @@ async def test_get_repository_empty_call_grpc_asyncio(): instance="instance_value", uid="uid_value", etag="etag_value", + service_account="service_account_value", ) ) await client.get_repository(request=None) @@ -35127,6 +35132,7 @@ def test_get_repository_rest_call_success(request_type): instance="instance_value", uid="uid_value", etag="etag_value", + service_account="service_account_value", ) # Wrap the value into a proper Response obj @@ -35148,6 +35154,7 @@ def test_get_repository_rest_call_success(request_type): assert response.instance == "instance_value" assert response.uid == "uid_value" assert response.etag == "etag_value" + assert response.service_account == "service_account_value" @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -35276,6 +35283,13 @@ def test_create_repository_rest_call_success(request_type): "license_": "license__value", "readme": "readme_value", }, + "service_account": "service_account_value", + "scan_config": { + "secret_scan_config": { + "enabled": True, + "inspect_template": "inspect_template_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 @@ -35497,6 +35511,13 @@ def test_update_repository_rest_call_success(request_type): "license_": "license__value", "readme": "readme_value", }, + "service_account": "service_account_value", + "scan_config": { + "secret_scan_config": { + "enabled": True, + "inspect_template": "inspect_template_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 @@ -44983,10 +45004,38 @@ def test_parse_hook_path(): assert expected == actual -def test_instance_path(): +def test_inspect_template_path(): project = "cuttlefish" location = "mussel" - instance = "winkle" + inspect_template = "winkle" + expected = "projects/{project}/locations/{location}/inspectTemplates/{inspect_template}".format( + project=project, + location=location, + inspect_template=inspect_template, + ) + actual = SecureSourceManagerClient.inspect_template_path( + project, location, inspect_template + ) + assert expected == actual + + +def test_parse_inspect_template_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "inspect_template": "abalone", + } + path = SecureSourceManagerClient.inspect_template_path(**expected) + + # Check that the path construction is reversible. + actual = SecureSourceManagerClient.parse_inspect_template_path(path) + assert expected == actual + + +def test_instance_path(): + project = "squid" + location = "clam" + instance = "whelk" expected = "projects/{project}/locations/{location}/instances/{instance}".format( project=project, location=location, @@ -44998,9 +45047,9 @@ def test_instance_path(): def test_parse_instance_path(): expected = { - "project": "nautilus", - "location": "scallop", - "instance": "abalone", + "project": "octopus", + "location": "oyster", + "instance": "nudibranch", } path = SecureSourceManagerClient.instance_path(**expected) @@ -45010,10 +45059,10 @@ def test_parse_instance_path(): def test_issue_path(): - project = "squid" - location = "clam" - repository = "whelk" - issue = "octopus" + project = "cuttlefish" + location = "mussel" + repository = "winkle" + issue = "nautilus" expected = "projects/{project}/locations/{location}/repositories/{repository}/issues/{issue}".format( project=project, location=location, @@ -45026,10 +45075,10 @@ def test_issue_path(): def test_parse_issue_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "repository": "cuttlefish", - "issue": "mussel", + "project": "scallop", + "location": "abalone", + "repository": "squid", + "issue": "clam", } path = SecureSourceManagerClient.issue_path(**expected) @@ -45039,11 +45088,11 @@ def test_parse_issue_path(): def test_issue_comment_path(): - project = "winkle" - location = "nautilus" - repository = "scallop" - issue = "abalone" - comment = "squid" + project = "whelk" + location = "octopus" + repository = "oyster" + issue = "nudibranch" + comment = "cuttlefish" expected = "projects/{project}/locations/{location}/repositories/{repository}/issues/{issue}/issueComments/{comment}".format( project=project, location=location, @@ -45059,11 +45108,11 @@ def test_issue_comment_path(): def test_parse_issue_comment_path(): expected = { - "project": "clam", - "location": "whelk", - "repository": "octopus", - "issue": "oyster", - "comment": "nudibranch", + "project": "mussel", + "location": "winkle", + "repository": "nautilus", + "issue": "scallop", + "comment": "abalone", } path = SecureSourceManagerClient.issue_comment_path(**expected) @@ -45073,10 +45122,10 @@ def test_parse_issue_comment_path(): def test_pull_request_path(): - project = "cuttlefish" - location = "mussel" - repository = "winkle" - pull_request = "nautilus" + project = "squid" + location = "clam" + repository = "whelk" + pull_request = "octopus" expected = "projects/{project}/locations/{location}/repositories/{repository}/pullRequests/{pull_request}".format( project=project, location=location, @@ -45091,10 +45140,10 @@ def test_pull_request_path(): def test_parse_pull_request_path(): expected = { - "project": "scallop", - "location": "abalone", - "repository": "squid", - "pull_request": "clam", + "project": "oyster", + "location": "nudibranch", + "repository": "cuttlefish", + "pull_request": "mussel", } path = SecureSourceManagerClient.pull_request_path(**expected) @@ -45104,11 +45153,11 @@ def test_parse_pull_request_path(): def test_pull_request_comment_path(): - project = "whelk" - location = "octopus" - repository = "oyster" - pull_request = "nudibranch" - comment = "cuttlefish" + project = "winkle" + location = "nautilus" + repository = "scallop" + pull_request = "abalone" + comment = "squid" expected = "projects/{project}/locations/{location}/repositories/{repository}/pullRequests/{pull_request}/pullRequestComments/{comment}".format( project=project, location=location, @@ -45124,11 +45173,11 @@ def test_pull_request_comment_path(): def test_parse_pull_request_comment_path(): expected = { - "project": "mussel", - "location": "winkle", - "repository": "nautilus", - "pull_request": "scallop", - "comment": "abalone", + "project": "clam", + "location": "whelk", + "repository": "octopus", + "pull_request": "oyster", + "comment": "nudibranch", } path = SecureSourceManagerClient.pull_request_comment_path(**expected) @@ -45138,9 +45187,9 @@ def test_parse_pull_request_comment_path(): def test_repository_path(): - project = "squid" - location = "clam" - repository = "whelk" + project = "cuttlefish" + location = "mussel" + repository = "winkle" expected = ( "projects/{project}/locations/{location}/repositories/{repository}".format( project=project, @@ -45154,9 +45203,9 @@ def test_repository_path(): def test_parse_repository_path(): expected = { - "project": "octopus", - "location": "oyster", - "repository": "nudibranch", + "project": "nautilus", + "location": "scallop", + "repository": "abalone", } path = SecureSourceManagerClient.repository_path(**expected) @@ -45165,10 +45214,33 @@ def test_parse_repository_path(): assert expected == actual +def test_service_account_path(): + project = "squid" + service_account = "clam" + expected = "projects/{project}/serviceAccounts/{service_account}".format( + project=project, + service_account=service_account, + ) + actual = SecureSourceManagerClient.service_account_path(project, service_account) + assert expected == actual + + +def test_parse_service_account_path(): + expected = { + "project": "whelk", + "service_account": "octopus", + } + path = SecureSourceManagerClient.service_account_path(**expected) + + # Check that the path construction is reversible. + actual = SecureSourceManagerClient.parse_service_account_path(path) + assert expected == actual + + def test_service_attachment_path(): - project = "cuttlefish" - region = "mussel" - service_attachment = "winkle" + project = "oyster" + region = "nudibranch" + service_attachment = "cuttlefish" expected = "projects/{project}/regions/{region}/serviceAttachments/{service_attachment}".format( project=project, region=region, @@ -45182,9 +45254,9 @@ def test_service_attachment_path(): def test_parse_service_attachment_path(): expected = { - "project": "nautilus", - "region": "scallop", - "service_attachment": "abalone", + "project": "mussel", + "region": "winkle", + "service_attachment": "nautilus", } path = SecureSourceManagerClient.service_attachment_path(**expected) @@ -45194,7 +45266,7 @@ def test_parse_service_attachment_path(): def test_common_billing_account_path(): - billing_account = "squid" + billing_account = "scallop" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -45204,7 +45276,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "clam", + "billing_account": "abalone", } path = SecureSourceManagerClient.common_billing_account_path(**expected) @@ -45214,7 +45286,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "whelk" + folder = "squid" expected = "folders/{folder}".format( folder=folder, ) @@ -45224,7 +45296,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "octopus", + "folder": "clam", } path = SecureSourceManagerClient.common_folder_path(**expected) @@ -45234,7 +45306,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "oyster" + organization = "whelk" expected = "organizations/{organization}".format( organization=organization, ) @@ -45244,7 +45316,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nudibranch", + "organization": "octopus", } path = SecureSourceManagerClient.common_organization_path(**expected) @@ -45254,7 +45326,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "cuttlefish" + project = "oyster" expected = "projects/{project}".format( project=project, ) @@ -45264,7 +45336,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "mussel", + "project": "nudibranch", } path = SecureSourceManagerClient.common_project_path(**expected) @@ -45274,8 +45346,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "winkle" - location = "nautilus" + project = "cuttlefish" + location = "mussel" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -45286,8 +45358,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "scallop", - "location": "abalone", + "project": "winkle", + "location": "nautilus", } path = SecureSourceManagerClient.common_location_path(**expected) diff --git a/packages/google-cloud-support/docs/support_v2/services_.rst b/packages/google-cloud-support/docs/support_v2/services_.rst index 0f2958ba81f1..7a318aff6614 100644 --- a/packages/google-cloud-support/docs/support_v2/services_.rst +++ b/packages/google-cloud-support/docs/support_v2/services_.rst @@ -6,3 +6,4 @@ Services for Google Cloud Support v2 API case_attachment_service case_service comment_service + support_event_subscription_service diff --git a/packages/google-cloud-support/docs/support_v2/support_event_subscription_service.rst b/packages/google-cloud-support/docs/support_v2/support_event_subscription_service.rst new file mode 100644 index 000000000000..384fa48f5964 --- /dev/null +++ b/packages/google-cloud-support/docs/support_v2/support_event_subscription_service.rst @@ -0,0 +1,10 @@ +SupportEventSubscriptionService +------------------------------------------------- + +.. automodule:: google.cloud.support_v2.services.support_event_subscription_service + :members: + :inherited-members: + +.. automodule:: google.cloud.support_v2.services.support_event_subscription_service.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-support/docs/support_v2beta/services_.rst b/packages/google-cloud-support/docs/support_v2beta/services_.rst index 850ce68ed744..5b97167df1cc 100644 --- a/packages/google-cloud-support/docs/support_v2beta/services_.rst +++ b/packages/google-cloud-support/docs/support_v2beta/services_.rst @@ -7,3 +7,4 @@ Services for Google Cloud Support v2beta API case_service comment_service feed_service + support_event_subscription_service diff --git a/packages/google-cloud-support/docs/support_v2beta/support_event_subscription_service.rst b/packages/google-cloud-support/docs/support_v2beta/support_event_subscription_service.rst new file mode 100644 index 000000000000..ff8010053d43 --- /dev/null +++ b/packages/google-cloud-support/docs/support_v2beta/support_event_subscription_service.rst @@ -0,0 +1,10 @@ +SupportEventSubscriptionService +------------------------------------------------- + +.. automodule:: google.cloud.support_v2beta.services.support_event_subscription_service + :members: + :inherited-members: + +.. automodule:: google.cloud.support_v2beta.services.support_event_subscription_service.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-support/google/cloud/support/__init__.py b/packages/google-cloud-support/google/cloud/support/__init__.py index b290187ec314..eaf91ba17d69 100644 --- a/packages/google-cloud-support/google/cloud/support/__init__.py +++ b/packages/google-cloud-support/google/cloud/support/__init__.py @@ -32,6 +32,12 @@ CommentServiceAsyncClient, ) from google.cloud.support_v2.services.comment_service.client import CommentServiceClient +from google.cloud.support_v2.services.support_event_subscription_service.async_client import ( + SupportEventSubscriptionServiceAsyncClient, +) +from google.cloud.support_v2.services.support_event_subscription_service.client import ( + SupportEventSubscriptionServiceClient, +) from google.cloud.support_v2.types.actor import Actor from google.cloud.support_v2.types.attachment import Attachment from google.cloud.support_v2.types.attachment_service import ( @@ -61,6 +67,18 @@ ListCommentsResponse, ) from google.cloud.support_v2.types.escalation import Escalation +from google.cloud.support_v2.types.support_event_subscription import ( + SupportEventSubscription, +) +from google.cloud.support_v2.types.support_event_subscription_service import ( + CreateSupportEventSubscriptionRequest, + DeleteSupportEventSubscriptionRequest, + GetSupportEventSubscriptionRequest, + ListSupportEventSubscriptionsRequest, + ListSupportEventSubscriptionsResponse, + UndeleteSupportEventSubscriptionRequest, + UpdateSupportEventSubscriptionRequest, +) __all__ = ( "CaseAttachmentServiceClient", @@ -69,6 +87,8 @@ "CaseServiceAsyncClient", "CommentServiceClient", "CommentServiceAsyncClient", + "SupportEventSubscriptionServiceClient", + "SupportEventSubscriptionServiceAsyncClient", "Actor", "Attachment", "GetAttachmentRequest", @@ -93,4 +113,12 @@ "ListCommentsRequest", "ListCommentsResponse", "Escalation", + "SupportEventSubscription", + "CreateSupportEventSubscriptionRequest", + "DeleteSupportEventSubscriptionRequest", + "GetSupportEventSubscriptionRequest", + "ListSupportEventSubscriptionsRequest", + "ListSupportEventSubscriptionsResponse", + "UndeleteSupportEventSubscriptionRequest", + "UpdateSupportEventSubscriptionRequest", ) diff --git a/packages/google-cloud-support/google/cloud/support_v2/__init__.py b/packages/google-cloud-support/google/cloud/support_v2/__init__.py index 5c1776102997..4c8d2a756542 100644 --- a/packages/google-cloud-support/google/cloud/support_v2/__init__.py +++ b/packages/google-cloud-support/google/cloud/support_v2/__init__.py @@ -29,6 +29,10 @@ ) from .services.case_service import CaseServiceAsyncClient, CaseServiceClient from .services.comment_service import CommentServiceAsyncClient, CommentServiceClient +from .services.support_event_subscription_service import ( + SupportEventSubscriptionServiceAsyncClient, + SupportEventSubscriptionServiceClient, +) from .types.actor import Actor from .types.attachment import Attachment from .types.attachment_service import ( @@ -58,6 +62,16 @@ ListCommentsResponse, ) from .types.escalation import Escalation +from .types.support_event_subscription import SupportEventSubscription +from .types.support_event_subscription_service import ( + CreateSupportEventSubscriptionRequest, + DeleteSupportEventSubscriptionRequest, + GetSupportEventSubscriptionRequest, + ListSupportEventSubscriptionsRequest, + ListSupportEventSubscriptionsResponse, + UndeleteSupportEventSubscriptionRequest, + UpdateSupportEventSubscriptionRequest, +) if hasattr(api_core, "check_python_version") and hasattr( api_core, "check_dependency_versions" @@ -146,6 +160,7 @@ def _get_version(dependency_name): "CaseAttachmentServiceAsyncClient", "CaseServiceAsyncClient", "CommentServiceAsyncClient", + "SupportEventSubscriptionServiceAsyncClient", "Actor", "Attachment", "Case", @@ -157,20 +172,29 @@ def _get_version(dependency_name): "CommentServiceClient", "CreateCaseRequest", "CreateCommentRequest", + "CreateSupportEventSubscriptionRequest", + "DeleteSupportEventSubscriptionRequest", "EscalateCaseRequest", "Escalation", "GetAttachmentRequest", "GetCaseRequest", "GetCommentRequest", + "GetSupportEventSubscriptionRequest", "ListAttachmentsRequest", "ListAttachmentsResponse", "ListCasesRequest", "ListCasesResponse", "ListCommentsRequest", "ListCommentsResponse", + "ListSupportEventSubscriptionsRequest", + "ListSupportEventSubscriptionsResponse", "SearchCaseClassificationsRequest", "SearchCaseClassificationsResponse", "SearchCasesRequest", "SearchCasesResponse", + "SupportEventSubscription", + "SupportEventSubscriptionServiceClient", + "UndeleteSupportEventSubscriptionRequest", "UpdateCaseRequest", + "UpdateSupportEventSubscriptionRequest", ) diff --git a/packages/google-cloud-support/google/cloud/support_v2/gapic_metadata.json b/packages/google-cloud-support/google/cloud/support_v2/gapic_metadata.json index 2dc5bec76621..2f760a92d332 100644 --- a/packages/google-cloud-support/google/cloud/support_v2/gapic_metadata.json +++ b/packages/google-cloud-support/google/cloud/support_v2/gapic_metadata.json @@ -256,6 +256,115 @@ } } } + }, + "SupportEventSubscriptionService": { + "clients": { + "grpc": { + "libraryClient": "SupportEventSubscriptionServiceClient", + "rpcs": { + "CreateSupportEventSubscription": { + "methods": [ + "create_support_event_subscription" + ] + }, + "DeleteSupportEventSubscription": { + "methods": [ + "delete_support_event_subscription" + ] + }, + "GetSupportEventSubscription": { + "methods": [ + "get_support_event_subscription" + ] + }, + "ListSupportEventSubscriptions": { + "methods": [ + "list_support_event_subscriptions" + ] + }, + "UndeleteSupportEventSubscription": { + "methods": [ + "undelete_support_event_subscription" + ] + }, + "UpdateSupportEventSubscription": { + "methods": [ + "update_support_event_subscription" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SupportEventSubscriptionServiceAsyncClient", + "rpcs": { + "CreateSupportEventSubscription": { + "methods": [ + "create_support_event_subscription" + ] + }, + "DeleteSupportEventSubscription": { + "methods": [ + "delete_support_event_subscription" + ] + }, + "GetSupportEventSubscription": { + "methods": [ + "get_support_event_subscription" + ] + }, + "ListSupportEventSubscriptions": { + "methods": [ + "list_support_event_subscriptions" + ] + }, + "UndeleteSupportEventSubscription": { + "methods": [ + "undelete_support_event_subscription" + ] + }, + "UpdateSupportEventSubscription": { + "methods": [ + "update_support_event_subscription" + ] + } + } + }, + "rest": { + "libraryClient": "SupportEventSubscriptionServiceClient", + "rpcs": { + "CreateSupportEventSubscription": { + "methods": [ + "create_support_event_subscription" + ] + }, + "DeleteSupportEventSubscription": { + "methods": [ + "delete_support_event_subscription" + ] + }, + "GetSupportEventSubscription": { + "methods": [ + "get_support_event_subscription" + ] + }, + "ListSupportEventSubscriptions": { + "methods": [ + "list_support_event_subscriptions" + ] + }, + "UndeleteSupportEventSubscription": { + "methods": [ + "undelete_support_event_subscription" + ] + }, + "UpdateSupportEventSubscription": { + "methods": [ + "update_support_event_subscription" + ] + } + } + } + } } } } diff --git a/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/__init__.py b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/__init__.py new file mode 100644 index 000000000000..e6fdafc1b99f --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import SupportEventSubscriptionServiceAsyncClient +from .client import SupportEventSubscriptionServiceClient + +__all__ = ( + "SupportEventSubscriptionServiceClient", + "SupportEventSubscriptionServiceAsyncClient", +) diff --git a/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/async_client.py b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/async_client.py new file mode 100644 index 000000000000..acfea2738f12 --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/async_client.py @@ -0,0 +1,1099 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.support_v2 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore + +from google.cloud.support_v2.services.support_event_subscription_service import pagers +from google.cloud.support_v2.types import ( + support_event_subscription, + support_event_subscription_service, +) +from google.cloud.support_v2.types import ( + support_event_subscription as gcs_support_event_subscription, +) + +from .client import SupportEventSubscriptionServiceClient +from .transports.base import ( + DEFAULT_CLIENT_INFO, + SupportEventSubscriptionServiceTransport, +) +from .transports.grpc_asyncio import SupportEventSubscriptionServiceGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class SupportEventSubscriptionServiceAsyncClient: + """Service for managing customer support event subscriptions.""" + + _client: SupportEventSubscriptionServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SupportEventSubscriptionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SupportEventSubscriptionServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ( + SupportEventSubscriptionServiceClient._DEFAULT_ENDPOINT_TEMPLATE + ) + _DEFAULT_UNIVERSE = SupportEventSubscriptionServiceClient._DEFAULT_UNIVERSE + + support_event_subscription_path = staticmethod( + SupportEventSubscriptionServiceClient.support_event_subscription_path + ) + parse_support_event_subscription_path = staticmethod( + SupportEventSubscriptionServiceClient.parse_support_event_subscription_path + ) + common_billing_account_path = staticmethod( + SupportEventSubscriptionServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + SupportEventSubscriptionServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + SupportEventSubscriptionServiceClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + SupportEventSubscriptionServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + SupportEventSubscriptionServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + SupportEventSubscriptionServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + SupportEventSubscriptionServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + SupportEventSubscriptionServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + SupportEventSubscriptionServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + SupportEventSubscriptionServiceClient.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: + SupportEventSubscriptionServiceAsyncClient: The constructed client. + """ + sa_info_func = ( + SupportEventSubscriptionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + SupportEventSubscriptionServiceAsyncClient, info, *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: + SupportEventSubscriptionServiceAsyncClient: The constructed client. + """ + sa_file_func = ( + SupportEventSubscriptionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + SupportEventSubscriptionServiceAsyncClient, filename, *args, **kwargs + ) + + 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 SupportEventSubscriptionServiceClient.get_mtls_endpoint_and_cert_source( + client_options + ) # type: ignore + + @property + def transport(self) -> SupportEventSubscriptionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SupportEventSubscriptionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """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 = SupportEventSubscriptionServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + SupportEventSubscriptionServiceTransport, + Callable[..., SupportEventSubscriptionServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the support event subscription service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SupportEventSubscriptionServiceTransport,Callable[..., SupportEventSubscriptionServiceTransport]]]): + 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 SupportEventSubscriptionServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = SupportEventSubscriptionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.support_v2.SupportEventSubscriptionServiceAsyncClient`.", + extra={ + "serviceName": "google.cloud.support.v2.SupportEventSubscriptionService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.support.v2.SupportEventSubscriptionService", + "credentialsType": None, + }, + ) + + async def create_support_event_subscription( + self, + request: Optional[ + Union[ + support_event_subscription_service.CreateSupportEventSubscriptionRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + support_event_subscription: Optional[ + gcs_support_event_subscription.SupportEventSubscription + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcs_support_event_subscription.SupportEventSubscription: + r"""Creates a support event subscription 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 support_v2 + + async def sample_create_support_event_subscription(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + support_event_subscription = support_v2.SupportEventSubscription() + support_event_subscription.pub_sub_topic = "pub_sub_topic_value" + + request = support_v2.CreateSupportEventSubscriptionRequest( + parent="parent_value", + support_event_subscription=support_event_subscription, + ) + + # Make the request + response = await client.create_support_event_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.support_v2.types.CreateSupportEventSubscriptionRequest, dict]]): + The request object. Request message for + CreateSupportEventSubscription. + parent (:class:`str`): + Required. The parent resource name where the support + event subscription will be created. Format: + organizations/{organization_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + support_event_subscription (:class:`google.cloud.support_v2.types.SupportEventSubscription`): + Required. The Pub/Sub configuration + to create. + + This corresponds to the ``support_event_subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2.types.SupportEventSubscription: + A support event subscription. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, support_event_subscription] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.CreateSupportEventSubscriptionRequest, + ): + request = support_event_subscription_service.CreateSupportEventSubscriptionRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if support_event_subscription is not None: + request.support_event_subscription = support_event_subscription + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_support_event_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_support_event_subscription( + self, + request: Optional[ + Union[ + support_event_subscription_service.GetSupportEventSubscriptionRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> support_event_subscription.SupportEventSubscription: + r"""Gets a support event subscription. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import support_v2 + + async def sample_get_support_event_subscription(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + request = support_v2.GetSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_support_event_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.support_v2.types.GetSupportEventSubscriptionRequest, dict]]): + The request object. Request message for + GetSupportEventSubscription. + name (:class:`str`): + Required. The name of the support event subscription to + retrieve. Format: + organizations/{organization_id}/supportEventSubscriptions/{subscription_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2.types.SupportEventSubscription: + A support event subscription. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.GetSupportEventSubscriptionRequest, + ): + request = ( + support_event_subscription_service.GetSupportEventSubscriptionRequest( + request + ) + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_support_event_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_support_event_subscriptions( + self, + request: Optional[ + Union[ + support_event_subscription_service.ListSupportEventSubscriptionsRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSupportEventSubscriptionsAsyncPager: + r"""Lists support event subscriptions. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import support_v2 + + async def sample_list_support_event_subscriptions(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + request = support_v2.ListSupportEventSubscriptionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_support_event_subscriptions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.support_v2.types.ListSupportEventSubscriptionsRequest, dict]]): + The request object. Request message for + ListSupportEventSubscriptions. + parent (:class:`str`): + Required. The fully qualified name of the Cloud resource + to list support event subscriptions under. Format: + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2.services.support_event_subscription_service.pagers.ListSupportEventSubscriptionsAsyncPager: + Response message for + ListSupportEventSubscriptions. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.ListSupportEventSubscriptionsRequest, + ): + request = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest( + request + ) + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = 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_support_event_subscriptions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSupportEventSubscriptionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_support_event_subscription( + self, + request: Optional[ + Union[ + support_event_subscription_service.UpdateSupportEventSubscriptionRequest, + dict, + ] + ] = None, + *, + support_event_subscription: Optional[ + gcs_support_event_subscription.SupportEventSubscription + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcs_support_event_subscription.SupportEventSubscription: + r"""Updates a support event subscription. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import support_v2 + + async def sample_update_support_event_subscription(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + support_event_subscription = support_v2.SupportEventSubscription() + support_event_subscription.pub_sub_topic = "pub_sub_topic_value" + + request = support_v2.UpdateSupportEventSubscriptionRequest( + support_event_subscription=support_event_subscription, + ) + + # Make the request + response = await client.update_support_event_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.support_v2.types.UpdateSupportEventSubscriptionRequest, dict]]): + The request object. Request message for + UpdateSupportEventSubscription. + support_event_subscription (:class:`google.cloud.support_v2.types.SupportEventSubscription`): + Required. The support event subscription to update. The + ``name`` field is used to identify the configuration to + update. + + This corresponds to the ``support_event_subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The list of fields to update. The only + supported value is pub_sub_topic. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2.types.SupportEventSubscription: + A support event subscription. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [support_event_subscription, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.UpdateSupportEventSubscriptionRequest, + ): + request = support_event_subscription_service.UpdateSupportEventSubscriptionRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if support_event_subscription is not None: + request.support_event_subscription = support_event_subscription + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_support_event_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ( + "support_event_subscription.name", + request.support_event_subscription.name, + ), + ) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_support_event_subscription( + self, + request: Optional[ + Union[ + support_event_subscription_service.DeleteSupportEventSubscriptionRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> support_event_subscription.SupportEventSubscription: + r"""Soft deletes a support event subscription. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import support_v2 + + async def sample_delete_support_event_subscription(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + request = support_v2.DeleteSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = await client.delete_support_event_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.support_v2.types.DeleteSupportEventSubscriptionRequest, dict]]): + The request object. Request message for + DeleteSupportEventSubscription. + name (:class:`str`): + Required. The name of the support event subscription to + delete. Format: + organizations/{organization_id}/supportEventSubscriptions/{subscription_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2.types.SupportEventSubscription: + A support event subscription. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.DeleteSupportEventSubscriptionRequest, + ): + request = support_event_subscription_service.DeleteSupportEventSubscriptionRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_support_event_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def undelete_support_event_subscription( + self, + request: Optional[ + Union[ + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest, + dict, + ] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> support_event_subscription.SupportEventSubscription: + r"""Undeletes a support event subscription. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import support_v2 + + async def sample_undelete_support_event_subscription(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + request = support_v2.UndeleteSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = await client.undelete_support_event_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.support_v2.types.UndeleteSupportEventSubscriptionRequest, dict]]): + The request object. Request message for + UndeleteSupportEventSubscription. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2.types.SupportEventSubscription: + A support event subscription. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest, + ): + request = support_event_subscription_service.UndeleteSupportEventSubscriptionRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.undelete_support_event_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "SupportEventSubscriptionServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("SupportEventSubscriptionServiceAsyncClient",) diff --git a/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/client.py b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/client.py new file mode 100644 index 000000000000..3167f48499bb --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/client.py @@ -0,0 +1,1533 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.support_v2 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore + +from google.cloud.support_v2.services.support_event_subscription_service import pagers +from google.cloud.support_v2.types import ( + support_event_subscription, + support_event_subscription_service, +) +from google.cloud.support_v2.types import ( + support_event_subscription as gcs_support_event_subscription, +) + +from .transports.base import ( + DEFAULT_CLIENT_INFO, + SupportEventSubscriptionServiceTransport, +) +from .transports.grpc import SupportEventSubscriptionServiceGrpcTransport +from .transports.grpc_asyncio import SupportEventSubscriptionServiceGrpcAsyncIOTransport +from .transports.rest import SupportEventSubscriptionServiceRestTransport + + +class SupportEventSubscriptionServiceClientMeta(type): + """Metaclass for the SupportEventSubscriptionService 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[SupportEventSubscriptionServiceTransport]] + _transport_registry["grpc"] = SupportEventSubscriptionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ( + SupportEventSubscriptionServiceGrpcAsyncIOTransport + ) + _transport_registry["rest"] = SupportEventSubscriptionServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[SupportEventSubscriptionServiceTransport]: + """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 SupportEventSubscriptionServiceClient( + metaclass=SupportEventSubscriptionServiceClientMeta +): + """Service for managing customer support event subscriptions.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """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: + Optional[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) + if m is None: + # Could not parse api_endpoint; return as-is. + return 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 = "cloudsupport.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "cloudsupport.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SupportEventSubscriptionServiceClient: 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: + SupportEventSubscriptionServiceClient: 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) -> SupportEventSubscriptionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SupportEventSubscriptionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def support_event_subscription_path( + organization: str, + support_event_subscription: str, + ) -> str: + """Returns a fully-qualified support_event_subscription string.""" + return "organizations/{organization}/supportEventSubscriptions/{support_event_subscription}".format( + organization=organization, + support_event_subscription=support_event_subscription, + ) + + @staticmethod + def parse_support_event_subscription_path(path: str) -> Dict[str, str]: + """Parses a support_event_subscription path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/supportEventSubscriptions/(?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 = ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + ) + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + 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: + 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 = ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + ) + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + 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, 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 + ) -> str: + """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 = SupportEventSubscriptionServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = SupportEventSubscriptionServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ( + SupportEventSubscriptionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.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 = SupportEventSubscriptionServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """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, + SupportEventSubscriptionServiceTransport, + Callable[..., SupportEventSubscriptionServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the support event subscription service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SupportEventSubscriptionServiceTransport,Callable[..., SupportEventSubscriptionServiceTransport]]]): + 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 SupportEventSubscriptionServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = ( + SupportEventSubscriptionServiceClient._read_environment_variables() + ) + self._client_cert_source = ( + SupportEventSubscriptionServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = ( + SupportEventSubscriptionServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance( + transport, SupportEventSubscriptionServiceTransport + ) + if transport_provided: + # transport is a SupportEventSubscriptionServiceTransport 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(SupportEventSubscriptionServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or SupportEventSubscriptionServiceClient._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[SupportEventSubscriptionServiceTransport], + Callable[..., SupportEventSubscriptionServiceTransport], + ] = ( + SupportEventSubscriptionServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast( + Callable[..., SupportEventSubscriptionServiceTransport], transport + ) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.support_v2.SupportEventSubscriptionServiceClient`.", + extra={ + "serviceName": "google.cloud.support.v2.SupportEventSubscriptionService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.support.v2.SupportEventSubscriptionService", + "credentialsType": None, + }, + ) + + def create_support_event_subscription( + self, + request: Optional[ + Union[ + support_event_subscription_service.CreateSupportEventSubscriptionRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + support_event_subscription: Optional[ + gcs_support_event_subscription.SupportEventSubscription + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcs_support_event_subscription.SupportEventSubscription: + r"""Creates a support event subscription 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 support_v2 + + def sample_create_support_event_subscription(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + support_event_subscription = support_v2.SupportEventSubscription() + support_event_subscription.pub_sub_topic = "pub_sub_topic_value" + + request = support_v2.CreateSupportEventSubscriptionRequest( + parent="parent_value", + support_event_subscription=support_event_subscription, + ) + + # Make the request + response = client.create_support_event_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.support_v2.types.CreateSupportEventSubscriptionRequest, dict]): + The request object. Request message for + CreateSupportEventSubscription. + parent (str): + Required. The parent resource name where the support + event subscription will be created. Format: + organizations/{organization_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + support_event_subscription (google.cloud.support_v2.types.SupportEventSubscription): + Required. The Pub/Sub configuration + to create. + + This corresponds to the ``support_event_subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2.types.SupportEventSubscription: + A support event subscription. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, support_event_subscription] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.CreateSupportEventSubscriptionRequest, + ): + request = support_event_subscription_service.CreateSupportEventSubscriptionRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if support_event_subscription is not None: + request.support_event_subscription = support_event_subscription + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_support_event_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_support_event_subscription( + self, + request: Optional[ + Union[ + support_event_subscription_service.GetSupportEventSubscriptionRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> support_event_subscription.SupportEventSubscription: + r"""Gets a support event subscription. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import support_v2 + + def sample_get_support_event_subscription(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + request = support_v2.GetSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = client.get_support_event_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.support_v2.types.GetSupportEventSubscriptionRequest, dict]): + The request object. Request message for + GetSupportEventSubscription. + name (str): + Required. The name of the support event subscription to + retrieve. Format: + organizations/{organization_id}/supportEventSubscriptions/{subscription_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2.types.SupportEventSubscription: + A support event subscription. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.GetSupportEventSubscriptionRequest, + ): + request = ( + support_event_subscription_service.GetSupportEventSubscriptionRequest( + request + ) + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.get_support_event_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_support_event_subscriptions( + self, + request: Optional[ + Union[ + support_event_subscription_service.ListSupportEventSubscriptionsRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSupportEventSubscriptionsPager: + r"""Lists support event subscriptions. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import support_v2 + + def sample_list_support_event_subscriptions(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + request = support_v2.ListSupportEventSubscriptionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_support_event_subscriptions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.support_v2.types.ListSupportEventSubscriptionsRequest, dict]): + The request object. Request message for + ListSupportEventSubscriptions. + parent (str): + Required. The fully qualified name of the Cloud resource + to list support event subscriptions under. Format: + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2.services.support_event_subscription_service.pagers.ListSupportEventSubscriptionsPager: + Response message for + ListSupportEventSubscriptions. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.ListSupportEventSubscriptionsRequest, + ): + request = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest( + request + ) + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + 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_support_event_subscriptions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSupportEventSubscriptionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_support_event_subscription( + self, + request: Optional[ + Union[ + support_event_subscription_service.UpdateSupportEventSubscriptionRequest, + dict, + ] + ] = None, + *, + support_event_subscription: Optional[ + gcs_support_event_subscription.SupportEventSubscription + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcs_support_event_subscription.SupportEventSubscription: + r"""Updates a support event subscription. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import support_v2 + + def sample_update_support_event_subscription(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + support_event_subscription = support_v2.SupportEventSubscription() + support_event_subscription.pub_sub_topic = "pub_sub_topic_value" + + request = support_v2.UpdateSupportEventSubscriptionRequest( + support_event_subscription=support_event_subscription, + ) + + # Make the request + response = client.update_support_event_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.support_v2.types.UpdateSupportEventSubscriptionRequest, dict]): + The request object. Request message for + UpdateSupportEventSubscription. + support_event_subscription (google.cloud.support_v2.types.SupportEventSubscription): + Required. The support event subscription to update. The + ``name`` field is used to identify the configuration to + update. + + This corresponds to the ``support_event_subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. The only + supported value is pub_sub_topic. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2.types.SupportEventSubscription: + A support event subscription. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [support_event_subscription, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.UpdateSupportEventSubscriptionRequest, + ): + request = support_event_subscription_service.UpdateSupportEventSubscriptionRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if support_event_subscription is not None: + request.support_event_subscription = support_event_subscription + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_support_event_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ( + "support_event_subscription.name", + request.support_event_subscription.name, + ), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_support_event_subscription( + self, + request: Optional[ + Union[ + support_event_subscription_service.DeleteSupportEventSubscriptionRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> support_event_subscription.SupportEventSubscription: + r"""Soft deletes a support event subscription. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import support_v2 + + def sample_delete_support_event_subscription(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + request = support_v2.DeleteSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = client.delete_support_event_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.support_v2.types.DeleteSupportEventSubscriptionRequest, dict]): + The request object. Request message for + DeleteSupportEventSubscription. + name (str): + Required. The name of the support event subscription to + delete. Format: + organizations/{organization_id}/supportEventSubscriptions/{subscription_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2.types.SupportEventSubscription: + A support event subscription. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.DeleteSupportEventSubscriptionRequest, + ): + request = support_event_subscription_service.DeleteSupportEventSubscriptionRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_support_event_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def undelete_support_event_subscription( + self, + request: Optional[ + Union[ + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest, + dict, + ] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> support_event_subscription.SupportEventSubscription: + r"""Undeletes a support event subscription. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import support_v2 + + def sample_undelete_support_event_subscription(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + request = support_v2.UndeleteSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = client.undelete_support_event_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.support_v2.types.UndeleteSupportEventSubscriptionRequest, dict]): + The request object. Request message for + UndeleteSupportEventSubscription. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2.types.SupportEventSubscription: + A support event subscription. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest, + ): + request = support_event_subscription_service.UndeleteSupportEventSubscriptionRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.undelete_support_event_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SupportEventSubscriptionServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("SupportEventSubscriptionServiceClient",) diff --git a/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/pagers.py b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/pagers.py new file mode 100644 index 000000000000..afb64dce25fc --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/pagers.py @@ -0,0 +1,226 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +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.support_v2.types import ( + support_event_subscription, + support_event_subscription_service, +) + + +class ListSupportEventSubscriptionsPager: + """A pager for iterating through ``list_support_event_subscriptions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.support_v2.types.ListSupportEventSubscriptionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``support_event_subscriptions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSupportEventSubscriptions`` requests and continue to iterate + through the ``support_event_subscriptions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.support_v2.types.ListSupportEventSubscriptionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., + support_event_subscription_service.ListSupportEventSubscriptionsResponse, + ], + request: support_event_subscription_service.ListSupportEventSubscriptionsRequest, + response: support_event_subscription_service.ListSupportEventSubscriptionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.support_v2.types.ListSupportEventSubscriptionsRequest): + The initial request object. + response (google.cloud.support_v2.types.ListSupportEventSubscriptionsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest( + request + ) + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[ + support_event_subscription_service.ListSupportEventSubscriptionsResponse + ]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[support_event_subscription.SupportEventSubscription]: + for page in self.pages: + yield from page.support_event_subscriptions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSupportEventSubscriptionsAsyncPager: + """A pager for iterating through ``list_support_event_subscriptions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.support_v2.types.ListSupportEventSubscriptionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``support_event_subscriptions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSupportEventSubscriptions`` requests and continue to iterate + through the ``support_event_subscriptions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.support_v2.types.ListSupportEventSubscriptionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., + Awaitable[ + support_event_subscription_service.ListSupportEventSubscriptionsResponse + ], + ], + request: support_event_subscription_service.ListSupportEventSubscriptionsRequest, + response: support_event_subscription_service.ListSupportEventSubscriptionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.support_v2.types.ListSupportEventSubscriptionsRequest): + The initial request object. + response (google.cloud.support_v2.types.ListSupportEventSubscriptionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest( + request + ) + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[ + support_event_subscription_service.ListSupportEventSubscriptionsResponse + ]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__( + self, + ) -> AsyncIterator[support_event_subscription.SupportEventSubscription]: + async def async_generator(): + async for page in self.pages: + for response in page.support_event_subscriptions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/README.rst b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/README.rst new file mode 100644 index 000000000000..a0df103b1167 --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``SupportEventSubscriptionServiceTransport`` is the ABC for all transports. + +- public child ``SupportEventSubscriptionServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``SupportEventSubscriptionServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseSupportEventSubscriptionServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``SupportEventSubscriptionServiceRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/__init__.py b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/__init__.py new file mode 100644 index 000000000000..975841d1831c --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/__init__.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 SupportEventSubscriptionServiceTransport +from .grpc import SupportEventSubscriptionServiceGrpcTransport +from .grpc_asyncio import SupportEventSubscriptionServiceGrpcAsyncIOTransport +from .rest import ( + SupportEventSubscriptionServiceRestInterceptor, + SupportEventSubscriptionServiceRestTransport, +) + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SupportEventSubscriptionServiceTransport]] +_transport_registry["grpc"] = SupportEventSubscriptionServiceGrpcTransport +_transport_registry["grpc_asyncio"] = ( + SupportEventSubscriptionServiceGrpcAsyncIOTransport +) +_transport_registry["rest"] = SupportEventSubscriptionServiceRestTransport + +__all__ = ( + "SupportEventSubscriptionServiceTransport", + "SupportEventSubscriptionServiceGrpcTransport", + "SupportEventSubscriptionServiceGrpcAsyncIOTransport", + "SupportEventSubscriptionServiceRestTransport", + "SupportEventSubscriptionServiceRestInterceptor", +) diff --git a/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/base.py b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/base.py new file mode 100644 index 000000000000..2f4c98fa694f --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/base.py @@ -0,0 +1,271 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.support_v2 import gapic_version as package_version +from google.cloud.support_v2.types import ( + support_event_subscription, + support_event_subscription_service, +) +from google.cloud.support_v2.types import ( + support_event_subscription as gcs_support_event_subscription, +) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class SupportEventSubscriptionServiceTransport(abc.ABC): + """Abstract transport class for SupportEventSubscriptionService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "cloudsupport.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.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: 'cloudsupport.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # 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=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_support_event_subscription: gapic_v1.method.wrap_method( + self.create_support_event_subscription, + default_timeout=None, + client_info=client_info, + ), + self.get_support_event_subscription: gapic_v1.method.wrap_method( + self.get_support_event_subscription, + default_timeout=None, + client_info=client_info, + ), + self.list_support_event_subscriptions: gapic_v1.method.wrap_method( + self.list_support_event_subscriptions, + default_timeout=None, + client_info=client_info, + ), + self.update_support_event_subscription: gapic_v1.method.wrap_method( + self.update_support_event_subscription, + default_timeout=None, + client_info=client_info, + ), + self.delete_support_event_subscription: gapic_v1.method.wrap_method( + self.delete_support_event_subscription, + default_timeout=None, + client_info=client_info, + ), + self.undelete_support_event_subscription: gapic_v1.method.wrap_method( + self.undelete_support_event_subscription, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.CreateSupportEventSubscriptionRequest], + Union[ + gcs_support_event_subscription.SupportEventSubscription, + Awaitable[gcs_support_event_subscription.SupportEventSubscription], + ], + ]: + raise NotImplementedError() + + @property + def get_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.GetSupportEventSubscriptionRequest], + Union[ + support_event_subscription.SupportEventSubscription, + Awaitable[support_event_subscription.SupportEventSubscription], + ], + ]: + raise NotImplementedError() + + @property + def list_support_event_subscriptions( + self, + ) -> Callable[ + [support_event_subscription_service.ListSupportEventSubscriptionsRequest], + Union[ + support_event_subscription_service.ListSupportEventSubscriptionsResponse, + Awaitable[ + support_event_subscription_service.ListSupportEventSubscriptionsResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def update_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.UpdateSupportEventSubscriptionRequest], + Union[ + gcs_support_event_subscription.SupportEventSubscription, + Awaitable[gcs_support_event_subscription.SupportEventSubscription], + ], + ]: + raise NotImplementedError() + + @property + def delete_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.DeleteSupportEventSubscriptionRequest], + Union[ + support_event_subscription.SupportEventSubscription, + Awaitable[support_event_subscription.SupportEventSubscription], + ], + ]: + raise NotImplementedError() + + @property + def undelete_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.UndeleteSupportEventSubscriptionRequest], + Union[ + support_event_subscription.SupportEventSubscription, + Awaitable[support_event_subscription.SupportEventSubscription], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("SupportEventSubscriptionServiceTransport",) diff --git a/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/grpc.py b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/grpc.py new file mode 100644 index 000000000000..9c576c9b236f --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/grpc.py @@ -0,0 +1,536 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.support_v2.types import ( + support_event_subscription, + support_event_subscription_service, +) +from google.cloud.support_v2.types import ( + support_event_subscription as gcs_support_event_subscription, +) + +from .base import DEFAULT_CLIENT_INFO, SupportEventSubscriptionServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.support.v2.SupportEventSubscriptionService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.support.v2.SupportEventSubscriptionService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SupportEventSubscriptionServiceGrpcTransport( + SupportEventSubscriptionServiceTransport +): + """gRPC backend transport for SupportEventSubscriptionService. + + Service for managing customer support event subscriptions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = "cloudsupport.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudsupport.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "cloudsupport.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def create_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.CreateSupportEventSubscriptionRequest], + gcs_support_event_subscription.SupportEventSubscription, + ]: + r"""Return a callable for the create support event + subscription method over gRPC. + + Creates a support event subscription for an + organization. + + Returns: + Callable[[~.CreateSupportEventSubscriptionRequest], + ~.SupportEventSubscription]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_support_event_subscription" not in self._stubs: + self._stubs["create_support_event_subscription"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2.SupportEventSubscriptionService/CreateSupportEventSubscription", + request_serializer=support_event_subscription_service.CreateSupportEventSubscriptionRequest.serialize, + response_deserializer=gcs_support_event_subscription.SupportEventSubscription.deserialize, + ) + ) + return self._stubs["create_support_event_subscription"] + + @property + def get_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.GetSupportEventSubscriptionRequest], + support_event_subscription.SupportEventSubscription, + ]: + r"""Return a callable for the get support event subscription method over gRPC. + + Gets a support event subscription. + + Returns: + Callable[[~.GetSupportEventSubscriptionRequest], + ~.SupportEventSubscription]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_support_event_subscription" not in self._stubs: + self._stubs["get_support_event_subscription"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2.SupportEventSubscriptionService/GetSupportEventSubscription", + request_serializer=support_event_subscription_service.GetSupportEventSubscriptionRequest.serialize, + response_deserializer=support_event_subscription.SupportEventSubscription.deserialize, + ) + ) + return self._stubs["get_support_event_subscription"] + + @property + def list_support_event_subscriptions( + self, + ) -> Callable[ + [support_event_subscription_service.ListSupportEventSubscriptionsRequest], + support_event_subscription_service.ListSupportEventSubscriptionsResponse, + ]: + r"""Return a callable for the list support event + subscriptions method over gRPC. + + Lists support event subscriptions. + + Returns: + Callable[[~.ListSupportEventSubscriptionsRequest], + ~.ListSupportEventSubscriptionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_support_event_subscriptions" not in self._stubs: + self._stubs["list_support_event_subscriptions"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2.SupportEventSubscriptionService/ListSupportEventSubscriptions", + request_serializer=support_event_subscription_service.ListSupportEventSubscriptionsRequest.serialize, + response_deserializer=support_event_subscription_service.ListSupportEventSubscriptionsResponse.deserialize, + ) + ) + return self._stubs["list_support_event_subscriptions"] + + @property + def update_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.UpdateSupportEventSubscriptionRequest], + gcs_support_event_subscription.SupportEventSubscription, + ]: + r"""Return a callable for the update support event + subscription method over gRPC. + + Updates a support event subscription. + + Returns: + Callable[[~.UpdateSupportEventSubscriptionRequest], + ~.SupportEventSubscription]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_support_event_subscription" not in self._stubs: + self._stubs["update_support_event_subscription"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2.SupportEventSubscriptionService/UpdateSupportEventSubscription", + request_serializer=support_event_subscription_service.UpdateSupportEventSubscriptionRequest.serialize, + response_deserializer=gcs_support_event_subscription.SupportEventSubscription.deserialize, + ) + ) + return self._stubs["update_support_event_subscription"] + + @property + def delete_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.DeleteSupportEventSubscriptionRequest], + support_event_subscription.SupportEventSubscription, + ]: + r"""Return a callable for the delete support event + subscription method over gRPC. + + Soft deletes a support event subscription. + + Returns: + Callable[[~.DeleteSupportEventSubscriptionRequest], + ~.SupportEventSubscription]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_support_event_subscription" not in self._stubs: + self._stubs["delete_support_event_subscription"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2.SupportEventSubscriptionService/DeleteSupportEventSubscription", + request_serializer=support_event_subscription_service.DeleteSupportEventSubscriptionRequest.serialize, + response_deserializer=support_event_subscription.SupportEventSubscription.deserialize, + ) + ) + return self._stubs["delete_support_event_subscription"] + + @property + def undelete_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.UndeleteSupportEventSubscriptionRequest], + support_event_subscription.SupportEventSubscription, + ]: + r"""Return a callable for the undelete support event + subscription method over gRPC. + + Undeletes a support event subscription. + + Returns: + Callable[[~.UndeleteSupportEventSubscriptionRequest], + ~.SupportEventSubscription]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "undelete_support_event_subscription" not in self._stubs: + self._stubs["undelete_support_event_subscription"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2.SupportEventSubscriptionService/UndeleteSupportEventSubscription", + request_serializer=support_event_subscription_service.UndeleteSupportEventSubscriptionRequest.serialize, + response_deserializer=support_event_subscription.SupportEventSubscription.deserialize, + ) + ) + return self._stubs["undelete_support_event_subscription"] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("SupportEventSubscriptionServiceGrpcTransport",) diff --git a/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/grpc_asyncio.py b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..50959a03b753 --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/grpc_asyncio.py @@ -0,0 +1,586 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.support_v2.types import ( + support_event_subscription, + support_event_subscription_service, +) +from google.cloud.support_v2.types import ( + support_event_subscription as gcs_support_event_subscription, +) + +from .base import DEFAULT_CLIENT_INFO, SupportEventSubscriptionServiceTransport +from .grpc import SupportEventSubscriptionServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.support.v2.SupportEventSubscriptionService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.support.v2.SupportEventSubscriptionService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SupportEventSubscriptionServiceGrpcAsyncIOTransport( + SupportEventSubscriptionServiceTransport +): + """gRPC AsyncIO backend transport for SupportEventSubscriptionService. + + Service for managing customer support event subscriptions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = "cloudsupport.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (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 = "cloudsupport.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudsupport.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.CreateSupportEventSubscriptionRequest], + Awaitable[gcs_support_event_subscription.SupportEventSubscription], + ]: + r"""Return a callable for the create support event + subscription method over gRPC. + + Creates a support event subscription for an + organization. + + Returns: + Callable[[~.CreateSupportEventSubscriptionRequest], + Awaitable[~.SupportEventSubscription]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_support_event_subscription" not in self._stubs: + self._stubs["create_support_event_subscription"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2.SupportEventSubscriptionService/CreateSupportEventSubscription", + request_serializer=support_event_subscription_service.CreateSupportEventSubscriptionRequest.serialize, + response_deserializer=gcs_support_event_subscription.SupportEventSubscription.deserialize, + ) + ) + return self._stubs["create_support_event_subscription"] + + @property + def get_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.GetSupportEventSubscriptionRequest], + Awaitable[support_event_subscription.SupportEventSubscription], + ]: + r"""Return a callable for the get support event subscription method over gRPC. + + Gets a support event subscription. + + Returns: + Callable[[~.GetSupportEventSubscriptionRequest], + Awaitable[~.SupportEventSubscription]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_support_event_subscription" not in self._stubs: + self._stubs["get_support_event_subscription"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2.SupportEventSubscriptionService/GetSupportEventSubscription", + request_serializer=support_event_subscription_service.GetSupportEventSubscriptionRequest.serialize, + response_deserializer=support_event_subscription.SupportEventSubscription.deserialize, + ) + ) + return self._stubs["get_support_event_subscription"] + + @property + def list_support_event_subscriptions( + self, + ) -> Callable[ + [support_event_subscription_service.ListSupportEventSubscriptionsRequest], + Awaitable[ + support_event_subscription_service.ListSupportEventSubscriptionsResponse + ], + ]: + r"""Return a callable for the list support event + subscriptions method over gRPC. + + Lists support event subscriptions. + + Returns: + Callable[[~.ListSupportEventSubscriptionsRequest], + Awaitable[~.ListSupportEventSubscriptionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_support_event_subscriptions" not in self._stubs: + self._stubs["list_support_event_subscriptions"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2.SupportEventSubscriptionService/ListSupportEventSubscriptions", + request_serializer=support_event_subscription_service.ListSupportEventSubscriptionsRequest.serialize, + response_deserializer=support_event_subscription_service.ListSupportEventSubscriptionsResponse.deserialize, + ) + ) + return self._stubs["list_support_event_subscriptions"] + + @property + def update_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.UpdateSupportEventSubscriptionRequest], + Awaitable[gcs_support_event_subscription.SupportEventSubscription], + ]: + r"""Return a callable for the update support event + subscription method over gRPC. + + Updates a support event subscription. + + Returns: + Callable[[~.UpdateSupportEventSubscriptionRequest], + Awaitable[~.SupportEventSubscription]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_support_event_subscription" not in self._stubs: + self._stubs["update_support_event_subscription"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2.SupportEventSubscriptionService/UpdateSupportEventSubscription", + request_serializer=support_event_subscription_service.UpdateSupportEventSubscriptionRequest.serialize, + response_deserializer=gcs_support_event_subscription.SupportEventSubscription.deserialize, + ) + ) + return self._stubs["update_support_event_subscription"] + + @property + def delete_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.DeleteSupportEventSubscriptionRequest], + Awaitable[support_event_subscription.SupportEventSubscription], + ]: + r"""Return a callable for the delete support event + subscription method over gRPC. + + Soft deletes a support event subscription. + + Returns: + Callable[[~.DeleteSupportEventSubscriptionRequest], + Awaitable[~.SupportEventSubscription]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_support_event_subscription" not in self._stubs: + self._stubs["delete_support_event_subscription"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2.SupportEventSubscriptionService/DeleteSupportEventSubscription", + request_serializer=support_event_subscription_service.DeleteSupportEventSubscriptionRequest.serialize, + response_deserializer=support_event_subscription.SupportEventSubscription.deserialize, + ) + ) + return self._stubs["delete_support_event_subscription"] + + @property + def undelete_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.UndeleteSupportEventSubscriptionRequest], + Awaitable[support_event_subscription.SupportEventSubscription], + ]: + r"""Return a callable for the undelete support event + subscription method over gRPC. + + Undeletes a support event subscription. + + Returns: + Callable[[~.UndeleteSupportEventSubscriptionRequest], + Awaitable[~.SupportEventSubscription]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "undelete_support_event_subscription" not in self._stubs: + self._stubs["undelete_support_event_subscription"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2.SupportEventSubscriptionService/UndeleteSupportEventSubscription", + request_serializer=support_event_subscription_service.UndeleteSupportEventSubscriptionRequest.serialize, + response_deserializer=support_event_subscription.SupportEventSubscription.deserialize, + ) + ) + return self._stubs["undelete_support_event_subscription"] + + 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_support_event_subscription: self._wrap_method( + self.create_support_event_subscription, + default_timeout=None, + client_info=client_info, + ), + self.get_support_event_subscription: self._wrap_method( + self.get_support_event_subscription, + default_timeout=None, + client_info=client_info, + ), + self.list_support_event_subscriptions: self._wrap_method( + self.list_support_event_subscriptions, + default_timeout=None, + client_info=client_info, + ), + self.update_support_event_subscription: self._wrap_method( + self.update_support_event_subscription, + default_timeout=None, + client_info=client_info, + ), + self.delete_support_event_subscription: self._wrap_method( + self.delete_support_event_subscription, + default_timeout=None, + client_info=client_info, + ), + self.undelete_support_event_subscription: self._wrap_method( + self.undelete_support_event_subscription, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ("SupportEventSubscriptionServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/rest.py b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/rest.py new file mode 100644 index 000000000000..8f5c1b5f679b --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/rest.py @@ -0,0 +1,1584 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.support_v2.types import ( + support_event_subscription, + support_event_subscription_service, +) +from google.cloud.support_v2.types import ( + support_event_subscription as gcs_support_event_subscription, +) + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseSupportEventSubscriptionServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class SupportEventSubscriptionServiceRestInterceptor: + """Interceptor for SupportEventSubscriptionService. + + 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 SupportEventSubscriptionServiceRestTransport. + + .. code-block:: python + class MyCustomSupportEventSubscriptionServiceInterceptor(SupportEventSubscriptionServiceRestInterceptor): + def pre_create_support_event_subscription(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_support_event_subscription(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_support_event_subscription(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_support_event_subscription(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_support_event_subscription(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_support_event_subscription(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_support_event_subscriptions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_support_event_subscriptions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_undelete_support_event_subscription(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_undelete_support_event_subscription(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_support_event_subscription(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_support_event_subscription(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SupportEventSubscriptionServiceRestTransport(interceptor=MyCustomSupportEventSubscriptionServiceInterceptor()) + client = SupportEventSubscriptionServiceClient(transport=transport) + + + """ + + def pre_create_support_event_subscription( + self, + request: support_event_subscription_service.CreateSupportEventSubscriptionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + support_event_subscription_service.CreateSupportEventSubscriptionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_support_event_subscription + + Override in a subclass to manipulate the request or metadata + before they are sent to the SupportEventSubscriptionService server. + """ + return request, metadata + + def post_create_support_event_subscription( + self, response: gcs_support_event_subscription.SupportEventSubscription + ) -> gcs_support_event_subscription.SupportEventSubscription: + """Post-rpc interceptor for create_support_event_subscription + + DEPRECATED. Please use the `post_create_support_event_subscription_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SupportEventSubscriptionService server but before + it is returned to user code. This `post_create_support_event_subscription` interceptor runs + before the `post_create_support_event_subscription_with_metadata` interceptor. + """ + return response + + def post_create_support_event_subscription_with_metadata( + self, + response: gcs_support_event_subscription.SupportEventSubscription, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcs_support_event_subscription.SupportEventSubscription, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for create_support_event_subscription + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SupportEventSubscriptionService server but before it is returned to user code. + + We recommend only using this `post_create_support_event_subscription_with_metadata` + interceptor in new development instead of the `post_create_support_event_subscription` interceptor. + When both interceptors are used, this `post_create_support_event_subscription_with_metadata` interceptor runs after the + `post_create_support_event_subscription` interceptor. The (possibly modified) response returned by + `post_create_support_event_subscription` will be passed to + `post_create_support_event_subscription_with_metadata`. + """ + return response, metadata + + def pre_delete_support_event_subscription( + self, + request: support_event_subscription_service.DeleteSupportEventSubscriptionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + support_event_subscription_service.DeleteSupportEventSubscriptionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_support_event_subscription + + Override in a subclass to manipulate the request or metadata + before they are sent to the SupportEventSubscriptionService server. + """ + return request, metadata + + def post_delete_support_event_subscription( + self, response: support_event_subscription.SupportEventSubscription + ) -> support_event_subscription.SupportEventSubscription: + """Post-rpc interceptor for delete_support_event_subscription + + DEPRECATED. Please use the `post_delete_support_event_subscription_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SupportEventSubscriptionService server but before + it is returned to user code. This `post_delete_support_event_subscription` interceptor runs + before the `post_delete_support_event_subscription_with_metadata` interceptor. + """ + return response + + def post_delete_support_event_subscription_with_metadata( + self, + response: support_event_subscription.SupportEventSubscription, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + support_event_subscription.SupportEventSubscription, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for delete_support_event_subscription + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SupportEventSubscriptionService server but before it is returned to user code. + + We recommend only using this `post_delete_support_event_subscription_with_metadata` + interceptor in new development instead of the `post_delete_support_event_subscription` interceptor. + When both interceptors are used, this `post_delete_support_event_subscription_with_metadata` interceptor runs after the + `post_delete_support_event_subscription` interceptor. The (possibly modified) response returned by + `post_delete_support_event_subscription` will be passed to + `post_delete_support_event_subscription_with_metadata`. + """ + return response, metadata + + def pre_get_support_event_subscription( + self, + request: support_event_subscription_service.GetSupportEventSubscriptionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + support_event_subscription_service.GetSupportEventSubscriptionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_support_event_subscription + + Override in a subclass to manipulate the request or metadata + before they are sent to the SupportEventSubscriptionService server. + """ + return request, metadata + + def post_get_support_event_subscription( + self, response: support_event_subscription.SupportEventSubscription + ) -> support_event_subscription.SupportEventSubscription: + """Post-rpc interceptor for get_support_event_subscription + + DEPRECATED. Please use the `post_get_support_event_subscription_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SupportEventSubscriptionService server but before + it is returned to user code. This `post_get_support_event_subscription` interceptor runs + before the `post_get_support_event_subscription_with_metadata` interceptor. + """ + return response + + def post_get_support_event_subscription_with_metadata( + self, + response: support_event_subscription.SupportEventSubscription, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + support_event_subscription.SupportEventSubscription, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_support_event_subscription + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SupportEventSubscriptionService server but before it is returned to user code. + + We recommend only using this `post_get_support_event_subscription_with_metadata` + interceptor in new development instead of the `post_get_support_event_subscription` interceptor. + When both interceptors are used, this `post_get_support_event_subscription_with_metadata` interceptor runs after the + `post_get_support_event_subscription` interceptor. The (possibly modified) response returned by + `post_get_support_event_subscription` will be passed to + `post_get_support_event_subscription_with_metadata`. + """ + return response, metadata + + def pre_list_support_event_subscriptions( + self, + request: support_event_subscription_service.ListSupportEventSubscriptionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + support_event_subscription_service.ListSupportEventSubscriptionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_support_event_subscriptions + + Override in a subclass to manipulate the request or metadata + before they are sent to the SupportEventSubscriptionService server. + """ + return request, metadata + + def post_list_support_event_subscriptions( + self, + response: support_event_subscription_service.ListSupportEventSubscriptionsResponse, + ) -> support_event_subscription_service.ListSupportEventSubscriptionsResponse: + """Post-rpc interceptor for list_support_event_subscriptions + + DEPRECATED. Please use the `post_list_support_event_subscriptions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SupportEventSubscriptionService server but before + it is returned to user code. This `post_list_support_event_subscriptions` interceptor runs + before the `post_list_support_event_subscriptions_with_metadata` interceptor. + """ + return response + + def post_list_support_event_subscriptions_with_metadata( + self, + response: support_event_subscription_service.ListSupportEventSubscriptionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + support_event_subscription_service.ListSupportEventSubscriptionsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_support_event_subscriptions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SupportEventSubscriptionService server but before it is returned to user code. + + We recommend only using this `post_list_support_event_subscriptions_with_metadata` + interceptor in new development instead of the `post_list_support_event_subscriptions` interceptor. + When both interceptors are used, this `post_list_support_event_subscriptions_with_metadata` interceptor runs after the + `post_list_support_event_subscriptions` interceptor. The (possibly modified) response returned by + `post_list_support_event_subscriptions` will be passed to + `post_list_support_event_subscriptions_with_metadata`. + """ + return response, metadata + + def pre_undelete_support_event_subscription( + self, + request: support_event_subscription_service.UndeleteSupportEventSubscriptionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for undelete_support_event_subscription + + Override in a subclass to manipulate the request or metadata + before they are sent to the SupportEventSubscriptionService server. + """ + return request, metadata + + def post_undelete_support_event_subscription( + self, response: support_event_subscription.SupportEventSubscription + ) -> support_event_subscription.SupportEventSubscription: + """Post-rpc interceptor for undelete_support_event_subscription + + DEPRECATED. Please use the `post_undelete_support_event_subscription_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SupportEventSubscriptionService server but before + it is returned to user code. This `post_undelete_support_event_subscription` interceptor runs + before the `post_undelete_support_event_subscription_with_metadata` interceptor. + """ + return response + + def post_undelete_support_event_subscription_with_metadata( + self, + response: support_event_subscription.SupportEventSubscription, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + support_event_subscription.SupportEventSubscription, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for undelete_support_event_subscription + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SupportEventSubscriptionService server but before it is returned to user code. + + We recommend only using this `post_undelete_support_event_subscription_with_metadata` + interceptor in new development instead of the `post_undelete_support_event_subscription` interceptor. + When both interceptors are used, this `post_undelete_support_event_subscription_with_metadata` interceptor runs after the + `post_undelete_support_event_subscription` interceptor. The (possibly modified) response returned by + `post_undelete_support_event_subscription` will be passed to + `post_undelete_support_event_subscription_with_metadata`. + """ + return response, metadata + + def pre_update_support_event_subscription( + self, + request: support_event_subscription_service.UpdateSupportEventSubscriptionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + support_event_subscription_service.UpdateSupportEventSubscriptionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_support_event_subscription + + Override in a subclass to manipulate the request or metadata + before they are sent to the SupportEventSubscriptionService server. + """ + return request, metadata + + def post_update_support_event_subscription( + self, response: gcs_support_event_subscription.SupportEventSubscription + ) -> gcs_support_event_subscription.SupportEventSubscription: + """Post-rpc interceptor for update_support_event_subscription + + DEPRECATED. Please use the `post_update_support_event_subscription_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SupportEventSubscriptionService server but before + it is returned to user code. This `post_update_support_event_subscription` interceptor runs + before the `post_update_support_event_subscription_with_metadata` interceptor. + """ + return response + + def post_update_support_event_subscription_with_metadata( + self, + response: gcs_support_event_subscription.SupportEventSubscription, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcs_support_event_subscription.SupportEventSubscription, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for update_support_event_subscription + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SupportEventSubscriptionService server but before it is returned to user code. + + We recommend only using this `post_update_support_event_subscription_with_metadata` + interceptor in new development instead of the `post_update_support_event_subscription` interceptor. + When both interceptors are used, this `post_update_support_event_subscription_with_metadata` interceptor runs after the + `post_update_support_event_subscription` interceptor. The (possibly modified) response returned by + `post_update_support_event_subscription` will be passed to + `post_update_support_event_subscription_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class SupportEventSubscriptionServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SupportEventSubscriptionServiceRestInterceptor + + +class SupportEventSubscriptionServiceRestTransport( + _BaseSupportEventSubscriptionServiceRestTransport +): + """REST backend synchronous transport for SupportEventSubscriptionService. + + Service for managing customer support event subscriptions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "cloudsupport.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[SupportEventSubscriptionServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudsupport.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + 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. + interceptor (Optional[SupportEventSubscriptionServiceRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = ( + interceptor or SupportEventSubscriptionServiceRestInterceptor() + ) + self._prep_wrapped_messages(client_info) + + class _CreateSupportEventSubscription( + _BaseSupportEventSubscriptionServiceRestTransport._BaseCreateSupportEventSubscription, + SupportEventSubscriptionServiceRestStub, + ): + def __hash__(self): + return hash( + "SupportEventSubscriptionServiceRestTransport.CreateSupportEventSubscription" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: support_event_subscription_service.CreateSupportEventSubscriptionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcs_support_event_subscription.SupportEventSubscription: + r"""Call the create support event + subscription method over HTTP. + + Args: + request (~.support_event_subscription_service.CreateSupportEventSubscriptionRequest): + The request object. Request message for + CreateSupportEventSubscription. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcs_support_event_subscription.SupportEventSubscription: + A support event subscription. + """ + + http_options = _BaseSupportEventSubscriptionServiceRestTransport._BaseCreateSupportEventSubscription._get_http_options() + + request, metadata = self._interceptor.pre_create_support_event_subscription( + request, metadata + ) + transcoded_request = _BaseSupportEventSubscriptionServiceRestTransport._BaseCreateSupportEventSubscription._get_transcoded_request( + http_options, request + ) + + body = _BaseSupportEventSubscriptionServiceRestTransport._BaseCreateSupportEventSubscription._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSupportEventSubscriptionServiceRestTransport._BaseCreateSupportEventSubscription._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.support_v2.SupportEventSubscriptionServiceClient.CreateSupportEventSubscription", + extra={ + "serviceName": "google.cloud.support.v2.SupportEventSubscriptionService", + "rpcName": "CreateSupportEventSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SupportEventSubscriptionServiceRestTransport._CreateSupportEventSubscription._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, 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_support_event_subscription.SupportEventSubscription() + pb_resp = gcs_support_event_subscription.SupportEventSubscription.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_support_event_subscription(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_create_support_event_subscription_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + gcs_support_event_subscription.SupportEventSubscription.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.support_v2.SupportEventSubscriptionServiceClient.create_support_event_subscription", + extra={ + "serviceName": "google.cloud.support.v2.SupportEventSubscriptionService", + "rpcName": "CreateSupportEventSubscription", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteSupportEventSubscription( + _BaseSupportEventSubscriptionServiceRestTransport._BaseDeleteSupportEventSubscription, + SupportEventSubscriptionServiceRestStub, + ): + def __hash__(self): + return hash( + "SupportEventSubscriptionServiceRestTransport.DeleteSupportEventSubscription" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: support_event_subscription_service.DeleteSupportEventSubscriptionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> support_event_subscription.SupportEventSubscription: + r"""Call the delete support event + subscription method over HTTP. + + Args: + request (~.support_event_subscription_service.DeleteSupportEventSubscriptionRequest): + The request object. Request message for + DeleteSupportEventSubscription. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.support_event_subscription.SupportEventSubscription: + A support event subscription. + """ + + http_options = _BaseSupportEventSubscriptionServiceRestTransport._BaseDeleteSupportEventSubscription._get_http_options() + + request, metadata = self._interceptor.pre_delete_support_event_subscription( + request, metadata + ) + transcoded_request = _BaseSupportEventSubscriptionServiceRestTransport._BaseDeleteSupportEventSubscription._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSupportEventSubscriptionServiceRestTransport._BaseDeleteSupportEventSubscription._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.support_v2.SupportEventSubscriptionServiceClient.DeleteSupportEventSubscription", + extra={ + "serviceName": "google.cloud.support.v2.SupportEventSubscriptionService", + "rpcName": "DeleteSupportEventSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SupportEventSubscriptionServiceRestTransport._DeleteSupportEventSubscription._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = support_event_subscription.SupportEventSubscription() + pb_resp = support_event_subscription.SupportEventSubscription.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_support_event_subscription(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_delete_support_event_subscription_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + support_event_subscription.SupportEventSubscription.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.support_v2.SupportEventSubscriptionServiceClient.delete_support_event_subscription", + extra={ + "serviceName": "google.cloud.support.v2.SupportEventSubscriptionService", + "rpcName": "DeleteSupportEventSubscription", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetSupportEventSubscription( + _BaseSupportEventSubscriptionServiceRestTransport._BaseGetSupportEventSubscription, + SupportEventSubscriptionServiceRestStub, + ): + def __hash__(self): + return hash( + "SupportEventSubscriptionServiceRestTransport.GetSupportEventSubscription" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: support_event_subscription_service.GetSupportEventSubscriptionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> support_event_subscription.SupportEventSubscription: + r"""Call the get support event + subscription method over HTTP. + + Args: + request (~.support_event_subscription_service.GetSupportEventSubscriptionRequest): + The request object. Request message for + GetSupportEventSubscription. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.support_event_subscription.SupportEventSubscription: + A support event subscription. + """ + + http_options = _BaseSupportEventSubscriptionServiceRestTransport._BaseGetSupportEventSubscription._get_http_options() + + request, metadata = self._interceptor.pre_get_support_event_subscription( + request, metadata + ) + transcoded_request = _BaseSupportEventSubscriptionServiceRestTransport._BaseGetSupportEventSubscription._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSupportEventSubscriptionServiceRestTransport._BaseGetSupportEventSubscription._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.support_v2.SupportEventSubscriptionServiceClient.GetSupportEventSubscription", + extra={ + "serviceName": "google.cloud.support.v2.SupportEventSubscriptionService", + "rpcName": "GetSupportEventSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SupportEventSubscriptionServiceRestTransport._GetSupportEventSubscription._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = support_event_subscription.SupportEventSubscription() + pb_resp = support_event_subscription.SupportEventSubscription.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_support_event_subscription(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_get_support_event_subscription_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + support_event_subscription.SupportEventSubscription.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.support_v2.SupportEventSubscriptionServiceClient.get_support_event_subscription", + extra={ + "serviceName": "google.cloud.support.v2.SupportEventSubscriptionService", + "rpcName": "GetSupportEventSubscription", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListSupportEventSubscriptions( + _BaseSupportEventSubscriptionServiceRestTransport._BaseListSupportEventSubscriptions, + SupportEventSubscriptionServiceRestStub, + ): + def __hash__(self): + return hash( + "SupportEventSubscriptionServiceRestTransport.ListSupportEventSubscriptions" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: support_event_subscription_service.ListSupportEventSubscriptionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> support_event_subscription_service.ListSupportEventSubscriptionsResponse: + r"""Call the list support event + subscriptions method over HTTP. + + Args: + request (~.support_event_subscription_service.ListSupportEventSubscriptionsRequest): + The request object. Request message for + ListSupportEventSubscriptions. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.support_event_subscription_service.ListSupportEventSubscriptionsResponse: + Response message for + ListSupportEventSubscriptions. + + """ + + http_options = _BaseSupportEventSubscriptionServiceRestTransport._BaseListSupportEventSubscriptions._get_http_options() + + request, metadata = self._interceptor.pre_list_support_event_subscriptions( + request, metadata + ) + transcoded_request = _BaseSupportEventSubscriptionServiceRestTransport._BaseListSupportEventSubscriptions._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSupportEventSubscriptionServiceRestTransport._BaseListSupportEventSubscriptions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.support_v2.SupportEventSubscriptionServiceClient.ListSupportEventSubscriptions", + extra={ + "serviceName": "google.cloud.support.v2.SupportEventSubscriptionService", + "rpcName": "ListSupportEventSubscriptions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SupportEventSubscriptionServiceRestTransport._ListSupportEventSubscriptions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = support_event_subscription_service.ListSupportEventSubscriptionsResponse() + pb_resp = support_event_subscription_service.ListSupportEventSubscriptionsResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_support_event_subscriptions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_list_support_event_subscriptions_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = support_event_subscription_service.ListSupportEventSubscriptionsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.support_v2.SupportEventSubscriptionServiceClient.list_support_event_subscriptions", + extra={ + "serviceName": "google.cloud.support.v2.SupportEventSubscriptionService", + "rpcName": "ListSupportEventSubscriptions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UndeleteSupportEventSubscription( + _BaseSupportEventSubscriptionServiceRestTransport._BaseUndeleteSupportEventSubscription, + SupportEventSubscriptionServiceRestStub, + ): + def __hash__(self): + return hash( + "SupportEventSubscriptionServiceRestTransport.UndeleteSupportEventSubscription" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: support_event_subscription_service.UndeleteSupportEventSubscriptionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> support_event_subscription.SupportEventSubscription: + r"""Call the undelete support event + subscription method over HTTP. + + Args: + request (~.support_event_subscription_service.UndeleteSupportEventSubscriptionRequest): + The request object. Request message for + UndeleteSupportEventSubscription. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.support_event_subscription.SupportEventSubscription: + A support event subscription. + """ + + http_options = _BaseSupportEventSubscriptionServiceRestTransport._BaseUndeleteSupportEventSubscription._get_http_options() + + request, metadata = ( + self._interceptor.pre_undelete_support_event_subscription( + request, metadata + ) + ) + transcoded_request = _BaseSupportEventSubscriptionServiceRestTransport._BaseUndeleteSupportEventSubscription._get_transcoded_request( + http_options, request + ) + + body = _BaseSupportEventSubscriptionServiceRestTransport._BaseUndeleteSupportEventSubscription._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSupportEventSubscriptionServiceRestTransport._BaseUndeleteSupportEventSubscription._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.support_v2.SupportEventSubscriptionServiceClient.UndeleteSupportEventSubscription", + extra={ + "serviceName": "google.cloud.support.v2.SupportEventSubscriptionService", + "rpcName": "UndeleteSupportEventSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SupportEventSubscriptionServiceRestTransport._UndeleteSupportEventSubscription._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = support_event_subscription.SupportEventSubscription() + pb_resp = support_event_subscription.SupportEventSubscription.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_undelete_support_event_subscription(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_undelete_support_event_subscription_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + support_event_subscription.SupportEventSubscription.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.support_v2.SupportEventSubscriptionServiceClient.undelete_support_event_subscription", + extra={ + "serviceName": "google.cloud.support.v2.SupportEventSubscriptionService", + "rpcName": "UndeleteSupportEventSubscription", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateSupportEventSubscription( + _BaseSupportEventSubscriptionServiceRestTransport._BaseUpdateSupportEventSubscription, + SupportEventSubscriptionServiceRestStub, + ): + def __hash__(self): + return hash( + "SupportEventSubscriptionServiceRestTransport.UpdateSupportEventSubscription" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: support_event_subscription_service.UpdateSupportEventSubscriptionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcs_support_event_subscription.SupportEventSubscription: + r"""Call the update support event + subscription method over HTTP. + + Args: + request (~.support_event_subscription_service.UpdateSupportEventSubscriptionRequest): + The request object. Request message for + UpdateSupportEventSubscription. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcs_support_event_subscription.SupportEventSubscription: + A support event subscription. + """ + + http_options = _BaseSupportEventSubscriptionServiceRestTransport._BaseUpdateSupportEventSubscription._get_http_options() + + request, metadata = self._interceptor.pre_update_support_event_subscription( + request, metadata + ) + transcoded_request = _BaseSupportEventSubscriptionServiceRestTransport._BaseUpdateSupportEventSubscription._get_transcoded_request( + http_options, request + ) + + body = _BaseSupportEventSubscriptionServiceRestTransport._BaseUpdateSupportEventSubscription._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSupportEventSubscriptionServiceRestTransport._BaseUpdateSupportEventSubscription._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.support_v2.SupportEventSubscriptionServiceClient.UpdateSupportEventSubscription", + extra={ + "serviceName": "google.cloud.support.v2.SupportEventSubscriptionService", + "rpcName": "UpdateSupportEventSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SupportEventSubscriptionServiceRestTransport._UpdateSupportEventSubscription._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, 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_support_event_subscription.SupportEventSubscription() + pb_resp = gcs_support_event_subscription.SupportEventSubscription.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_support_event_subscription(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_update_support_event_subscription_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + gcs_support_event_subscription.SupportEventSubscription.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.support_v2.SupportEventSubscriptionServiceClient.update_support_event_subscription", + extra={ + "serviceName": "google.cloud.support.v2.SupportEventSubscriptionService", + "rpcName": "UpdateSupportEventSubscription", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.CreateSupportEventSubscriptionRequest], + gcs_support_event_subscription.SupportEventSubscription, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSupportEventSubscription( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def delete_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.DeleteSupportEventSubscriptionRequest], + support_event_subscription.SupportEventSubscription, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteSupportEventSubscription( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.GetSupportEventSubscriptionRequest], + support_event_subscription.SupportEventSubscription, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSupportEventSubscription( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_support_event_subscriptions( + self, + ) -> Callable[ + [support_event_subscription_service.ListSupportEventSubscriptionsRequest], + support_event_subscription_service.ListSupportEventSubscriptionsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSupportEventSubscriptions( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def undelete_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.UndeleteSupportEventSubscriptionRequest], + support_event_subscription.SupportEventSubscription, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UndeleteSupportEventSubscription( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def update_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.UpdateSupportEventSubscriptionRequest], + gcs_support_event_subscription.SupportEventSubscription, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSupportEventSubscription( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("SupportEventSubscriptionServiceRestTransport",) diff --git a/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/rest_base.py b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/rest_base.py new file mode 100644 index 000000000000..939bf3c172c5 --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2/services/support_event_subscription_service/transports/rest_base.py @@ -0,0 +1,423 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.support_v2.types import ( + support_event_subscription, + support_event_subscription_service, +) +from google.cloud.support_v2.types import ( + support_event_subscription as gcs_support_event_subscription, +) + +from .base import DEFAULT_CLIENT_INFO, SupportEventSubscriptionServiceTransport + + +class _BaseSupportEventSubscriptionServiceRestTransport( + SupportEventSubscriptionServiceTransport +): + """Base REST backend transport for SupportEventSubscriptionService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "cloudsupport.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudsupport.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreateSupportEventSubscription: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=*/*}/supportEventSubscriptions", + "body": "support_event_subscription", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = support_event_subscription_service.CreateSupportEventSubscriptionRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSupportEventSubscriptionServiceRestTransport._BaseCreateSupportEventSubscription._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteSupportEventSubscription: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=*/*/supportEventSubscriptions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = support_event_subscription_service.DeleteSupportEventSubscriptionRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSupportEventSubscriptionServiceRestTransport._BaseDeleteSupportEventSubscription._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetSupportEventSubscription: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=*/*/supportEventSubscriptions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = support_event_subscription_service.GetSupportEventSubscriptionRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSupportEventSubscriptionServiceRestTransport._BaseGetSupportEventSubscription._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListSupportEventSubscriptions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=*/*}/supportEventSubscriptions", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = support_event_subscription_service.ListSupportEventSubscriptionsRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSupportEventSubscriptionServiceRestTransport._BaseListSupportEventSubscriptions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUndeleteSupportEventSubscription: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=*/*/supportEventSubscriptions/*}:undelete", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = support_event_subscription_service.UndeleteSupportEventSubscriptionRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSupportEventSubscriptionServiceRestTransport._BaseUndeleteSupportEventSubscription._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateSupportEventSubscription: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{support_event_subscription.name=*/*/supportEventSubscriptions/*}", + "body": "support_event_subscription", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = support_event_subscription_service.UpdateSupportEventSubscriptionRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSupportEventSubscriptionServiceRestTransport._BaseUpdateSupportEventSubscription._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BaseSupportEventSubscriptionServiceRestTransport",) diff --git a/packages/google-cloud-support/google/cloud/support_v2/types/__init__.py b/packages/google-cloud-support/google/cloud/support_v2/types/__init__.py index a3a0983bf28c..e534b045bb42 100644 --- a/packages/google-cloud-support/google/cloud/support_v2/types/__init__.py +++ b/packages/google-cloud-support/google/cloud/support_v2/types/__init__.py @@ -53,6 +53,18 @@ from .escalation import ( Escalation, ) +from .support_event_subscription import ( + SupportEventSubscription, +) +from .support_event_subscription_service import ( + CreateSupportEventSubscriptionRequest, + DeleteSupportEventSubscriptionRequest, + GetSupportEventSubscriptionRequest, + ListSupportEventSubscriptionsRequest, + ListSupportEventSubscriptionsResponse, + UndeleteSupportEventSubscriptionRequest, + UpdateSupportEventSubscriptionRequest, +) __all__ = ( "Actor", @@ -79,4 +91,12 @@ "ListCommentsRequest", "ListCommentsResponse", "Escalation", + "SupportEventSubscription", + "CreateSupportEventSubscriptionRequest", + "DeleteSupportEventSubscriptionRequest", + "GetSupportEventSubscriptionRequest", + "ListSupportEventSubscriptionsRequest", + "ListSupportEventSubscriptionsResponse", + "UndeleteSupportEventSubscriptionRequest", + "UpdateSupportEventSubscriptionRequest", ) diff --git a/packages/google-cloud-support/google/cloud/support_v2/types/case_service.py b/packages/google-cloud-support/google/cloud/support_v2/types/case_service.py index 3e61466f6d7d..297accfa8846 100644 --- a/packages/google-cloud-support/google/cloud/support_v2/types/case_service.py +++ b/packages/google-cloud-support/google/cloud/support_v2/types/case_service.py @@ -176,10 +176,6 @@ class SearchCasesRequest(proto.Message): Expressions use the following fields separated by ``AND`` and specified with ``=``: - - ``organization``: An organization name in the form - ``organizations/``. - - ``project``: A project name in the form - ``projects/``. - ``state``: Can be ``OPEN`` or ``CLOSED``. - ``priority``: Can be ``P0``, ``P1``, ``P2``, ``P3``, or ``P4``. You can specify multiple values for priority using @@ -187,8 +183,6 @@ class SearchCasesRequest(proto.Message): ``priority=P1 OR priority=P2``. - ``creator.email``: The email address of the case creator. - You must specify either ``organization`` or ``project``. - To search across ``displayName``, ``description``, and comments, use a global restriction with no keyword or operator. For example, ``"my search"``. @@ -199,8 +193,32 @@ class SearchCasesRequest(proto.Message): ``update_time>"2020-01-01T00:00:00-05:00"``. ``update_time`` only supports the greater than operator (``>``). + If you are using the ``v2`` version of the API, you must + specify the case parent in the ``parent`` field. If you + provide an empty ``query``, all cases under the parent + resource will be returned. + + If you are using the ``v2beta`` version of the API, you must + specify the case parent in the ``query`` field using one of + the two fields below, which are only available for + ``v2beta``. The ``parent`` field will be ignored. + + - ``organization``: An organization name in the form + ``organizations/``. + - ``project``: A project name in the form + ``projects/``. + Examples: + For ``v2``: + + - ``state=CLOSED`` + - ``state=OPEN AND creator.email="tester@example.com"`` + - ``state=OPEN AND (priority=P0 OR priority=P1)`` + - ``update_time>"2020-01-01T00:00:00-05:00"`` + + For ``v2beta``: + - ``organization="organizations/123456789"`` - ``project="projects/my-project-id"`` - ``project="projects/123456789"`` diff --git a/packages/google-cloud-support/google/cloud/support_v2/types/support_event_subscription.py b/packages/google-cloud-support/google/cloud/support_v2/types/support_event_subscription.py new file mode 100644 index 000000000000..6b49dd88d337 --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2/types/support_event_subscription.py @@ -0,0 +1,148 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.support.v2", + manifest={ + "SupportEventSubscription", + }, +) + + +class SupportEventSubscription(proto.Message): + r"""A support event subscription. + + Attributes: + name (str): + Identifier. The resource name of the support + event subscription. + pub_sub_topic (str): + Required. The name of the Pub/Sub topic to + publish notifications to. Format: + projects/{project}/topics/{topic} + state (google.cloud.support_v2.types.SupportEventSubscription.State): + Output only. The state of the subscription. + failure_reason (google.cloud.support_v2.types.SupportEventSubscription.FailureReason): + Output only. Reason why subscription is + failing. State of subscription must be FAILING + in order for this to have a value. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the + subscription was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the + subscription was last updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the + subscription was deleted. + purge_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the + subscription will be purged. + """ + + class State(proto.Enum): + r"""The state of the subscription. + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + WORKING (1): + Subscription is active and working. + FAILING (2): + Subscription is failing. Notifications cannot + be published for some reason. + DELETED (3): + Subscription has been deleted and is pending purge. + Notifications are not sent for deleted subscriptions. + Deleted subscriptions are purged after their ``purge_time`` + has passed. + """ + + STATE_UNSPECIFIED = 0 + WORKING = 1 + FAILING = 2 + DELETED = 3 + + class FailureReason(proto.Enum): + r"""The reason why the subscription is failing. + + Values: + FAILURE_REASON_UNSPECIFIED (0): + Unspecified failure reason. + PERMISSION_DENIED (1): + The service account (i.e. + cloud-support-apievents@system.gserviceaccount.com) + lacks the permission to publish to the + customer's Pub/Sub topic. + TOPIC_NOT_FOUND (2): + The specified Pub/Sub topic does not exist. + OTHER (3): + Message failed to publish due to a + system-side error. + """ + + FAILURE_REASON_UNSPECIFIED = 0 + PERMISSION_DENIED = 1 + TOPIC_NOT_FOUND = 2 + OTHER = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + pub_sub_topic: str = proto.Field( + proto.STRING, + number=2, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + failure_reason: FailureReason = proto.Field( + proto.ENUM, + number=4, + enum=FailureReason, + ) + 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, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + purge_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-support/google/cloud/support_v2/types/support_event_subscription_service.py b/packages/google-cloud-support/google/cloud/support_v2/types/support_event_subscription_service.py new file mode 100644 index 000000000000..c6bc6394e444 --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2/types/support_event_subscription_service.py @@ -0,0 +1,225 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.support_v2.types import ( + support_event_subscription as gcs_support_event_subscription, +) + +__protobuf__ = proto.module( + package="google.cloud.support.v2", + manifest={ + "CreateSupportEventSubscriptionRequest", + "GetSupportEventSubscriptionRequest", + "ListSupportEventSubscriptionsRequest", + "ListSupportEventSubscriptionsResponse", + "UpdateSupportEventSubscriptionRequest", + "DeleteSupportEventSubscriptionRequest", + "UndeleteSupportEventSubscriptionRequest", + }, +) + + +class CreateSupportEventSubscriptionRequest(proto.Message): + r"""Request message for CreateSupportEventSubscription. + + Attributes: + parent (str): + Required. The parent resource name where the support event + subscription will be created. Format: + organizations/{organization_id} + support_event_subscription (google.cloud.support_v2.types.SupportEventSubscription): + Required. The Pub/Sub configuration to + create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + support_event_subscription: gcs_support_event_subscription.SupportEventSubscription = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_support_event_subscription.SupportEventSubscription, + ) + + +class GetSupportEventSubscriptionRequest(proto.Message): + r"""Request message for GetSupportEventSubscription. + + Attributes: + name (str): + Required. The name of the support event subscription to + retrieve. Format: + organizations/{organization_id}/supportEventSubscriptions/{subscription_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSupportEventSubscriptionsRequest(proto.Message): + r"""Request message for ListSupportEventSubscriptions. + + Attributes: + parent (str): + Required. The fully qualified name of the Cloud resource to + list support event subscriptions under. Format: + organizations/{organization_id} + filter (str): + Optional. Filter expression based on AIP-160. Supported + fields: + + - pub_sub_topic + - state + + Examples: + + - ``pub_sub_topic="projects/example-project/topics/example-topic"`` + - ``state=WORKING`` + - ``pub_sub_topic="projects/example-project/topics/example-topic" AND state=WORKING`` + show_deleted (bool): + Optional. Whether to show deleted + subscriptions. By default, deleted subscriptions + are not returned. + page_size (int): + Optional. The maximum number of support event + subscriptions to return. + page_token (str): + Optional. A token identifying the page of results to return. + If unspecified, the first page is retrieved. + + When paginating, all other parameters provided to + ``ListSupportEventSubscriptions`` must match the call that + provided the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + show_deleted: bool = proto.Field( + proto.BOOL, + number=3, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListSupportEventSubscriptionsResponse(proto.Message): + r"""Response message for ListSupportEventSubscriptions. + + Attributes: + support_event_subscriptions (MutableSequence[google.cloud.support_v2.types.SupportEventSubscription]): + The support event subscriptions. + 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 + + support_event_subscriptions: MutableSequence[ + gcs_support_event_subscription.SupportEventSubscription + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_support_event_subscription.SupportEventSubscription, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateSupportEventSubscriptionRequest(proto.Message): + r"""Request message for UpdateSupportEventSubscription. + + Attributes: + support_event_subscription (google.cloud.support_v2.types.SupportEventSubscription): + Required. The support event subscription to update. The + ``name`` field is used to identify the configuration to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. The only supported + value is pub_sub_topic. + """ + + support_event_subscription: gcs_support_event_subscription.SupportEventSubscription = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_support_event_subscription.SupportEventSubscription, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteSupportEventSubscriptionRequest(proto.Message): + r"""Request message for DeleteSupportEventSubscription. + + Attributes: + name (str): + Required. The name of the support event subscription to + delete. Format: + organizations/{organization_id}/supportEventSubscriptions/{subscription_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UndeleteSupportEventSubscriptionRequest(proto.Message): + r"""Request message for UndeleteSupportEventSubscription. + + Attributes: + name (str): + Required. The name of the support event subscription to + undelete. Format: + organizations/{organization_id}/supportEventSubscriptions/{subscription_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-support/google/cloud/support_v2beta/__init__.py b/packages/google-cloud-support/google/cloud/support_v2beta/__init__.py index 23e7f9d851f1..d09fc1235100 100644 --- a/packages/google-cloud-support/google/cloud/support_v2beta/__init__.py +++ b/packages/google-cloud-support/google/cloud/support_v2beta/__init__.py @@ -30,6 +30,10 @@ from .services.case_service import CaseServiceAsyncClient, CaseServiceClient from .services.comment_service import CommentServiceAsyncClient, CommentServiceClient from .services.feed_service import FeedServiceAsyncClient, FeedServiceClient +from .services.support_event_subscription_service import ( + SupportEventSubscriptionServiceAsyncClient, + SupportEventSubscriptionServiceClient, +) from .types.actor import Actor from .types.attachment import Attachment from .types.attachment_service import ( @@ -63,6 +67,16 @@ from .types.escalation import Escalation from .types.feed_item import FeedItem from .types.feed_service import ShowFeedRequest, ShowFeedResponse +from .types.support_event_subscription import SupportEventSubscription +from .types.support_event_subscription_service import ( + CreateSupportEventSubscriptionRequest, + DeleteSupportEventSubscriptionRequest, + GetSupportEventSubscriptionRequest, + ListSupportEventSubscriptionsRequest, + ListSupportEventSubscriptionsResponse, + UndeleteSupportEventSubscriptionRequest, + UpdateSupportEventSubscriptionRequest, +) if hasattr(api_core, "check_python_version") and hasattr( api_core, "check_dependency_versions" @@ -152,6 +166,7 @@ def _get_version(dependency_name): "CaseServiceAsyncClient", "CommentServiceAsyncClient", "FeedServiceAsyncClient", + "SupportEventSubscriptionServiceAsyncClient", "Actor", "Attachment", "Case", @@ -163,6 +178,8 @@ def _get_version(dependency_name): "CommentServiceClient", "CreateCaseRequest", "CreateCommentRequest", + "CreateSupportEventSubscriptionRequest", + "DeleteSupportEventSubscriptionRequest", "EmailMessage", "EscalateCaseRequest", "Escalation", @@ -171,12 +188,15 @@ def _get_version(dependency_name): "GetAttachmentRequest", "GetCaseRequest", "GetCommentRequest", + "GetSupportEventSubscriptionRequest", "ListAttachmentsRequest", "ListAttachmentsResponse", "ListCasesRequest", "ListCasesResponse", "ListCommentsRequest", "ListCommentsResponse", + "ListSupportEventSubscriptionsRequest", + "ListSupportEventSubscriptionsResponse", "Product", "ProductLine", "SearchCaseClassificationsRequest", @@ -185,6 +205,10 @@ def _get_version(dependency_name): "SearchCasesResponse", "ShowFeedRequest", "ShowFeedResponse", + "SupportEventSubscription", + "SupportEventSubscriptionServiceClient", "TextContent", + "UndeleteSupportEventSubscriptionRequest", "UpdateCaseRequest", + "UpdateSupportEventSubscriptionRequest", ) diff --git a/packages/google-cloud-support/google/cloud/support_v2beta/gapic_metadata.json b/packages/google-cloud-support/google/cloud/support_v2beta/gapic_metadata.json index 5f39f97f1ce8..98b37c7681ad 100644 --- a/packages/google-cloud-support/google/cloud/support_v2beta/gapic_metadata.json +++ b/packages/google-cloud-support/google/cloud/support_v2beta/gapic_metadata.json @@ -290,6 +290,115 @@ } } } + }, + "SupportEventSubscriptionService": { + "clients": { + "grpc": { + "libraryClient": "SupportEventSubscriptionServiceClient", + "rpcs": { + "CreateSupportEventSubscription": { + "methods": [ + "create_support_event_subscription" + ] + }, + "DeleteSupportEventSubscription": { + "methods": [ + "delete_support_event_subscription" + ] + }, + "GetSupportEventSubscription": { + "methods": [ + "get_support_event_subscription" + ] + }, + "ListSupportEventSubscriptions": { + "methods": [ + "list_support_event_subscriptions" + ] + }, + "UndeleteSupportEventSubscription": { + "methods": [ + "undelete_support_event_subscription" + ] + }, + "UpdateSupportEventSubscription": { + "methods": [ + "update_support_event_subscription" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SupportEventSubscriptionServiceAsyncClient", + "rpcs": { + "CreateSupportEventSubscription": { + "methods": [ + "create_support_event_subscription" + ] + }, + "DeleteSupportEventSubscription": { + "methods": [ + "delete_support_event_subscription" + ] + }, + "GetSupportEventSubscription": { + "methods": [ + "get_support_event_subscription" + ] + }, + "ListSupportEventSubscriptions": { + "methods": [ + "list_support_event_subscriptions" + ] + }, + "UndeleteSupportEventSubscription": { + "methods": [ + "undelete_support_event_subscription" + ] + }, + "UpdateSupportEventSubscription": { + "methods": [ + "update_support_event_subscription" + ] + } + } + }, + "rest": { + "libraryClient": "SupportEventSubscriptionServiceClient", + "rpcs": { + "CreateSupportEventSubscription": { + "methods": [ + "create_support_event_subscription" + ] + }, + "DeleteSupportEventSubscription": { + "methods": [ + "delete_support_event_subscription" + ] + }, + "GetSupportEventSubscription": { + "methods": [ + "get_support_event_subscription" + ] + }, + "ListSupportEventSubscriptions": { + "methods": [ + "list_support_event_subscriptions" + ] + }, + "UndeleteSupportEventSubscription": { + "methods": [ + "undelete_support_event_subscription" + ] + }, + "UpdateSupportEventSubscription": { + "methods": [ + "update_support_event_subscription" + ] + } + } + } + } } } } diff --git a/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/__init__.py b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/__init__.py new file mode 100644 index 000000000000..e6fdafc1b99f --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import SupportEventSubscriptionServiceAsyncClient +from .client import SupportEventSubscriptionServiceClient + +__all__ = ( + "SupportEventSubscriptionServiceClient", + "SupportEventSubscriptionServiceAsyncClient", +) diff --git a/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/async_client.py b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/async_client.py new file mode 100644 index 000000000000..36e2f1a7b272 --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/async_client.py @@ -0,0 +1,1101 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.support_v2beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore + +from google.cloud.support_v2beta.services.support_event_subscription_service import ( + pagers, +) +from google.cloud.support_v2beta.types import ( + support_event_subscription, + support_event_subscription_service, +) +from google.cloud.support_v2beta.types import ( + support_event_subscription as gcs_support_event_subscription, +) + +from .client import SupportEventSubscriptionServiceClient +from .transports.base import ( + DEFAULT_CLIENT_INFO, + SupportEventSubscriptionServiceTransport, +) +from .transports.grpc_asyncio import SupportEventSubscriptionServiceGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class SupportEventSubscriptionServiceAsyncClient: + """Service for managing customer support event subscriptions.""" + + _client: SupportEventSubscriptionServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SupportEventSubscriptionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SupportEventSubscriptionServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ( + SupportEventSubscriptionServiceClient._DEFAULT_ENDPOINT_TEMPLATE + ) + _DEFAULT_UNIVERSE = SupportEventSubscriptionServiceClient._DEFAULT_UNIVERSE + + support_event_subscription_path = staticmethod( + SupportEventSubscriptionServiceClient.support_event_subscription_path + ) + parse_support_event_subscription_path = staticmethod( + SupportEventSubscriptionServiceClient.parse_support_event_subscription_path + ) + common_billing_account_path = staticmethod( + SupportEventSubscriptionServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + SupportEventSubscriptionServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + SupportEventSubscriptionServiceClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + SupportEventSubscriptionServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + SupportEventSubscriptionServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + SupportEventSubscriptionServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + SupportEventSubscriptionServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + SupportEventSubscriptionServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + SupportEventSubscriptionServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + SupportEventSubscriptionServiceClient.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: + SupportEventSubscriptionServiceAsyncClient: The constructed client. + """ + sa_info_func = ( + SupportEventSubscriptionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func( + SupportEventSubscriptionServiceAsyncClient, info, *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: + SupportEventSubscriptionServiceAsyncClient: The constructed client. + """ + sa_file_func = ( + SupportEventSubscriptionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func( + SupportEventSubscriptionServiceAsyncClient, filename, *args, **kwargs + ) + + 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 SupportEventSubscriptionServiceClient.get_mtls_endpoint_and_cert_source( + client_options + ) # type: ignore + + @property + def transport(self) -> SupportEventSubscriptionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SupportEventSubscriptionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """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 = SupportEventSubscriptionServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + SupportEventSubscriptionServiceTransport, + Callable[..., SupportEventSubscriptionServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the support event subscription service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SupportEventSubscriptionServiceTransport,Callable[..., SupportEventSubscriptionServiceTransport]]]): + 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 SupportEventSubscriptionServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = SupportEventSubscriptionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.support_v2beta.SupportEventSubscriptionServiceAsyncClient`.", + extra={ + "serviceName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "credentialsType": None, + }, + ) + + async def create_support_event_subscription( + self, + request: Optional[ + Union[ + support_event_subscription_service.CreateSupportEventSubscriptionRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + support_event_subscription: Optional[ + gcs_support_event_subscription.SupportEventSubscription + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcs_support_event_subscription.SupportEventSubscription: + r"""Creates a support event subscription 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 support_v2beta + + async def sample_create_support_event_subscription(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + support_event_subscription = support_v2beta.SupportEventSubscription() + support_event_subscription.pub_sub_topic = "pub_sub_topic_value" + + request = support_v2beta.CreateSupportEventSubscriptionRequest( + parent="parent_value", + support_event_subscription=support_event_subscription, + ) + + # Make the request + response = await client.create_support_event_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.support_v2beta.types.CreateSupportEventSubscriptionRequest, dict]]): + The request object. Request message for + CreateSupportEventSubscription. + parent (:class:`str`): + Required. The parent resource name where the support + event subscription will be created. Format: + organizations/{organization_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + support_event_subscription (:class:`google.cloud.support_v2beta.types.SupportEventSubscription`): + Required. The Pub/Sub configuration + to create. + + This corresponds to the ``support_event_subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2beta.types.SupportEventSubscription: + A support event subscription. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, support_event_subscription] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.CreateSupportEventSubscriptionRequest, + ): + request = support_event_subscription_service.CreateSupportEventSubscriptionRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if support_event_subscription is not None: + request.support_event_subscription = support_event_subscription + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_support_event_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_support_event_subscription( + self, + request: Optional[ + Union[ + support_event_subscription_service.GetSupportEventSubscriptionRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> support_event_subscription.SupportEventSubscription: + r"""Gets a support event subscription. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import support_v2beta + + async def sample_get_support_event_subscription(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + request = support_v2beta.GetSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_support_event_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.support_v2beta.types.GetSupportEventSubscriptionRequest, dict]]): + The request object. Request message for + GetSupportEventSubscription. + name (:class:`str`): + Required. The name of the support event subscription to + retrieve. Format: + organizations/{organization_id}/supportEventSubscriptions/{subscription_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2beta.types.SupportEventSubscription: + A support event subscription. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.GetSupportEventSubscriptionRequest, + ): + request = ( + support_event_subscription_service.GetSupportEventSubscriptionRequest( + request + ) + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_support_event_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_support_event_subscriptions( + self, + request: Optional[ + Union[ + support_event_subscription_service.ListSupportEventSubscriptionsRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSupportEventSubscriptionsAsyncPager: + r"""Lists support event subscriptions. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import support_v2beta + + async def sample_list_support_event_subscriptions(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + request = support_v2beta.ListSupportEventSubscriptionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_support_event_subscriptions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.support_v2beta.types.ListSupportEventSubscriptionsRequest, dict]]): + The request object. Request message for + ListSupportEventSubscriptions. + parent (:class:`str`): + Required. The fully qualified name of the Cloud resource + to list support event subscriptions under. Format: + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2beta.services.support_event_subscription_service.pagers.ListSupportEventSubscriptionsAsyncPager: + Response message for + ListSupportEventSubscriptions. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.ListSupportEventSubscriptionsRequest, + ): + request = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest( + request + ) + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = 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_support_event_subscriptions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSupportEventSubscriptionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_support_event_subscription( + self, + request: Optional[ + Union[ + support_event_subscription_service.UpdateSupportEventSubscriptionRequest, + dict, + ] + ] = None, + *, + support_event_subscription: Optional[ + gcs_support_event_subscription.SupportEventSubscription + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcs_support_event_subscription.SupportEventSubscription: + r"""Updates a support event subscription. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import support_v2beta + + async def sample_update_support_event_subscription(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + support_event_subscription = support_v2beta.SupportEventSubscription() + support_event_subscription.pub_sub_topic = "pub_sub_topic_value" + + request = support_v2beta.UpdateSupportEventSubscriptionRequest( + support_event_subscription=support_event_subscription, + ) + + # Make the request + response = await client.update_support_event_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.support_v2beta.types.UpdateSupportEventSubscriptionRequest, dict]]): + The request object. Request message for + UpdateSupportEventSubscription. + support_event_subscription (:class:`google.cloud.support_v2beta.types.SupportEventSubscription`): + Required. The support event subscription to update. The + ``name`` field is used to identify the configuration to + update. + + This corresponds to the ``support_event_subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The list of fields to update. The only + supported value is pub_sub_topic. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2beta.types.SupportEventSubscription: + A support event subscription. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [support_event_subscription, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.UpdateSupportEventSubscriptionRequest, + ): + request = support_event_subscription_service.UpdateSupportEventSubscriptionRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if support_event_subscription is not None: + request.support_event_subscription = support_event_subscription + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_support_event_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ( + "support_event_subscription.name", + request.support_event_subscription.name, + ), + ) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_support_event_subscription( + self, + request: Optional[ + Union[ + support_event_subscription_service.DeleteSupportEventSubscriptionRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> support_event_subscription.SupportEventSubscription: + r"""Soft deletes a support event subscription. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import support_v2beta + + async def sample_delete_support_event_subscription(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + request = support_v2beta.DeleteSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = await client.delete_support_event_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.support_v2beta.types.DeleteSupportEventSubscriptionRequest, dict]]): + The request object. Request message for + DeleteSupportEventSubscription. + name (:class:`str`): + Required. The name of the support event subscription to + delete. Format: + organizations/{organization_id}/supportEventSubscriptions/{subscription_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2beta.types.SupportEventSubscription: + A support event subscription. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.DeleteSupportEventSubscriptionRequest, + ): + request = support_event_subscription_service.DeleteSupportEventSubscriptionRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = 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_support_event_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def undelete_support_event_subscription( + self, + request: Optional[ + Union[ + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest, + dict, + ] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> support_event_subscription.SupportEventSubscription: + r"""Undeletes a support event subscription. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import support_v2beta + + async def sample_undelete_support_event_subscription(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + request = support_v2beta.UndeleteSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = await client.undelete_support_event_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.support_v2beta.types.UndeleteSupportEventSubscriptionRequest, dict]]): + The request object. Request message for + UndeleteSupportEventSubscription. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2beta.types.SupportEventSubscription: + A support event subscription. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest, + ): + request = support_event_subscription_service.UndeleteSupportEventSubscriptionRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.undelete_support_event_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "SupportEventSubscriptionServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("SupportEventSubscriptionServiceAsyncClient",) diff --git a/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/client.py b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/client.py new file mode 100644 index 000000000000..c2da8e38d069 --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/client.py @@ -0,0 +1,1535 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.support_v2beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore + +from google.cloud.support_v2beta.services.support_event_subscription_service import ( + pagers, +) +from google.cloud.support_v2beta.types import ( + support_event_subscription, + support_event_subscription_service, +) +from google.cloud.support_v2beta.types import ( + support_event_subscription as gcs_support_event_subscription, +) + +from .transports.base import ( + DEFAULT_CLIENT_INFO, + SupportEventSubscriptionServiceTransport, +) +from .transports.grpc import SupportEventSubscriptionServiceGrpcTransport +from .transports.grpc_asyncio import SupportEventSubscriptionServiceGrpcAsyncIOTransport +from .transports.rest import SupportEventSubscriptionServiceRestTransport + + +class SupportEventSubscriptionServiceClientMeta(type): + """Metaclass for the SupportEventSubscriptionService 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[SupportEventSubscriptionServiceTransport]] + _transport_registry["grpc"] = SupportEventSubscriptionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ( + SupportEventSubscriptionServiceGrpcAsyncIOTransport + ) + _transport_registry["rest"] = SupportEventSubscriptionServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[SupportEventSubscriptionServiceTransport]: + """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 SupportEventSubscriptionServiceClient( + metaclass=SupportEventSubscriptionServiceClientMeta +): + """Service for managing customer support event subscriptions.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """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: + Optional[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) + if m is None: + # Could not parse api_endpoint; return as-is. + return 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 = "cloudsupport.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "cloudsupport.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SupportEventSubscriptionServiceClient: 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: + SupportEventSubscriptionServiceClient: 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) -> SupportEventSubscriptionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SupportEventSubscriptionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def support_event_subscription_path( + organization: str, + support_event_subscription: str, + ) -> str: + """Returns a fully-qualified support_event_subscription string.""" + return "organizations/{organization}/supportEventSubscriptions/{support_event_subscription}".format( + organization=organization, + support_event_subscription=support_event_subscription, + ) + + @staticmethod + def parse_support_event_subscription_path(path: str) -> Dict[str, str]: + """Parses a support_event_subscription path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/supportEventSubscriptions/(?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 = ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + ) + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + 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: + 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 = ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + ) + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + 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, 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 + ) -> str: + """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 = SupportEventSubscriptionServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = SupportEventSubscriptionServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ( + SupportEventSubscriptionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.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 = SupportEventSubscriptionServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """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, + SupportEventSubscriptionServiceTransport, + Callable[..., SupportEventSubscriptionServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the support event subscription service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SupportEventSubscriptionServiceTransport,Callable[..., SupportEventSubscriptionServiceTransport]]]): + 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 SupportEventSubscriptionServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = ( + SupportEventSubscriptionServiceClient._read_environment_variables() + ) + self._client_cert_source = ( + SupportEventSubscriptionServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = ( + SupportEventSubscriptionServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance( + transport, SupportEventSubscriptionServiceTransport + ) + if transport_provided: + # transport is a SupportEventSubscriptionServiceTransport 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(SupportEventSubscriptionServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or SupportEventSubscriptionServiceClient._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[SupportEventSubscriptionServiceTransport], + Callable[..., SupportEventSubscriptionServiceTransport], + ] = ( + SupportEventSubscriptionServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast( + Callable[..., SupportEventSubscriptionServiceTransport], transport + ) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.support_v2beta.SupportEventSubscriptionServiceClient`.", + extra={ + "serviceName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "credentialsType": None, + }, + ) + + def create_support_event_subscription( + self, + request: Optional[ + Union[ + support_event_subscription_service.CreateSupportEventSubscriptionRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + support_event_subscription: Optional[ + gcs_support_event_subscription.SupportEventSubscription + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcs_support_event_subscription.SupportEventSubscription: + r"""Creates a support event subscription 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 support_v2beta + + def sample_create_support_event_subscription(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + support_event_subscription = support_v2beta.SupportEventSubscription() + support_event_subscription.pub_sub_topic = "pub_sub_topic_value" + + request = support_v2beta.CreateSupportEventSubscriptionRequest( + parent="parent_value", + support_event_subscription=support_event_subscription, + ) + + # Make the request + response = client.create_support_event_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.support_v2beta.types.CreateSupportEventSubscriptionRequest, dict]): + The request object. Request message for + CreateSupportEventSubscription. + parent (str): + Required. The parent resource name where the support + event subscription will be created. Format: + organizations/{organization_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + support_event_subscription (google.cloud.support_v2beta.types.SupportEventSubscription): + Required. The Pub/Sub configuration + to create. + + This corresponds to the ``support_event_subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2beta.types.SupportEventSubscription: + A support event subscription. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, support_event_subscription] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.CreateSupportEventSubscriptionRequest, + ): + request = support_event_subscription_service.CreateSupportEventSubscriptionRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if support_event_subscription is not None: + request.support_event_subscription = support_event_subscription + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_support_event_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_support_event_subscription( + self, + request: Optional[ + Union[ + support_event_subscription_service.GetSupportEventSubscriptionRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> support_event_subscription.SupportEventSubscription: + r"""Gets a support event subscription. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import support_v2beta + + def sample_get_support_event_subscription(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + request = support_v2beta.GetSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = client.get_support_event_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.support_v2beta.types.GetSupportEventSubscriptionRequest, dict]): + The request object. Request message for + GetSupportEventSubscription. + name (str): + Required. The name of the support event subscription to + retrieve. Format: + organizations/{organization_id}/supportEventSubscriptions/{subscription_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2beta.types.SupportEventSubscription: + A support event subscription. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.GetSupportEventSubscriptionRequest, + ): + request = ( + support_event_subscription_service.GetSupportEventSubscriptionRequest( + request + ) + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.get_support_event_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_support_event_subscriptions( + self, + request: Optional[ + Union[ + support_event_subscription_service.ListSupportEventSubscriptionsRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSupportEventSubscriptionsPager: + r"""Lists support event subscriptions. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import support_v2beta + + def sample_list_support_event_subscriptions(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + request = support_v2beta.ListSupportEventSubscriptionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_support_event_subscriptions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.support_v2beta.types.ListSupportEventSubscriptionsRequest, dict]): + The request object. Request message for + ListSupportEventSubscriptions. + parent (str): + Required. The fully qualified name of the Cloud resource + to list support event subscriptions under. Format: + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2beta.services.support_event_subscription_service.pagers.ListSupportEventSubscriptionsPager: + Response message for + ListSupportEventSubscriptions. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.ListSupportEventSubscriptionsRequest, + ): + request = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest( + request + ) + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + 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_support_event_subscriptions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSupportEventSubscriptionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_support_event_subscription( + self, + request: Optional[ + Union[ + support_event_subscription_service.UpdateSupportEventSubscriptionRequest, + dict, + ] + ] = None, + *, + support_event_subscription: Optional[ + gcs_support_event_subscription.SupportEventSubscription + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcs_support_event_subscription.SupportEventSubscription: + r"""Updates a support event subscription. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import support_v2beta + + def sample_update_support_event_subscription(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + support_event_subscription = support_v2beta.SupportEventSubscription() + support_event_subscription.pub_sub_topic = "pub_sub_topic_value" + + request = support_v2beta.UpdateSupportEventSubscriptionRequest( + support_event_subscription=support_event_subscription, + ) + + # Make the request + response = client.update_support_event_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.support_v2beta.types.UpdateSupportEventSubscriptionRequest, dict]): + The request object. Request message for + UpdateSupportEventSubscription. + support_event_subscription (google.cloud.support_v2beta.types.SupportEventSubscription): + Required. The support event subscription to update. The + ``name`` field is used to identify the configuration to + update. + + This corresponds to the ``support_event_subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. The only + supported value is pub_sub_topic. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2beta.types.SupportEventSubscription: + A support event subscription. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [support_event_subscription, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.UpdateSupportEventSubscriptionRequest, + ): + request = support_event_subscription_service.UpdateSupportEventSubscriptionRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if support_event_subscription is not None: + request.support_event_subscription = support_event_subscription + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_support_event_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ( + "support_event_subscription.name", + request.support_event_subscription.name, + ), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_support_event_subscription( + self, + request: Optional[ + Union[ + support_event_subscription_service.DeleteSupportEventSubscriptionRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> support_event_subscription.SupportEventSubscription: + r"""Soft deletes a support event subscription. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import support_v2beta + + def sample_delete_support_event_subscription(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + request = support_v2beta.DeleteSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = client.delete_support_event_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.support_v2beta.types.DeleteSupportEventSubscriptionRequest, dict]): + The request object. Request message for + DeleteSupportEventSubscription. + name (str): + Required. The name of the support event subscription to + delete. Format: + organizations/{organization_id}/supportEventSubscriptions/{subscription_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2beta.types.SupportEventSubscription: + A support event subscription. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.DeleteSupportEventSubscriptionRequest, + ): + request = support_event_subscription_service.DeleteSupportEventSubscriptionRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_support_event_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def undelete_support_event_subscription( + self, + request: Optional[ + Union[ + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest, + dict, + ] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> support_event_subscription.SupportEventSubscription: + r"""Undeletes a support event subscription. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import support_v2beta + + def sample_undelete_support_event_subscription(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + request = support_v2beta.UndeleteSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = client.undelete_support_event_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.support_v2beta.types.UndeleteSupportEventSubscriptionRequest, dict]): + The request object. Request message for + UndeleteSupportEventSubscription. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.support_v2beta.types.SupportEventSubscription: + A support event subscription. + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest, + ): + request = support_event_subscription_service.UndeleteSupportEventSubscriptionRequest( + request + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.undelete_support_event_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SupportEventSubscriptionServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("SupportEventSubscriptionServiceClient",) diff --git a/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/pagers.py b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/pagers.py new file mode 100644 index 000000000000..a666a0e76dc0 --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/pagers.py @@ -0,0 +1,226 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +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.support_v2beta.types import ( + support_event_subscription, + support_event_subscription_service, +) + + +class ListSupportEventSubscriptionsPager: + """A pager for iterating through ``list_support_event_subscriptions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.support_v2beta.types.ListSupportEventSubscriptionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``support_event_subscriptions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSupportEventSubscriptions`` requests and continue to iterate + through the ``support_event_subscriptions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.support_v2beta.types.ListSupportEventSubscriptionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., + support_event_subscription_service.ListSupportEventSubscriptionsResponse, + ], + request: support_event_subscription_service.ListSupportEventSubscriptionsRequest, + response: support_event_subscription_service.ListSupportEventSubscriptionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.support_v2beta.types.ListSupportEventSubscriptionsRequest): + The initial request object. + response (google.cloud.support_v2beta.types.ListSupportEventSubscriptionsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest( + request + ) + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[ + support_event_subscription_service.ListSupportEventSubscriptionsResponse + ]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[support_event_subscription.SupportEventSubscription]: + for page in self.pages: + yield from page.support_event_subscriptions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSupportEventSubscriptionsAsyncPager: + """A pager for iterating through ``list_support_event_subscriptions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.support_v2beta.types.ListSupportEventSubscriptionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``support_event_subscriptions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSupportEventSubscriptions`` requests and continue to iterate + through the ``support_event_subscriptions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.support_v2beta.types.ListSupportEventSubscriptionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., + Awaitable[ + support_event_subscription_service.ListSupportEventSubscriptionsResponse + ], + ], + request: support_event_subscription_service.ListSupportEventSubscriptionsRequest, + response: support_event_subscription_service.ListSupportEventSubscriptionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.support_v2beta.types.ListSupportEventSubscriptionsRequest): + The initial request object. + response (google.cloud.support_v2beta.types.ListSupportEventSubscriptionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest( + request + ) + ) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[ + support_event_subscription_service.ListSupportEventSubscriptionsResponse + ]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__( + self, + ) -> AsyncIterator[support_event_subscription.SupportEventSubscription]: + async def async_generator(): + async for page in self.pages: + for response in page.support_event_subscriptions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/README.rst b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/README.rst new file mode 100644 index 000000000000..a0df103b1167 --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``SupportEventSubscriptionServiceTransport`` is the ABC for all transports. + +- public child ``SupportEventSubscriptionServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``SupportEventSubscriptionServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseSupportEventSubscriptionServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``SupportEventSubscriptionServiceRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/__init__.py b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/__init__.py new file mode 100644 index 000000000000..975841d1831c --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/__init__.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 SupportEventSubscriptionServiceTransport +from .grpc import SupportEventSubscriptionServiceGrpcTransport +from .grpc_asyncio import SupportEventSubscriptionServiceGrpcAsyncIOTransport +from .rest import ( + SupportEventSubscriptionServiceRestInterceptor, + SupportEventSubscriptionServiceRestTransport, +) + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SupportEventSubscriptionServiceTransport]] +_transport_registry["grpc"] = SupportEventSubscriptionServiceGrpcTransport +_transport_registry["grpc_asyncio"] = ( + SupportEventSubscriptionServiceGrpcAsyncIOTransport +) +_transport_registry["rest"] = SupportEventSubscriptionServiceRestTransport + +__all__ = ( + "SupportEventSubscriptionServiceTransport", + "SupportEventSubscriptionServiceGrpcTransport", + "SupportEventSubscriptionServiceGrpcAsyncIOTransport", + "SupportEventSubscriptionServiceRestTransport", + "SupportEventSubscriptionServiceRestInterceptor", +) diff --git a/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/base.py b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/base.py new file mode 100644 index 000000000000..530a48538e47 --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/base.py @@ -0,0 +1,271 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.support_v2beta import gapic_version as package_version +from google.cloud.support_v2beta.types import ( + support_event_subscription, + support_event_subscription_service, +) +from google.cloud.support_v2beta.types import ( + support_event_subscription as gcs_support_event_subscription, +) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class SupportEventSubscriptionServiceTransport(abc.ABC): + """Abstract transport class for SupportEventSubscriptionService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "cloudsupport.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.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: 'cloudsupport.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # 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=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_support_event_subscription: gapic_v1.method.wrap_method( + self.create_support_event_subscription, + default_timeout=None, + client_info=client_info, + ), + self.get_support_event_subscription: gapic_v1.method.wrap_method( + self.get_support_event_subscription, + default_timeout=None, + client_info=client_info, + ), + self.list_support_event_subscriptions: gapic_v1.method.wrap_method( + self.list_support_event_subscriptions, + default_timeout=None, + client_info=client_info, + ), + self.update_support_event_subscription: gapic_v1.method.wrap_method( + self.update_support_event_subscription, + default_timeout=None, + client_info=client_info, + ), + self.delete_support_event_subscription: gapic_v1.method.wrap_method( + self.delete_support_event_subscription, + default_timeout=None, + client_info=client_info, + ), + self.undelete_support_event_subscription: gapic_v1.method.wrap_method( + self.undelete_support_event_subscription, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.CreateSupportEventSubscriptionRequest], + Union[ + gcs_support_event_subscription.SupportEventSubscription, + Awaitable[gcs_support_event_subscription.SupportEventSubscription], + ], + ]: + raise NotImplementedError() + + @property + def get_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.GetSupportEventSubscriptionRequest], + Union[ + support_event_subscription.SupportEventSubscription, + Awaitable[support_event_subscription.SupportEventSubscription], + ], + ]: + raise NotImplementedError() + + @property + def list_support_event_subscriptions( + self, + ) -> Callable[ + [support_event_subscription_service.ListSupportEventSubscriptionsRequest], + Union[ + support_event_subscription_service.ListSupportEventSubscriptionsResponse, + Awaitable[ + support_event_subscription_service.ListSupportEventSubscriptionsResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def update_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.UpdateSupportEventSubscriptionRequest], + Union[ + gcs_support_event_subscription.SupportEventSubscription, + Awaitable[gcs_support_event_subscription.SupportEventSubscription], + ], + ]: + raise NotImplementedError() + + @property + def delete_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.DeleteSupportEventSubscriptionRequest], + Union[ + support_event_subscription.SupportEventSubscription, + Awaitable[support_event_subscription.SupportEventSubscription], + ], + ]: + raise NotImplementedError() + + @property + def undelete_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.UndeleteSupportEventSubscriptionRequest], + Union[ + support_event_subscription.SupportEventSubscription, + Awaitable[support_event_subscription.SupportEventSubscription], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("SupportEventSubscriptionServiceTransport",) diff --git a/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/grpc.py b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/grpc.py new file mode 100644 index 000000000000..1e374bb41721 --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/grpc.py @@ -0,0 +1,536 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.support_v2beta.types import ( + support_event_subscription, + support_event_subscription_service, +) +from google.cloud.support_v2beta.types import ( + support_event_subscription as gcs_support_event_subscription, +) + +from .base import DEFAULT_CLIENT_INFO, SupportEventSubscriptionServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SupportEventSubscriptionServiceGrpcTransport( + SupportEventSubscriptionServiceTransport +): + """gRPC backend transport for SupportEventSubscriptionService. + + Service for managing customer support event subscriptions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = "cloudsupport.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudsupport.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "cloudsupport.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def create_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.CreateSupportEventSubscriptionRequest], + gcs_support_event_subscription.SupportEventSubscription, + ]: + r"""Return a callable for the create support event + subscription method over gRPC. + + Creates a support event subscription for an + organization. + + Returns: + Callable[[~.CreateSupportEventSubscriptionRequest], + ~.SupportEventSubscription]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_support_event_subscription" not in self._stubs: + self._stubs["create_support_event_subscription"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2beta.SupportEventSubscriptionService/CreateSupportEventSubscription", + request_serializer=support_event_subscription_service.CreateSupportEventSubscriptionRequest.serialize, + response_deserializer=gcs_support_event_subscription.SupportEventSubscription.deserialize, + ) + ) + return self._stubs["create_support_event_subscription"] + + @property + def get_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.GetSupportEventSubscriptionRequest], + support_event_subscription.SupportEventSubscription, + ]: + r"""Return a callable for the get support event subscription method over gRPC. + + Gets a support event subscription. + + Returns: + Callable[[~.GetSupportEventSubscriptionRequest], + ~.SupportEventSubscription]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_support_event_subscription" not in self._stubs: + self._stubs["get_support_event_subscription"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2beta.SupportEventSubscriptionService/GetSupportEventSubscription", + request_serializer=support_event_subscription_service.GetSupportEventSubscriptionRequest.serialize, + response_deserializer=support_event_subscription.SupportEventSubscription.deserialize, + ) + ) + return self._stubs["get_support_event_subscription"] + + @property + def list_support_event_subscriptions( + self, + ) -> Callable[ + [support_event_subscription_service.ListSupportEventSubscriptionsRequest], + support_event_subscription_service.ListSupportEventSubscriptionsResponse, + ]: + r"""Return a callable for the list support event + subscriptions method over gRPC. + + Lists support event subscriptions. + + Returns: + Callable[[~.ListSupportEventSubscriptionsRequest], + ~.ListSupportEventSubscriptionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_support_event_subscriptions" not in self._stubs: + self._stubs["list_support_event_subscriptions"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2beta.SupportEventSubscriptionService/ListSupportEventSubscriptions", + request_serializer=support_event_subscription_service.ListSupportEventSubscriptionsRequest.serialize, + response_deserializer=support_event_subscription_service.ListSupportEventSubscriptionsResponse.deserialize, + ) + ) + return self._stubs["list_support_event_subscriptions"] + + @property + def update_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.UpdateSupportEventSubscriptionRequest], + gcs_support_event_subscription.SupportEventSubscription, + ]: + r"""Return a callable for the update support event + subscription method over gRPC. + + Updates a support event subscription. + + Returns: + Callable[[~.UpdateSupportEventSubscriptionRequest], + ~.SupportEventSubscription]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_support_event_subscription" not in self._stubs: + self._stubs["update_support_event_subscription"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2beta.SupportEventSubscriptionService/UpdateSupportEventSubscription", + request_serializer=support_event_subscription_service.UpdateSupportEventSubscriptionRequest.serialize, + response_deserializer=gcs_support_event_subscription.SupportEventSubscription.deserialize, + ) + ) + return self._stubs["update_support_event_subscription"] + + @property + def delete_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.DeleteSupportEventSubscriptionRequest], + support_event_subscription.SupportEventSubscription, + ]: + r"""Return a callable for the delete support event + subscription method over gRPC. + + Soft deletes a support event subscription. + + Returns: + Callable[[~.DeleteSupportEventSubscriptionRequest], + ~.SupportEventSubscription]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_support_event_subscription" not in self._stubs: + self._stubs["delete_support_event_subscription"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2beta.SupportEventSubscriptionService/DeleteSupportEventSubscription", + request_serializer=support_event_subscription_service.DeleteSupportEventSubscriptionRequest.serialize, + response_deserializer=support_event_subscription.SupportEventSubscription.deserialize, + ) + ) + return self._stubs["delete_support_event_subscription"] + + @property + def undelete_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.UndeleteSupportEventSubscriptionRequest], + support_event_subscription.SupportEventSubscription, + ]: + r"""Return a callable for the undelete support event + subscription method over gRPC. + + Undeletes a support event subscription. + + Returns: + Callable[[~.UndeleteSupportEventSubscriptionRequest], + ~.SupportEventSubscription]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "undelete_support_event_subscription" not in self._stubs: + self._stubs["undelete_support_event_subscription"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2beta.SupportEventSubscriptionService/UndeleteSupportEventSubscription", + request_serializer=support_event_subscription_service.UndeleteSupportEventSubscriptionRequest.serialize, + response_deserializer=support_event_subscription.SupportEventSubscription.deserialize, + ) + ) + return self._stubs["undelete_support_event_subscription"] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("SupportEventSubscriptionServiceGrpcTransport",) diff --git a/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/grpc_asyncio.py b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..2cb8119adbed --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/grpc_asyncio.py @@ -0,0 +1,586 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.support_v2beta.types import ( + support_event_subscription, + support_event_subscription_service, +) +from google.cloud.support_v2beta.types import ( + support_event_subscription as gcs_support_event_subscription, +) + +from .base import DEFAULT_CLIENT_INFO, SupportEventSubscriptionServiceTransport +from .grpc import SupportEventSubscriptionServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SupportEventSubscriptionServiceGrpcAsyncIOTransport( + SupportEventSubscriptionServiceTransport +): + """gRPC AsyncIO backend transport for SupportEventSubscriptionService. + + Service for managing customer support event subscriptions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = "cloudsupport.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (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 = "cloudsupport.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudsupport.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.CreateSupportEventSubscriptionRequest], + Awaitable[gcs_support_event_subscription.SupportEventSubscription], + ]: + r"""Return a callable for the create support event + subscription method over gRPC. + + Creates a support event subscription for an + organization. + + Returns: + Callable[[~.CreateSupportEventSubscriptionRequest], + Awaitable[~.SupportEventSubscription]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_support_event_subscription" not in self._stubs: + self._stubs["create_support_event_subscription"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2beta.SupportEventSubscriptionService/CreateSupportEventSubscription", + request_serializer=support_event_subscription_service.CreateSupportEventSubscriptionRequest.serialize, + response_deserializer=gcs_support_event_subscription.SupportEventSubscription.deserialize, + ) + ) + return self._stubs["create_support_event_subscription"] + + @property + def get_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.GetSupportEventSubscriptionRequest], + Awaitable[support_event_subscription.SupportEventSubscription], + ]: + r"""Return a callable for the get support event subscription method over gRPC. + + Gets a support event subscription. + + Returns: + Callable[[~.GetSupportEventSubscriptionRequest], + Awaitable[~.SupportEventSubscription]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_support_event_subscription" not in self._stubs: + self._stubs["get_support_event_subscription"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2beta.SupportEventSubscriptionService/GetSupportEventSubscription", + request_serializer=support_event_subscription_service.GetSupportEventSubscriptionRequest.serialize, + response_deserializer=support_event_subscription.SupportEventSubscription.deserialize, + ) + ) + return self._stubs["get_support_event_subscription"] + + @property + def list_support_event_subscriptions( + self, + ) -> Callable[ + [support_event_subscription_service.ListSupportEventSubscriptionsRequest], + Awaitable[ + support_event_subscription_service.ListSupportEventSubscriptionsResponse + ], + ]: + r"""Return a callable for the list support event + subscriptions method over gRPC. + + Lists support event subscriptions. + + Returns: + Callable[[~.ListSupportEventSubscriptionsRequest], + Awaitable[~.ListSupportEventSubscriptionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_support_event_subscriptions" not in self._stubs: + self._stubs["list_support_event_subscriptions"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2beta.SupportEventSubscriptionService/ListSupportEventSubscriptions", + request_serializer=support_event_subscription_service.ListSupportEventSubscriptionsRequest.serialize, + response_deserializer=support_event_subscription_service.ListSupportEventSubscriptionsResponse.deserialize, + ) + ) + return self._stubs["list_support_event_subscriptions"] + + @property + def update_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.UpdateSupportEventSubscriptionRequest], + Awaitable[gcs_support_event_subscription.SupportEventSubscription], + ]: + r"""Return a callable for the update support event + subscription method over gRPC. + + Updates a support event subscription. + + Returns: + Callable[[~.UpdateSupportEventSubscriptionRequest], + Awaitable[~.SupportEventSubscription]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_support_event_subscription" not in self._stubs: + self._stubs["update_support_event_subscription"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2beta.SupportEventSubscriptionService/UpdateSupportEventSubscription", + request_serializer=support_event_subscription_service.UpdateSupportEventSubscriptionRequest.serialize, + response_deserializer=gcs_support_event_subscription.SupportEventSubscription.deserialize, + ) + ) + return self._stubs["update_support_event_subscription"] + + @property + def delete_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.DeleteSupportEventSubscriptionRequest], + Awaitable[support_event_subscription.SupportEventSubscription], + ]: + r"""Return a callable for the delete support event + subscription method over gRPC. + + Soft deletes a support event subscription. + + Returns: + Callable[[~.DeleteSupportEventSubscriptionRequest], + Awaitable[~.SupportEventSubscription]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_support_event_subscription" not in self._stubs: + self._stubs["delete_support_event_subscription"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2beta.SupportEventSubscriptionService/DeleteSupportEventSubscription", + request_serializer=support_event_subscription_service.DeleteSupportEventSubscriptionRequest.serialize, + response_deserializer=support_event_subscription.SupportEventSubscription.deserialize, + ) + ) + return self._stubs["delete_support_event_subscription"] + + @property + def undelete_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.UndeleteSupportEventSubscriptionRequest], + Awaitable[support_event_subscription.SupportEventSubscription], + ]: + r"""Return a callable for the undelete support event + subscription method over gRPC. + + Undeletes a support event subscription. + + Returns: + Callable[[~.UndeleteSupportEventSubscriptionRequest], + Awaitable[~.SupportEventSubscription]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "undelete_support_event_subscription" not in self._stubs: + self._stubs["undelete_support_event_subscription"] = ( + self._logged_channel.unary_unary( + "/google.cloud.support.v2beta.SupportEventSubscriptionService/UndeleteSupportEventSubscription", + request_serializer=support_event_subscription_service.UndeleteSupportEventSubscriptionRequest.serialize, + response_deserializer=support_event_subscription.SupportEventSubscription.deserialize, + ) + ) + return self._stubs["undelete_support_event_subscription"] + + 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_support_event_subscription: self._wrap_method( + self.create_support_event_subscription, + default_timeout=None, + client_info=client_info, + ), + self.get_support_event_subscription: self._wrap_method( + self.get_support_event_subscription, + default_timeout=None, + client_info=client_info, + ), + self.list_support_event_subscriptions: self._wrap_method( + self.list_support_event_subscriptions, + default_timeout=None, + client_info=client_info, + ), + self.update_support_event_subscription: self._wrap_method( + self.update_support_event_subscription, + default_timeout=None, + client_info=client_info, + ), + self.delete_support_event_subscription: self._wrap_method( + self.delete_support_event_subscription, + default_timeout=None, + client_info=client_info, + ), + self.undelete_support_event_subscription: self._wrap_method( + self.undelete_support_event_subscription, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ("SupportEventSubscriptionServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/rest.py b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/rest.py new file mode 100644 index 000000000000..319b226908f8 --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/rest.py @@ -0,0 +1,1584 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.support_v2beta.types import ( + support_event_subscription, + support_event_subscription_service, +) +from google.cloud.support_v2beta.types import ( + support_event_subscription as gcs_support_event_subscription, +) + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseSupportEventSubscriptionServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class SupportEventSubscriptionServiceRestInterceptor: + """Interceptor for SupportEventSubscriptionService. + + 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 SupportEventSubscriptionServiceRestTransport. + + .. code-block:: python + class MyCustomSupportEventSubscriptionServiceInterceptor(SupportEventSubscriptionServiceRestInterceptor): + def pre_create_support_event_subscription(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_support_event_subscription(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_support_event_subscription(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_support_event_subscription(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_support_event_subscription(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_support_event_subscription(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_support_event_subscriptions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_support_event_subscriptions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_undelete_support_event_subscription(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_undelete_support_event_subscription(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_support_event_subscription(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_support_event_subscription(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SupportEventSubscriptionServiceRestTransport(interceptor=MyCustomSupportEventSubscriptionServiceInterceptor()) + client = SupportEventSubscriptionServiceClient(transport=transport) + + + """ + + def pre_create_support_event_subscription( + self, + request: support_event_subscription_service.CreateSupportEventSubscriptionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + support_event_subscription_service.CreateSupportEventSubscriptionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_support_event_subscription + + Override in a subclass to manipulate the request or metadata + before they are sent to the SupportEventSubscriptionService server. + """ + return request, metadata + + def post_create_support_event_subscription( + self, response: gcs_support_event_subscription.SupportEventSubscription + ) -> gcs_support_event_subscription.SupportEventSubscription: + """Post-rpc interceptor for create_support_event_subscription + + DEPRECATED. Please use the `post_create_support_event_subscription_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SupportEventSubscriptionService server but before + it is returned to user code. This `post_create_support_event_subscription` interceptor runs + before the `post_create_support_event_subscription_with_metadata` interceptor. + """ + return response + + def post_create_support_event_subscription_with_metadata( + self, + response: gcs_support_event_subscription.SupportEventSubscription, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcs_support_event_subscription.SupportEventSubscription, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for create_support_event_subscription + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SupportEventSubscriptionService server but before it is returned to user code. + + We recommend only using this `post_create_support_event_subscription_with_metadata` + interceptor in new development instead of the `post_create_support_event_subscription` interceptor. + When both interceptors are used, this `post_create_support_event_subscription_with_metadata` interceptor runs after the + `post_create_support_event_subscription` interceptor. The (possibly modified) response returned by + `post_create_support_event_subscription` will be passed to + `post_create_support_event_subscription_with_metadata`. + """ + return response, metadata + + def pre_delete_support_event_subscription( + self, + request: support_event_subscription_service.DeleteSupportEventSubscriptionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + support_event_subscription_service.DeleteSupportEventSubscriptionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_support_event_subscription + + Override in a subclass to manipulate the request or metadata + before they are sent to the SupportEventSubscriptionService server. + """ + return request, metadata + + def post_delete_support_event_subscription( + self, response: support_event_subscription.SupportEventSubscription + ) -> support_event_subscription.SupportEventSubscription: + """Post-rpc interceptor for delete_support_event_subscription + + DEPRECATED. Please use the `post_delete_support_event_subscription_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SupportEventSubscriptionService server but before + it is returned to user code. This `post_delete_support_event_subscription` interceptor runs + before the `post_delete_support_event_subscription_with_metadata` interceptor. + """ + return response + + def post_delete_support_event_subscription_with_metadata( + self, + response: support_event_subscription.SupportEventSubscription, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + support_event_subscription.SupportEventSubscription, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for delete_support_event_subscription + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SupportEventSubscriptionService server but before it is returned to user code. + + We recommend only using this `post_delete_support_event_subscription_with_metadata` + interceptor in new development instead of the `post_delete_support_event_subscription` interceptor. + When both interceptors are used, this `post_delete_support_event_subscription_with_metadata` interceptor runs after the + `post_delete_support_event_subscription` interceptor. The (possibly modified) response returned by + `post_delete_support_event_subscription` will be passed to + `post_delete_support_event_subscription_with_metadata`. + """ + return response, metadata + + def pre_get_support_event_subscription( + self, + request: support_event_subscription_service.GetSupportEventSubscriptionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + support_event_subscription_service.GetSupportEventSubscriptionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_support_event_subscription + + Override in a subclass to manipulate the request or metadata + before they are sent to the SupportEventSubscriptionService server. + """ + return request, metadata + + def post_get_support_event_subscription( + self, response: support_event_subscription.SupportEventSubscription + ) -> support_event_subscription.SupportEventSubscription: + """Post-rpc interceptor for get_support_event_subscription + + DEPRECATED. Please use the `post_get_support_event_subscription_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SupportEventSubscriptionService server but before + it is returned to user code. This `post_get_support_event_subscription` interceptor runs + before the `post_get_support_event_subscription_with_metadata` interceptor. + """ + return response + + def post_get_support_event_subscription_with_metadata( + self, + response: support_event_subscription.SupportEventSubscription, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + support_event_subscription.SupportEventSubscription, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_support_event_subscription + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SupportEventSubscriptionService server but before it is returned to user code. + + We recommend only using this `post_get_support_event_subscription_with_metadata` + interceptor in new development instead of the `post_get_support_event_subscription` interceptor. + When both interceptors are used, this `post_get_support_event_subscription_with_metadata` interceptor runs after the + `post_get_support_event_subscription` interceptor. The (possibly modified) response returned by + `post_get_support_event_subscription` will be passed to + `post_get_support_event_subscription_with_metadata`. + """ + return response, metadata + + def pre_list_support_event_subscriptions( + self, + request: support_event_subscription_service.ListSupportEventSubscriptionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + support_event_subscription_service.ListSupportEventSubscriptionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_support_event_subscriptions + + Override in a subclass to manipulate the request or metadata + before they are sent to the SupportEventSubscriptionService server. + """ + return request, metadata + + def post_list_support_event_subscriptions( + self, + response: support_event_subscription_service.ListSupportEventSubscriptionsResponse, + ) -> support_event_subscription_service.ListSupportEventSubscriptionsResponse: + """Post-rpc interceptor for list_support_event_subscriptions + + DEPRECATED. Please use the `post_list_support_event_subscriptions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SupportEventSubscriptionService server but before + it is returned to user code. This `post_list_support_event_subscriptions` interceptor runs + before the `post_list_support_event_subscriptions_with_metadata` interceptor. + """ + return response + + def post_list_support_event_subscriptions_with_metadata( + self, + response: support_event_subscription_service.ListSupportEventSubscriptionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + support_event_subscription_service.ListSupportEventSubscriptionsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_support_event_subscriptions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SupportEventSubscriptionService server but before it is returned to user code. + + We recommend only using this `post_list_support_event_subscriptions_with_metadata` + interceptor in new development instead of the `post_list_support_event_subscriptions` interceptor. + When both interceptors are used, this `post_list_support_event_subscriptions_with_metadata` interceptor runs after the + `post_list_support_event_subscriptions` interceptor. The (possibly modified) response returned by + `post_list_support_event_subscriptions` will be passed to + `post_list_support_event_subscriptions_with_metadata`. + """ + return response, metadata + + def pre_undelete_support_event_subscription( + self, + request: support_event_subscription_service.UndeleteSupportEventSubscriptionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for undelete_support_event_subscription + + Override in a subclass to manipulate the request or metadata + before they are sent to the SupportEventSubscriptionService server. + """ + return request, metadata + + def post_undelete_support_event_subscription( + self, response: support_event_subscription.SupportEventSubscription + ) -> support_event_subscription.SupportEventSubscription: + """Post-rpc interceptor for undelete_support_event_subscription + + DEPRECATED. Please use the `post_undelete_support_event_subscription_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SupportEventSubscriptionService server but before + it is returned to user code. This `post_undelete_support_event_subscription` interceptor runs + before the `post_undelete_support_event_subscription_with_metadata` interceptor. + """ + return response + + def post_undelete_support_event_subscription_with_metadata( + self, + response: support_event_subscription.SupportEventSubscription, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + support_event_subscription.SupportEventSubscription, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for undelete_support_event_subscription + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SupportEventSubscriptionService server but before it is returned to user code. + + We recommend only using this `post_undelete_support_event_subscription_with_metadata` + interceptor in new development instead of the `post_undelete_support_event_subscription` interceptor. + When both interceptors are used, this `post_undelete_support_event_subscription_with_metadata` interceptor runs after the + `post_undelete_support_event_subscription` interceptor. The (possibly modified) response returned by + `post_undelete_support_event_subscription` will be passed to + `post_undelete_support_event_subscription_with_metadata`. + """ + return response, metadata + + def pre_update_support_event_subscription( + self, + request: support_event_subscription_service.UpdateSupportEventSubscriptionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + support_event_subscription_service.UpdateSupportEventSubscriptionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_support_event_subscription + + Override in a subclass to manipulate the request or metadata + before they are sent to the SupportEventSubscriptionService server. + """ + return request, metadata + + def post_update_support_event_subscription( + self, response: gcs_support_event_subscription.SupportEventSubscription + ) -> gcs_support_event_subscription.SupportEventSubscription: + """Post-rpc interceptor for update_support_event_subscription + + DEPRECATED. Please use the `post_update_support_event_subscription_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SupportEventSubscriptionService server but before + it is returned to user code. This `post_update_support_event_subscription` interceptor runs + before the `post_update_support_event_subscription_with_metadata` interceptor. + """ + return response + + def post_update_support_event_subscription_with_metadata( + self, + response: gcs_support_event_subscription.SupportEventSubscription, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcs_support_event_subscription.SupportEventSubscription, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for update_support_event_subscription + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SupportEventSubscriptionService server but before it is returned to user code. + + We recommend only using this `post_update_support_event_subscription_with_metadata` + interceptor in new development instead of the `post_update_support_event_subscription` interceptor. + When both interceptors are used, this `post_update_support_event_subscription_with_metadata` interceptor runs after the + `post_update_support_event_subscription` interceptor. The (possibly modified) response returned by + `post_update_support_event_subscription` will be passed to + `post_update_support_event_subscription_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class SupportEventSubscriptionServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SupportEventSubscriptionServiceRestInterceptor + + +class SupportEventSubscriptionServiceRestTransport( + _BaseSupportEventSubscriptionServiceRestTransport +): + """REST backend synchronous transport for SupportEventSubscriptionService. + + Service for managing customer support event subscriptions. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "cloudsupport.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[SupportEventSubscriptionServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudsupport.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + 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. + interceptor (Optional[SupportEventSubscriptionServiceRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = ( + interceptor or SupportEventSubscriptionServiceRestInterceptor() + ) + self._prep_wrapped_messages(client_info) + + class _CreateSupportEventSubscription( + _BaseSupportEventSubscriptionServiceRestTransport._BaseCreateSupportEventSubscription, + SupportEventSubscriptionServiceRestStub, + ): + def __hash__(self): + return hash( + "SupportEventSubscriptionServiceRestTransport.CreateSupportEventSubscription" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: support_event_subscription_service.CreateSupportEventSubscriptionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcs_support_event_subscription.SupportEventSubscription: + r"""Call the create support event + subscription method over HTTP. + + Args: + request (~.support_event_subscription_service.CreateSupportEventSubscriptionRequest): + The request object. Request message for + CreateSupportEventSubscription. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcs_support_event_subscription.SupportEventSubscription: + A support event subscription. + """ + + http_options = _BaseSupportEventSubscriptionServiceRestTransport._BaseCreateSupportEventSubscription._get_http_options() + + request, metadata = self._interceptor.pre_create_support_event_subscription( + request, metadata + ) + transcoded_request = _BaseSupportEventSubscriptionServiceRestTransport._BaseCreateSupportEventSubscription._get_transcoded_request( + http_options, request + ) + + body = _BaseSupportEventSubscriptionServiceRestTransport._BaseCreateSupportEventSubscription._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSupportEventSubscriptionServiceRestTransport._BaseCreateSupportEventSubscription._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.support_v2beta.SupportEventSubscriptionServiceClient.CreateSupportEventSubscription", + extra={ + "serviceName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "rpcName": "CreateSupportEventSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SupportEventSubscriptionServiceRestTransport._CreateSupportEventSubscription._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, 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_support_event_subscription.SupportEventSubscription() + pb_resp = gcs_support_event_subscription.SupportEventSubscription.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_support_event_subscription(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_create_support_event_subscription_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + gcs_support_event_subscription.SupportEventSubscription.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.support_v2beta.SupportEventSubscriptionServiceClient.create_support_event_subscription", + extra={ + "serviceName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "rpcName": "CreateSupportEventSubscription", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteSupportEventSubscription( + _BaseSupportEventSubscriptionServiceRestTransport._BaseDeleteSupportEventSubscription, + SupportEventSubscriptionServiceRestStub, + ): + def __hash__(self): + return hash( + "SupportEventSubscriptionServiceRestTransport.DeleteSupportEventSubscription" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: support_event_subscription_service.DeleteSupportEventSubscriptionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> support_event_subscription.SupportEventSubscription: + r"""Call the delete support event + subscription method over HTTP. + + Args: + request (~.support_event_subscription_service.DeleteSupportEventSubscriptionRequest): + The request object. Request message for + DeleteSupportEventSubscription. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.support_event_subscription.SupportEventSubscription: + A support event subscription. + """ + + http_options = _BaseSupportEventSubscriptionServiceRestTransport._BaseDeleteSupportEventSubscription._get_http_options() + + request, metadata = self._interceptor.pre_delete_support_event_subscription( + request, metadata + ) + transcoded_request = _BaseSupportEventSubscriptionServiceRestTransport._BaseDeleteSupportEventSubscription._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSupportEventSubscriptionServiceRestTransport._BaseDeleteSupportEventSubscription._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.support_v2beta.SupportEventSubscriptionServiceClient.DeleteSupportEventSubscription", + extra={ + "serviceName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "rpcName": "DeleteSupportEventSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SupportEventSubscriptionServiceRestTransport._DeleteSupportEventSubscription._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = support_event_subscription.SupportEventSubscription() + pb_resp = support_event_subscription.SupportEventSubscription.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_support_event_subscription(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_delete_support_event_subscription_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + support_event_subscription.SupportEventSubscription.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.support_v2beta.SupportEventSubscriptionServiceClient.delete_support_event_subscription", + extra={ + "serviceName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "rpcName": "DeleteSupportEventSubscription", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetSupportEventSubscription( + _BaseSupportEventSubscriptionServiceRestTransport._BaseGetSupportEventSubscription, + SupportEventSubscriptionServiceRestStub, + ): + def __hash__(self): + return hash( + "SupportEventSubscriptionServiceRestTransport.GetSupportEventSubscription" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: support_event_subscription_service.GetSupportEventSubscriptionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> support_event_subscription.SupportEventSubscription: + r"""Call the get support event + subscription method over HTTP. + + Args: + request (~.support_event_subscription_service.GetSupportEventSubscriptionRequest): + The request object. Request message for + GetSupportEventSubscription. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.support_event_subscription.SupportEventSubscription: + A support event subscription. + """ + + http_options = _BaseSupportEventSubscriptionServiceRestTransport._BaseGetSupportEventSubscription._get_http_options() + + request, metadata = self._interceptor.pre_get_support_event_subscription( + request, metadata + ) + transcoded_request = _BaseSupportEventSubscriptionServiceRestTransport._BaseGetSupportEventSubscription._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSupportEventSubscriptionServiceRestTransport._BaseGetSupportEventSubscription._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.support_v2beta.SupportEventSubscriptionServiceClient.GetSupportEventSubscription", + extra={ + "serviceName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "rpcName": "GetSupportEventSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SupportEventSubscriptionServiceRestTransport._GetSupportEventSubscription._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = support_event_subscription.SupportEventSubscription() + pb_resp = support_event_subscription.SupportEventSubscription.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_support_event_subscription(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_get_support_event_subscription_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + support_event_subscription.SupportEventSubscription.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.support_v2beta.SupportEventSubscriptionServiceClient.get_support_event_subscription", + extra={ + "serviceName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "rpcName": "GetSupportEventSubscription", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListSupportEventSubscriptions( + _BaseSupportEventSubscriptionServiceRestTransport._BaseListSupportEventSubscriptions, + SupportEventSubscriptionServiceRestStub, + ): + def __hash__(self): + return hash( + "SupportEventSubscriptionServiceRestTransport.ListSupportEventSubscriptions" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: support_event_subscription_service.ListSupportEventSubscriptionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> support_event_subscription_service.ListSupportEventSubscriptionsResponse: + r"""Call the list support event + subscriptions method over HTTP. + + Args: + request (~.support_event_subscription_service.ListSupportEventSubscriptionsRequest): + The request object. Request message for + ListSupportEventSubscriptions. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.support_event_subscription_service.ListSupportEventSubscriptionsResponse: + Response message for + ListSupportEventSubscriptions. + + """ + + http_options = _BaseSupportEventSubscriptionServiceRestTransport._BaseListSupportEventSubscriptions._get_http_options() + + request, metadata = self._interceptor.pre_list_support_event_subscriptions( + request, metadata + ) + transcoded_request = _BaseSupportEventSubscriptionServiceRestTransport._BaseListSupportEventSubscriptions._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSupportEventSubscriptionServiceRestTransport._BaseListSupportEventSubscriptions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.support_v2beta.SupportEventSubscriptionServiceClient.ListSupportEventSubscriptions", + extra={ + "serviceName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "rpcName": "ListSupportEventSubscriptions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SupportEventSubscriptionServiceRestTransport._ListSupportEventSubscriptions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = support_event_subscription_service.ListSupportEventSubscriptionsResponse() + pb_resp = support_event_subscription_service.ListSupportEventSubscriptionsResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_support_event_subscriptions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_list_support_event_subscriptions_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = support_event_subscription_service.ListSupportEventSubscriptionsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.support_v2beta.SupportEventSubscriptionServiceClient.list_support_event_subscriptions", + extra={ + "serviceName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "rpcName": "ListSupportEventSubscriptions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UndeleteSupportEventSubscription( + _BaseSupportEventSubscriptionServiceRestTransport._BaseUndeleteSupportEventSubscription, + SupportEventSubscriptionServiceRestStub, + ): + def __hash__(self): + return hash( + "SupportEventSubscriptionServiceRestTransport.UndeleteSupportEventSubscription" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: support_event_subscription_service.UndeleteSupportEventSubscriptionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> support_event_subscription.SupportEventSubscription: + r"""Call the undelete support event + subscription method over HTTP. + + Args: + request (~.support_event_subscription_service.UndeleteSupportEventSubscriptionRequest): + The request object. Request message for + UndeleteSupportEventSubscription. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.support_event_subscription.SupportEventSubscription: + A support event subscription. + """ + + http_options = _BaseSupportEventSubscriptionServiceRestTransport._BaseUndeleteSupportEventSubscription._get_http_options() + + request, metadata = ( + self._interceptor.pre_undelete_support_event_subscription( + request, metadata + ) + ) + transcoded_request = _BaseSupportEventSubscriptionServiceRestTransport._BaseUndeleteSupportEventSubscription._get_transcoded_request( + http_options, request + ) + + body = _BaseSupportEventSubscriptionServiceRestTransport._BaseUndeleteSupportEventSubscription._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSupportEventSubscriptionServiceRestTransport._BaseUndeleteSupportEventSubscription._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.support_v2beta.SupportEventSubscriptionServiceClient.UndeleteSupportEventSubscription", + extra={ + "serviceName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "rpcName": "UndeleteSupportEventSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SupportEventSubscriptionServiceRestTransport._UndeleteSupportEventSubscription._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = support_event_subscription.SupportEventSubscription() + pb_resp = support_event_subscription.SupportEventSubscription.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_undelete_support_event_subscription(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_undelete_support_event_subscription_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + support_event_subscription.SupportEventSubscription.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.support_v2beta.SupportEventSubscriptionServiceClient.undelete_support_event_subscription", + extra={ + "serviceName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "rpcName": "UndeleteSupportEventSubscription", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateSupportEventSubscription( + _BaseSupportEventSubscriptionServiceRestTransport._BaseUpdateSupportEventSubscription, + SupportEventSubscriptionServiceRestStub, + ): + def __hash__(self): + return hash( + "SupportEventSubscriptionServiceRestTransport.UpdateSupportEventSubscription" + ) + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: support_event_subscription_service.UpdateSupportEventSubscriptionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcs_support_event_subscription.SupportEventSubscription: + r"""Call the update support event + subscription method over HTTP. + + Args: + request (~.support_event_subscription_service.UpdateSupportEventSubscriptionRequest): + The request object. Request message for + UpdateSupportEventSubscription. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcs_support_event_subscription.SupportEventSubscription: + A support event subscription. + """ + + http_options = _BaseSupportEventSubscriptionServiceRestTransport._BaseUpdateSupportEventSubscription._get_http_options() + + request, metadata = self._interceptor.pre_update_support_event_subscription( + request, metadata + ) + transcoded_request = _BaseSupportEventSubscriptionServiceRestTransport._BaseUpdateSupportEventSubscription._get_transcoded_request( + http_options, request + ) + + body = _BaseSupportEventSubscriptionServiceRestTransport._BaseUpdateSupportEventSubscription._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSupportEventSubscriptionServiceRestTransport._BaseUpdateSupportEventSubscription._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.support_v2beta.SupportEventSubscriptionServiceClient.UpdateSupportEventSubscription", + extra={ + "serviceName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "rpcName": "UpdateSupportEventSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SupportEventSubscriptionServiceRestTransport._UpdateSupportEventSubscription._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, 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_support_event_subscription.SupportEventSubscription() + pb_resp = gcs_support_event_subscription.SupportEventSubscription.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_support_event_subscription(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_update_support_event_subscription_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + gcs_support_event_subscription.SupportEventSubscription.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.support_v2beta.SupportEventSubscriptionServiceClient.update_support_event_subscription", + extra={ + "serviceName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "rpcName": "UpdateSupportEventSubscription", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.CreateSupportEventSubscriptionRequest], + gcs_support_event_subscription.SupportEventSubscription, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSupportEventSubscription( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def delete_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.DeleteSupportEventSubscriptionRequest], + support_event_subscription.SupportEventSubscription, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteSupportEventSubscription( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.GetSupportEventSubscriptionRequest], + support_event_subscription.SupportEventSubscription, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSupportEventSubscription( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_support_event_subscriptions( + self, + ) -> Callable[ + [support_event_subscription_service.ListSupportEventSubscriptionsRequest], + support_event_subscription_service.ListSupportEventSubscriptionsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSupportEventSubscriptions( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def undelete_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.UndeleteSupportEventSubscriptionRequest], + support_event_subscription.SupportEventSubscription, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UndeleteSupportEventSubscription( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def update_support_event_subscription( + self, + ) -> Callable[ + [support_event_subscription_service.UpdateSupportEventSubscriptionRequest], + gcs_support_event_subscription.SupportEventSubscription, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSupportEventSubscription( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("SupportEventSubscriptionServiceRestTransport",) diff --git a/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/rest_base.py b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/rest_base.py new file mode 100644 index 000000000000..e3390536088f --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2beta/services/support_event_subscription_service/transports/rest_base.py @@ -0,0 +1,423 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.support_v2beta.types import ( + support_event_subscription, + support_event_subscription_service, +) +from google.cloud.support_v2beta.types import ( + support_event_subscription as gcs_support_event_subscription, +) + +from .base import DEFAULT_CLIENT_INFO, SupportEventSubscriptionServiceTransport + + +class _BaseSupportEventSubscriptionServiceRestTransport( + SupportEventSubscriptionServiceTransport +): + """Base REST backend transport for SupportEventSubscriptionService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "cloudsupport.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudsupport.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreateSupportEventSubscription: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{parent=*/*}/supportEventSubscriptions", + "body": "support_event_subscription", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = support_event_subscription_service.CreateSupportEventSubscriptionRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSupportEventSubscriptionServiceRestTransport._BaseCreateSupportEventSubscription._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteSupportEventSubscription: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2beta/{name=*/*/supportEventSubscriptions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = support_event_subscription_service.DeleteSupportEventSubscriptionRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSupportEventSubscriptionServiceRestTransport._BaseDeleteSupportEventSubscription._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetSupportEventSubscription: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{name=*/*/supportEventSubscriptions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = support_event_subscription_service.GetSupportEventSubscriptionRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSupportEventSubscriptionServiceRestTransport._BaseGetSupportEventSubscription._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListSupportEventSubscriptions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2beta/{parent=*/*}/supportEventSubscriptions", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = support_event_subscription_service.ListSupportEventSubscriptionsRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSupportEventSubscriptionServiceRestTransport._BaseListSupportEventSubscriptions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUndeleteSupportEventSubscription: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2beta/{name=*/*/supportEventSubscriptions/*}:undelete", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = support_event_subscription_service.UndeleteSupportEventSubscriptionRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSupportEventSubscriptionServiceRestTransport._BaseUndeleteSupportEventSubscription._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateSupportEventSubscription: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2beta/{support_event_subscription.name=*/*/supportEventSubscriptions/*}", + "body": "support_event_subscription", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = support_event_subscription_service.UpdateSupportEventSubscriptionRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSupportEventSubscriptionServiceRestTransport._BaseUpdateSupportEventSubscription._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BaseSupportEventSubscriptionServiceRestTransport",) diff --git a/packages/google-cloud-support/google/cloud/support_v2beta/types/__init__.py b/packages/google-cloud-support/google/cloud/support_v2beta/types/__init__.py index 6be8a494bc4a..a30746ee0d37 100644 --- a/packages/google-cloud-support/google/cloud/support_v2beta/types/__init__.py +++ b/packages/google-cloud-support/google/cloud/support_v2beta/types/__init__.py @@ -68,6 +68,18 @@ ShowFeedRequest, ShowFeedResponse, ) +from .support_event_subscription import ( + SupportEventSubscription, +) +from .support_event_subscription_service import ( + CreateSupportEventSubscriptionRequest, + DeleteSupportEventSubscriptionRequest, + GetSupportEventSubscriptionRequest, + ListSupportEventSubscriptionsRequest, + ListSupportEventSubscriptionsResponse, + UndeleteSupportEventSubscriptionRequest, + UpdateSupportEventSubscriptionRequest, +) __all__ = ( "Actor", @@ -101,4 +113,12 @@ "FeedItem", "ShowFeedRequest", "ShowFeedResponse", + "SupportEventSubscription", + "CreateSupportEventSubscriptionRequest", + "DeleteSupportEventSubscriptionRequest", + "GetSupportEventSubscriptionRequest", + "ListSupportEventSubscriptionsRequest", + "ListSupportEventSubscriptionsResponse", + "UndeleteSupportEventSubscriptionRequest", + "UpdateSupportEventSubscriptionRequest", ) diff --git a/packages/google-cloud-support/google/cloud/support_v2beta/types/case_service.py b/packages/google-cloud-support/google/cloud/support_v2beta/types/case_service.py index eebd687320fd..d0eb5d2b5c3d 100644 --- a/packages/google-cloud-support/google/cloud/support_v2beta/types/case_service.py +++ b/packages/google-cloud-support/google/cloud/support_v2beta/types/case_service.py @@ -190,10 +190,6 @@ class SearchCasesRequest(proto.Message): Expressions use the following fields separated by ``AND`` and specified with ``=``: - - ``organization``: An organization name in the form - ``organizations/``. - - ``project``: A project name in the form - ``projects/``. - ``state``: Can be ``OPEN`` or ``CLOSED``. - ``priority``: Can be ``P0``, ``P1``, ``P2``, ``P3``, or ``P4``. You can specify multiple values for priority using @@ -201,8 +197,6 @@ class SearchCasesRequest(proto.Message): ``priority=P1 OR priority=P2``. - ``creator.email``: The email address of the case creator. - You must specify either ``organization`` or ``project``. - To search across ``displayName``, ``description``, and comments, use a global restriction with no keyword or operator. For example, ``"my search"``. @@ -213,8 +207,32 @@ class SearchCasesRequest(proto.Message): ``update_time>"2020-01-01T00:00:00-05:00"``. ``update_time`` only supports the greater than operator (``>``). + If you are using the ``v2`` version of the API, you must + specify the case parent in the ``parent`` field. If you + provide an empty ``query``, all cases under the parent + resource will be returned. + + If you are using the ``v2beta`` version of the API, you must + specify the case parent in the ``query`` field using one of + the two fields below, which are only available for + ``v2beta``. The ``parent`` field will be ignored. + + - ``organization``: An organization name in the form + ``organizations/``. + - ``project``: A project name in the form + ``projects/``. + Examples: + For ``v2``: + + - ``state=CLOSED`` + - ``state=OPEN AND creator.email="tester@example.com"`` + - ``state=OPEN AND (priority=P0 OR priority=P1)`` + - ``update_time>"2020-01-01T00:00:00-05:00"`` + + For ``v2beta``: + - ``organization="organizations/123456789"`` - ``project="projects/my-project-id"`` - ``project="projects/123456789"`` diff --git a/packages/google-cloud-support/google/cloud/support_v2beta/types/support_event_subscription.py b/packages/google-cloud-support/google/cloud/support_v2beta/types/support_event_subscription.py new file mode 100644 index 000000000000..8001a4682a48 --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2beta/types/support_event_subscription.py @@ -0,0 +1,148 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.support.v2beta", + manifest={ + "SupportEventSubscription", + }, +) + + +class SupportEventSubscription(proto.Message): + r"""A support event subscription. + + Attributes: + name (str): + Identifier. The resource name of the support + event subscription. + pub_sub_topic (str): + Required. The name of the Pub/Sub topic to + publish notifications to. Format: + projects/{project}/topics/{topic} + state (google.cloud.support_v2beta.types.SupportEventSubscription.State): + Output only. The state of the subscription. + failure_reason (google.cloud.support_v2beta.types.SupportEventSubscription.FailureReason): + Output only. Reason why subscription is + failing. State of subscription must be FAILING + in order for this to have a value. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the + subscription was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the + subscription was last updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the + subscription was deleted. + purge_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the + subscription will be purged. + """ + + class State(proto.Enum): + r"""The state of the subscription. + + Values: + STATE_UNSPECIFIED (0): + Unspecified state. + WORKING (1): + Subscription is active and working. + FAILING (2): + Subscription is failing. Notifications cannot + be published for some reason. + DELETED (3): + Subscription has been deleted and is pending purge. + Notifications are not sent for deleted subscriptions. + Deleted subscriptions are purged after their ``purge_time`` + has passed. + """ + + STATE_UNSPECIFIED = 0 + WORKING = 1 + FAILING = 2 + DELETED = 3 + + class FailureReason(proto.Enum): + r"""The reason why the subscription is failing. + + Values: + FAILURE_REASON_UNSPECIFIED (0): + Unspecified failure reason. + PERMISSION_DENIED (1): + The service account (i.e. + cloud-support-apievents@system.gserviceaccount.com) + lacks the permission to publish to the + customer's Pub/Sub topic. + TOPIC_NOT_FOUND (2): + The specified Pub/Sub topic does not exist. + OTHER (3): + Message failed to publish due to a + system-side error. + """ + + FAILURE_REASON_UNSPECIFIED = 0 + PERMISSION_DENIED = 1 + TOPIC_NOT_FOUND = 2 + OTHER = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + pub_sub_topic: str = proto.Field( + proto.STRING, + number=2, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + failure_reason: FailureReason = proto.Field( + proto.ENUM, + number=4, + enum=FailureReason, + ) + 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, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + purge_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-support/google/cloud/support_v2beta/types/support_event_subscription_service.py b/packages/google-cloud-support/google/cloud/support_v2beta/types/support_event_subscription_service.py new file mode 100644 index 000000000000..dfa673a1cb7b --- /dev/null +++ b/packages/google-cloud-support/google/cloud/support_v2beta/types/support_event_subscription_service.py @@ -0,0 +1,225 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.support_v2beta.types import ( + support_event_subscription as gcs_support_event_subscription, +) + +__protobuf__ = proto.module( + package="google.cloud.support.v2beta", + manifest={ + "CreateSupportEventSubscriptionRequest", + "GetSupportEventSubscriptionRequest", + "ListSupportEventSubscriptionsRequest", + "ListSupportEventSubscriptionsResponse", + "UpdateSupportEventSubscriptionRequest", + "DeleteSupportEventSubscriptionRequest", + "UndeleteSupportEventSubscriptionRequest", + }, +) + + +class CreateSupportEventSubscriptionRequest(proto.Message): + r"""Request message for CreateSupportEventSubscription. + + Attributes: + parent (str): + Required. The parent resource name where the support event + subscription will be created. Format: + organizations/{organization_id} + support_event_subscription (google.cloud.support_v2beta.types.SupportEventSubscription): + Required. The Pub/Sub configuration to + create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + support_event_subscription: gcs_support_event_subscription.SupportEventSubscription = proto.Field( + proto.MESSAGE, + number=2, + message=gcs_support_event_subscription.SupportEventSubscription, + ) + + +class GetSupportEventSubscriptionRequest(proto.Message): + r"""Request message for GetSupportEventSubscription. + + Attributes: + name (str): + Required. The name of the support event subscription to + retrieve. Format: + organizations/{organization_id}/supportEventSubscriptions/{subscription_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSupportEventSubscriptionsRequest(proto.Message): + r"""Request message for ListSupportEventSubscriptions. + + Attributes: + parent (str): + Required. The fully qualified name of the Cloud resource to + list support event subscriptions under. Format: + organizations/{organization_id} + filter (str): + Optional. Filter expression based on AIP-160. Supported + fields: + + - pub_sub_topic + - state + + Examples: + + - ``pub_sub_topic="projects/example-project/topics/example-topic"`` + - ``state=WORKING`` + - ``pub_sub_topic="projects/example-project/topics/example-topic" AND state=WORKING`` + show_deleted (bool): + Optional. Whether to show deleted + subscriptions. By default, deleted subscriptions + are not returned. + page_size (int): + Optional. The maximum number of support event + subscriptions to return. + page_token (str): + Optional. A token identifying the page of results to return. + If unspecified, the first page is retrieved. + + When paginating, all other parameters provided to + ``ListSupportEventSubscriptions`` must match the call that + provided the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + show_deleted: bool = proto.Field( + proto.BOOL, + number=3, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListSupportEventSubscriptionsResponse(proto.Message): + r"""Response message for ListSupportEventSubscriptions. + + Attributes: + support_event_subscriptions (MutableSequence[google.cloud.support_v2beta.types.SupportEventSubscription]): + The support event subscriptions. + 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 + + support_event_subscriptions: MutableSequence[ + gcs_support_event_subscription.SupportEventSubscription + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcs_support_event_subscription.SupportEventSubscription, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateSupportEventSubscriptionRequest(proto.Message): + r"""Request message for UpdateSupportEventSubscription. + + Attributes: + support_event_subscription (google.cloud.support_v2beta.types.SupportEventSubscription): + Required. The support event subscription to update. The + ``name`` field is used to identify the configuration to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. The only supported + value is pub_sub_topic. + """ + + support_event_subscription: gcs_support_event_subscription.SupportEventSubscription = proto.Field( + proto.MESSAGE, + number=1, + message=gcs_support_event_subscription.SupportEventSubscription, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteSupportEventSubscriptionRequest(proto.Message): + r"""Request message for DeleteSupportEventSubscription. + + Attributes: + name (str): + Required. The name of the support event subscription to + delete. Format: + organizations/{organization_id}/supportEventSubscriptions/{subscription_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UndeleteSupportEventSubscriptionRequest(proto.Message): + r"""Request message for UndeleteSupportEventSubscription. + + Attributes: + name (str): + Required. The name of the support event subscription to + undelete. Format: + organizations/{organization_id}/supportEventSubscriptions/{subscription_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_create_support_event_subscription_async.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_create_support_event_subscription_async.py new file mode 100644 index 000000000000..fa32c5bf911d --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_create_support_event_subscription_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSupportEventSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2_generated_SupportEventSubscriptionService_CreateSupportEventSubscription_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2 + + +async def sample_create_support_event_subscription(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + support_event_subscription = support_v2.SupportEventSubscription() + support_event_subscription.pub_sub_topic = "pub_sub_topic_value" + + request = support_v2.CreateSupportEventSubscriptionRequest( + parent="parent_value", + support_event_subscription=support_event_subscription, + ) + + # Make the request + response = await client.create_support_event_subscription(request=request) + + # Handle the response + print(response) + + +# [END cloudsupport_v2_generated_SupportEventSubscriptionService_CreateSupportEventSubscription_async] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_create_support_event_subscription_sync.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_create_support_event_subscription_sync.py new file mode 100644 index 000000000000..7f0729b0f4e5 --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_create_support_event_subscription_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSupportEventSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2_generated_SupportEventSubscriptionService_CreateSupportEventSubscription_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2 + + +def sample_create_support_event_subscription(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + support_event_subscription = support_v2.SupportEventSubscription() + support_event_subscription.pub_sub_topic = "pub_sub_topic_value" + + request = support_v2.CreateSupportEventSubscriptionRequest( + parent="parent_value", + support_event_subscription=support_event_subscription, + ) + + # Make the request + response = client.create_support_event_subscription(request=request) + + # Handle the response + print(response) + + +# [END cloudsupport_v2_generated_SupportEventSubscriptionService_CreateSupportEventSubscription_sync] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_delete_support_event_subscription_async.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_delete_support_event_subscription_async.py new file mode 100644 index 000000000000..dd70d6274020 --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_delete_support_event_subscription_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSupportEventSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2_generated_SupportEventSubscriptionService_DeleteSupportEventSubscription_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2 + + +async def sample_delete_support_event_subscription(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + request = support_v2.DeleteSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = await client.delete_support_event_subscription(request=request) + + # Handle the response + print(response) + + +# [END cloudsupport_v2_generated_SupportEventSubscriptionService_DeleteSupportEventSubscription_async] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_delete_support_event_subscription_sync.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_delete_support_event_subscription_sync.py new file mode 100644 index 000000000000..3b00b2ca1593 --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_delete_support_event_subscription_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSupportEventSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2_generated_SupportEventSubscriptionService_DeleteSupportEventSubscription_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2 + + +def sample_delete_support_event_subscription(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + request = support_v2.DeleteSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = client.delete_support_event_subscription(request=request) + + # Handle the response + print(response) + + +# [END cloudsupport_v2_generated_SupportEventSubscriptionService_DeleteSupportEventSubscription_sync] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_get_support_event_subscription_async.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_get_support_event_subscription_async.py new file mode 100644 index 000000000000..d1a830c72530 --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_get_support_event_subscription_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSupportEventSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2_generated_SupportEventSubscriptionService_GetSupportEventSubscription_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2 + + +async def sample_get_support_event_subscription(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + request = support_v2.GetSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_support_event_subscription(request=request) + + # Handle the response + print(response) + + +# [END cloudsupport_v2_generated_SupportEventSubscriptionService_GetSupportEventSubscription_async] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_get_support_event_subscription_sync.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_get_support_event_subscription_sync.py new file mode 100644 index 000000000000..6bb0308d34bc --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_get_support_event_subscription_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSupportEventSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2_generated_SupportEventSubscriptionService_GetSupportEventSubscription_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2 + + +def sample_get_support_event_subscription(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + request = support_v2.GetSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = client.get_support_event_subscription(request=request) + + # Handle the response + print(response) + + +# [END cloudsupport_v2_generated_SupportEventSubscriptionService_GetSupportEventSubscription_sync] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_list_support_event_subscriptions_async.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_list_support_event_subscriptions_async.py new file mode 100644 index 000000000000..52254e2a1637 --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_list_support_event_subscriptions_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSupportEventSubscriptions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2_generated_SupportEventSubscriptionService_ListSupportEventSubscriptions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2 + + +async def sample_list_support_event_subscriptions(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + request = support_v2.ListSupportEventSubscriptionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_support_event_subscriptions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END cloudsupport_v2_generated_SupportEventSubscriptionService_ListSupportEventSubscriptions_async] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_list_support_event_subscriptions_sync.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_list_support_event_subscriptions_sync.py new file mode 100644 index 000000000000..4663226c7416 --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_list_support_event_subscriptions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSupportEventSubscriptions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2_generated_SupportEventSubscriptionService_ListSupportEventSubscriptions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2 + + +def sample_list_support_event_subscriptions(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + request = support_v2.ListSupportEventSubscriptionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_support_event_subscriptions(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END cloudsupport_v2_generated_SupportEventSubscriptionService_ListSupportEventSubscriptions_sync] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_undelete_support_event_subscription_async.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_undelete_support_event_subscription_async.py new file mode 100644 index 000000000000..c38b291cf176 --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_undelete_support_event_subscription_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UndeleteSupportEventSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2_generated_SupportEventSubscriptionService_UndeleteSupportEventSubscription_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2 + + +async def sample_undelete_support_event_subscription(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + request = support_v2.UndeleteSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = await client.undelete_support_event_subscription(request=request) + + # Handle the response + print(response) + + +# [END cloudsupport_v2_generated_SupportEventSubscriptionService_UndeleteSupportEventSubscription_async] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_undelete_support_event_subscription_sync.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_undelete_support_event_subscription_sync.py new file mode 100644 index 000000000000..dc72eb86d048 --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_undelete_support_event_subscription_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UndeleteSupportEventSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2_generated_SupportEventSubscriptionService_UndeleteSupportEventSubscription_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2 + + +def sample_undelete_support_event_subscription(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + request = support_v2.UndeleteSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = client.undelete_support_event_subscription(request=request) + + # Handle the response + print(response) + + +# [END cloudsupport_v2_generated_SupportEventSubscriptionService_UndeleteSupportEventSubscription_sync] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_update_support_event_subscription_async.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_update_support_event_subscription_async.py new file mode 100644 index 000000000000..dd8bf97abf3c --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_update_support_event_subscription_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSupportEventSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2_generated_SupportEventSubscriptionService_UpdateSupportEventSubscription_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2 + + +async def sample_update_support_event_subscription(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + support_event_subscription = support_v2.SupportEventSubscription() + support_event_subscription.pub_sub_topic = "pub_sub_topic_value" + + request = support_v2.UpdateSupportEventSubscriptionRequest( + support_event_subscription=support_event_subscription, + ) + + # Make the request + response = await client.update_support_event_subscription(request=request) + + # Handle the response + print(response) + + +# [END cloudsupport_v2_generated_SupportEventSubscriptionService_UpdateSupportEventSubscription_async] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_update_support_event_subscription_sync.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_update_support_event_subscription_sync.py new file mode 100644 index 000000000000..721bcd1bbd37 --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2_generated_support_event_subscription_service_update_support_event_subscription_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSupportEventSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2_generated_SupportEventSubscriptionService_UpdateSupportEventSubscription_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2 + + +def sample_update_support_event_subscription(): + # Create a client + client = support_v2.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + support_event_subscription = support_v2.SupportEventSubscription() + support_event_subscription.pub_sub_topic = "pub_sub_topic_value" + + request = support_v2.UpdateSupportEventSubscriptionRequest( + support_event_subscription=support_event_subscription, + ) + + # Make the request + response = client.update_support_event_subscription(request=request) + + # Handle the response + print(response) + + +# [END cloudsupport_v2_generated_SupportEventSubscriptionService_UpdateSupportEventSubscription_sync] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_create_support_event_subscription_async.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_create_support_event_subscription_async.py new file mode 100644 index 000000000000..814bb351d5fd --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_create_support_event_subscription_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSupportEventSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2beta_generated_SupportEventSubscriptionService_CreateSupportEventSubscription_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2beta + + +async def sample_create_support_event_subscription(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + support_event_subscription = support_v2beta.SupportEventSubscription() + support_event_subscription.pub_sub_topic = "pub_sub_topic_value" + + request = support_v2beta.CreateSupportEventSubscriptionRequest( + parent="parent_value", + support_event_subscription=support_event_subscription, + ) + + # Make the request + response = await client.create_support_event_subscription(request=request) + + # Handle the response + print(response) + + +# [END cloudsupport_v2beta_generated_SupportEventSubscriptionService_CreateSupportEventSubscription_async] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_create_support_event_subscription_sync.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_create_support_event_subscription_sync.py new file mode 100644 index 000000000000..5036f7e75751 --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_create_support_event_subscription_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSupportEventSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2beta_generated_SupportEventSubscriptionService_CreateSupportEventSubscription_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2beta + + +def sample_create_support_event_subscription(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + support_event_subscription = support_v2beta.SupportEventSubscription() + support_event_subscription.pub_sub_topic = "pub_sub_topic_value" + + request = support_v2beta.CreateSupportEventSubscriptionRequest( + parent="parent_value", + support_event_subscription=support_event_subscription, + ) + + # Make the request + response = client.create_support_event_subscription(request=request) + + # Handle the response + print(response) + + +# [END cloudsupport_v2beta_generated_SupportEventSubscriptionService_CreateSupportEventSubscription_sync] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_delete_support_event_subscription_async.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_delete_support_event_subscription_async.py new file mode 100644 index 000000000000..dd09d5431a55 --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_delete_support_event_subscription_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSupportEventSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2beta_generated_SupportEventSubscriptionService_DeleteSupportEventSubscription_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2beta + + +async def sample_delete_support_event_subscription(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + request = support_v2beta.DeleteSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = await client.delete_support_event_subscription(request=request) + + # Handle the response + print(response) + + +# [END cloudsupport_v2beta_generated_SupportEventSubscriptionService_DeleteSupportEventSubscription_async] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_delete_support_event_subscription_sync.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_delete_support_event_subscription_sync.py new file mode 100644 index 000000000000..3be28c4941f6 --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_delete_support_event_subscription_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSupportEventSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2beta_generated_SupportEventSubscriptionService_DeleteSupportEventSubscription_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2beta + + +def sample_delete_support_event_subscription(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + request = support_v2beta.DeleteSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = client.delete_support_event_subscription(request=request) + + # Handle the response + print(response) + + +# [END cloudsupport_v2beta_generated_SupportEventSubscriptionService_DeleteSupportEventSubscription_sync] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_get_support_event_subscription_async.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_get_support_event_subscription_async.py new file mode 100644 index 000000000000..e2baf1914d89 --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_get_support_event_subscription_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSupportEventSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2beta_generated_SupportEventSubscriptionService_GetSupportEventSubscription_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2beta + + +async def sample_get_support_event_subscription(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + request = support_v2beta.GetSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_support_event_subscription(request=request) + + # Handle the response + print(response) + + +# [END cloudsupport_v2beta_generated_SupportEventSubscriptionService_GetSupportEventSubscription_async] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_get_support_event_subscription_sync.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_get_support_event_subscription_sync.py new file mode 100644 index 000000000000..f152392dd80f --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_get_support_event_subscription_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSupportEventSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2beta_generated_SupportEventSubscriptionService_GetSupportEventSubscription_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2beta + + +def sample_get_support_event_subscription(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + request = support_v2beta.GetSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = client.get_support_event_subscription(request=request) + + # Handle the response + print(response) + + +# [END cloudsupport_v2beta_generated_SupportEventSubscriptionService_GetSupportEventSubscription_sync] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_list_support_event_subscriptions_async.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_list_support_event_subscriptions_async.py new file mode 100644 index 000000000000..24c0e2f52cee --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_list_support_event_subscriptions_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSupportEventSubscriptions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2beta_generated_SupportEventSubscriptionService_ListSupportEventSubscriptions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2beta + + +async def sample_list_support_event_subscriptions(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + request = support_v2beta.ListSupportEventSubscriptionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_support_event_subscriptions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END cloudsupport_v2beta_generated_SupportEventSubscriptionService_ListSupportEventSubscriptions_async] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_list_support_event_subscriptions_sync.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_list_support_event_subscriptions_sync.py new file mode 100644 index 000000000000..5e5d048591e5 --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_list_support_event_subscriptions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSupportEventSubscriptions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2beta_generated_SupportEventSubscriptionService_ListSupportEventSubscriptions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2beta + + +def sample_list_support_event_subscriptions(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + request = support_v2beta.ListSupportEventSubscriptionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_support_event_subscriptions(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END cloudsupport_v2beta_generated_SupportEventSubscriptionService_ListSupportEventSubscriptions_sync] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_undelete_support_event_subscription_async.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_undelete_support_event_subscription_async.py new file mode 100644 index 000000000000..231fd798faff --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_undelete_support_event_subscription_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UndeleteSupportEventSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2beta_generated_SupportEventSubscriptionService_UndeleteSupportEventSubscription_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2beta + + +async def sample_undelete_support_event_subscription(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + request = support_v2beta.UndeleteSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = await client.undelete_support_event_subscription(request=request) + + # Handle the response + print(response) + + +# [END cloudsupport_v2beta_generated_SupportEventSubscriptionService_UndeleteSupportEventSubscription_async] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_undelete_support_event_subscription_sync.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_undelete_support_event_subscription_sync.py new file mode 100644 index 000000000000..49fa542ab492 --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_undelete_support_event_subscription_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UndeleteSupportEventSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2beta_generated_SupportEventSubscriptionService_UndeleteSupportEventSubscription_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2beta + + +def sample_undelete_support_event_subscription(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + request = support_v2beta.UndeleteSupportEventSubscriptionRequest( + name="name_value", + ) + + # Make the request + response = client.undelete_support_event_subscription(request=request) + + # Handle the response + print(response) + + +# [END cloudsupport_v2beta_generated_SupportEventSubscriptionService_UndeleteSupportEventSubscription_sync] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_update_support_event_subscription_async.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_update_support_event_subscription_async.py new file mode 100644 index 000000000000..cda5b65f3d0d --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_update_support_event_subscription_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSupportEventSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2beta_generated_SupportEventSubscriptionService_UpdateSupportEventSubscription_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2beta + + +async def sample_update_support_event_subscription(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceAsyncClient() + + # Initialize request argument(s) + support_event_subscription = support_v2beta.SupportEventSubscription() + support_event_subscription.pub_sub_topic = "pub_sub_topic_value" + + request = support_v2beta.UpdateSupportEventSubscriptionRequest( + support_event_subscription=support_event_subscription, + ) + + # Make the request + response = await client.update_support_event_subscription(request=request) + + # Handle the response + print(response) + + +# [END cloudsupport_v2beta_generated_SupportEventSubscriptionService_UpdateSupportEventSubscription_async] diff --git a/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_update_support_event_subscription_sync.py b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_update_support_event_subscription_sync.py new file mode 100644 index 000000000000..68936faf1d6c --- /dev/null +++ b/packages/google-cloud-support/samples/generated_samples/cloudsupport_v2beta_generated_support_event_subscription_service_update_support_event_subscription_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSupportEventSubscription +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-support + + +# [START cloudsupport_v2beta_generated_SupportEventSubscriptionService_UpdateSupportEventSubscription_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import support_v2beta + + +def sample_update_support_event_subscription(): + # Create a client + client = support_v2beta.SupportEventSubscriptionServiceClient() + + # Initialize request argument(s) + support_event_subscription = support_v2beta.SupportEventSubscription() + support_event_subscription.pub_sub_topic = "pub_sub_topic_value" + + request = support_v2beta.UpdateSupportEventSubscriptionRequest( + support_event_subscription=support_event_subscription, + ) + + # Make the request + response = client.update_support_event_subscription(request=request) + + # Handle the response + print(response) + + +# [END cloudsupport_v2beta_generated_SupportEventSubscriptionService_UpdateSupportEventSubscription_sync] diff --git a/packages/google-cloud-support/samples/generated_samples/snippet_metadata_google.cloud.support.v2.json b/packages/google-cloud-support/samples/generated_samples/snippet_metadata_google.cloud.support.v2.json index bb35055aab5b..3e46a3e2e620 100644 --- a/packages/google-cloud-support/samples/generated_samples/snippet_metadata_google.cloud.support.v2.json +++ b/packages/google-cloud-support/samples/generated_samples/snippet_metadata_google.cloud.support.v2.json @@ -2095,6 +2095,980 @@ } ], "title": "cloudsupport_v2_generated_comment_service_list_comments_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceAsyncClient", + "shortName": "SupportEventSubscriptionServiceAsyncClient" + }, + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceAsyncClient.create_support_event_subscription", + "method": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService.CreateSupportEventSubscription", + "service": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "CreateSupportEventSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2.types.CreateSupportEventSubscriptionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "support_event_subscription", + "type": "google.cloud.support_v2.types.SupportEventSubscription" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2.types.SupportEventSubscription", + "shortName": "create_support_event_subscription" + }, + "description": "Sample for CreateSupportEventSubscription", + "file": "cloudsupport_v2_generated_support_event_subscription_service_create_support_event_subscription_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2_generated_SupportEventSubscriptionService_CreateSupportEventSubscription_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": "cloudsupport_v2_generated_support_event_subscription_service_create_support_event_subscription_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceClient", + "shortName": "SupportEventSubscriptionServiceClient" + }, + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceClient.create_support_event_subscription", + "method": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService.CreateSupportEventSubscription", + "service": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "CreateSupportEventSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2.types.CreateSupportEventSubscriptionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "support_event_subscription", + "type": "google.cloud.support_v2.types.SupportEventSubscription" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2.types.SupportEventSubscription", + "shortName": "create_support_event_subscription" + }, + "description": "Sample for CreateSupportEventSubscription", + "file": "cloudsupport_v2_generated_support_event_subscription_service_create_support_event_subscription_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2_generated_SupportEventSubscriptionService_CreateSupportEventSubscription_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": "cloudsupport_v2_generated_support_event_subscription_service_create_support_event_subscription_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceAsyncClient", + "shortName": "SupportEventSubscriptionServiceAsyncClient" + }, + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceAsyncClient.delete_support_event_subscription", + "method": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService.DeleteSupportEventSubscription", + "service": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "DeleteSupportEventSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2.types.DeleteSupportEventSubscriptionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2.types.SupportEventSubscription", + "shortName": "delete_support_event_subscription" + }, + "description": "Sample for DeleteSupportEventSubscription", + "file": "cloudsupport_v2_generated_support_event_subscription_service_delete_support_event_subscription_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2_generated_SupportEventSubscriptionService_DeleteSupportEventSubscription_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudsupport_v2_generated_support_event_subscription_service_delete_support_event_subscription_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceClient", + "shortName": "SupportEventSubscriptionServiceClient" + }, + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceClient.delete_support_event_subscription", + "method": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService.DeleteSupportEventSubscription", + "service": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "DeleteSupportEventSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2.types.DeleteSupportEventSubscriptionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2.types.SupportEventSubscription", + "shortName": "delete_support_event_subscription" + }, + "description": "Sample for DeleteSupportEventSubscription", + "file": "cloudsupport_v2_generated_support_event_subscription_service_delete_support_event_subscription_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2_generated_SupportEventSubscriptionService_DeleteSupportEventSubscription_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudsupport_v2_generated_support_event_subscription_service_delete_support_event_subscription_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceAsyncClient", + "shortName": "SupportEventSubscriptionServiceAsyncClient" + }, + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceAsyncClient.get_support_event_subscription", + "method": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService.GetSupportEventSubscription", + "service": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "GetSupportEventSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2.types.GetSupportEventSubscriptionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2.types.SupportEventSubscription", + "shortName": "get_support_event_subscription" + }, + "description": "Sample for GetSupportEventSubscription", + "file": "cloudsupport_v2_generated_support_event_subscription_service_get_support_event_subscription_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2_generated_SupportEventSubscriptionService_GetSupportEventSubscription_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudsupport_v2_generated_support_event_subscription_service_get_support_event_subscription_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceClient", + "shortName": "SupportEventSubscriptionServiceClient" + }, + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceClient.get_support_event_subscription", + "method": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService.GetSupportEventSubscription", + "service": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "GetSupportEventSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2.types.GetSupportEventSubscriptionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2.types.SupportEventSubscription", + "shortName": "get_support_event_subscription" + }, + "description": "Sample for GetSupportEventSubscription", + "file": "cloudsupport_v2_generated_support_event_subscription_service_get_support_event_subscription_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2_generated_SupportEventSubscriptionService_GetSupportEventSubscription_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudsupport_v2_generated_support_event_subscription_service_get_support_event_subscription_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceAsyncClient", + "shortName": "SupportEventSubscriptionServiceAsyncClient" + }, + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceAsyncClient.list_support_event_subscriptions", + "method": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService.ListSupportEventSubscriptions", + "service": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "ListSupportEventSubscriptions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2.types.ListSupportEventSubscriptionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2.services.support_event_subscription_service.pagers.ListSupportEventSubscriptionsAsyncPager", + "shortName": "list_support_event_subscriptions" + }, + "description": "Sample for ListSupportEventSubscriptions", + "file": "cloudsupport_v2_generated_support_event_subscription_service_list_support_event_subscriptions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2_generated_SupportEventSubscriptionService_ListSupportEventSubscriptions_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudsupport_v2_generated_support_event_subscription_service_list_support_event_subscriptions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceClient", + "shortName": "SupportEventSubscriptionServiceClient" + }, + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceClient.list_support_event_subscriptions", + "method": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService.ListSupportEventSubscriptions", + "service": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "ListSupportEventSubscriptions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2.types.ListSupportEventSubscriptionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2.services.support_event_subscription_service.pagers.ListSupportEventSubscriptionsPager", + "shortName": "list_support_event_subscriptions" + }, + "description": "Sample for ListSupportEventSubscriptions", + "file": "cloudsupport_v2_generated_support_event_subscription_service_list_support_event_subscriptions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2_generated_SupportEventSubscriptionService_ListSupportEventSubscriptions_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudsupport_v2_generated_support_event_subscription_service_list_support_event_subscriptions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceAsyncClient", + "shortName": "SupportEventSubscriptionServiceAsyncClient" + }, + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceAsyncClient.undelete_support_event_subscription", + "method": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService.UndeleteSupportEventSubscription", + "service": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "UndeleteSupportEventSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2.types.UndeleteSupportEventSubscriptionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2.types.SupportEventSubscription", + "shortName": "undelete_support_event_subscription" + }, + "description": "Sample for UndeleteSupportEventSubscription", + "file": "cloudsupport_v2_generated_support_event_subscription_service_undelete_support_event_subscription_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2_generated_SupportEventSubscriptionService_UndeleteSupportEventSubscription_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudsupport_v2_generated_support_event_subscription_service_undelete_support_event_subscription_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceClient", + "shortName": "SupportEventSubscriptionServiceClient" + }, + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceClient.undelete_support_event_subscription", + "method": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService.UndeleteSupportEventSubscription", + "service": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "UndeleteSupportEventSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2.types.UndeleteSupportEventSubscriptionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2.types.SupportEventSubscription", + "shortName": "undelete_support_event_subscription" + }, + "description": "Sample for UndeleteSupportEventSubscription", + "file": "cloudsupport_v2_generated_support_event_subscription_service_undelete_support_event_subscription_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2_generated_SupportEventSubscriptionService_UndeleteSupportEventSubscription_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudsupport_v2_generated_support_event_subscription_service_undelete_support_event_subscription_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceAsyncClient", + "shortName": "SupportEventSubscriptionServiceAsyncClient" + }, + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceAsyncClient.update_support_event_subscription", + "method": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService.UpdateSupportEventSubscription", + "service": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "UpdateSupportEventSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2.types.UpdateSupportEventSubscriptionRequest" + }, + { + "name": "support_event_subscription", + "type": "google.cloud.support_v2.types.SupportEventSubscription" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2.types.SupportEventSubscription", + "shortName": "update_support_event_subscription" + }, + "description": "Sample for UpdateSupportEventSubscription", + "file": "cloudsupport_v2_generated_support_event_subscription_service_update_support_event_subscription_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2_generated_SupportEventSubscriptionService_UpdateSupportEventSubscription_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": "cloudsupport_v2_generated_support_event_subscription_service_update_support_event_subscription_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceClient", + "shortName": "SupportEventSubscriptionServiceClient" + }, + "fullName": "google.cloud.support_v2.SupportEventSubscriptionServiceClient.update_support_event_subscription", + "method": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService.UpdateSupportEventSubscription", + "service": { + "fullName": "google.cloud.support.v2.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "UpdateSupportEventSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2.types.UpdateSupportEventSubscriptionRequest" + }, + { + "name": "support_event_subscription", + "type": "google.cloud.support_v2.types.SupportEventSubscription" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2.types.SupportEventSubscription", + "shortName": "update_support_event_subscription" + }, + "description": "Sample for UpdateSupportEventSubscription", + "file": "cloudsupport_v2_generated_support_event_subscription_service_update_support_event_subscription_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2_generated_SupportEventSubscriptionService_UpdateSupportEventSubscription_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": "cloudsupport_v2_generated_support_event_subscription_service_update_support_event_subscription_sync.py" } ] } diff --git a/packages/google-cloud-support/samples/generated_samples/snippet_metadata_google.cloud.support.v2beta.json b/packages/google-cloud-support/samples/generated_samples/snippet_metadata_google.cloud.support.v2beta.json index 50ed0c25de8d..42a1d9b55e74 100644 --- a/packages/google-cloud-support/samples/generated_samples/snippet_metadata_google.cloud.support.v2beta.json +++ b/packages/google-cloud-support/samples/generated_samples/snippet_metadata_google.cloud.support.v2beta.json @@ -2256,6 +2256,980 @@ } ], "title": "cloudsupport_v2beta_generated_feed_service_show_feed_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceAsyncClient", + "shortName": "SupportEventSubscriptionServiceAsyncClient" + }, + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceAsyncClient.create_support_event_subscription", + "method": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService.CreateSupportEventSubscription", + "service": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "CreateSupportEventSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2beta.types.CreateSupportEventSubscriptionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "support_event_subscription", + "type": "google.cloud.support_v2beta.types.SupportEventSubscription" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2beta.types.SupportEventSubscription", + "shortName": "create_support_event_subscription" + }, + "description": "Sample for CreateSupportEventSubscription", + "file": "cloudsupport_v2beta_generated_support_event_subscription_service_create_support_event_subscription_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2beta_generated_SupportEventSubscriptionService_CreateSupportEventSubscription_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": "cloudsupport_v2beta_generated_support_event_subscription_service_create_support_event_subscription_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceClient", + "shortName": "SupportEventSubscriptionServiceClient" + }, + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceClient.create_support_event_subscription", + "method": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService.CreateSupportEventSubscription", + "service": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "CreateSupportEventSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2beta.types.CreateSupportEventSubscriptionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "support_event_subscription", + "type": "google.cloud.support_v2beta.types.SupportEventSubscription" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2beta.types.SupportEventSubscription", + "shortName": "create_support_event_subscription" + }, + "description": "Sample for CreateSupportEventSubscription", + "file": "cloudsupport_v2beta_generated_support_event_subscription_service_create_support_event_subscription_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2beta_generated_SupportEventSubscriptionService_CreateSupportEventSubscription_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": "cloudsupport_v2beta_generated_support_event_subscription_service_create_support_event_subscription_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceAsyncClient", + "shortName": "SupportEventSubscriptionServiceAsyncClient" + }, + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceAsyncClient.delete_support_event_subscription", + "method": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService.DeleteSupportEventSubscription", + "service": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "DeleteSupportEventSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2beta.types.DeleteSupportEventSubscriptionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2beta.types.SupportEventSubscription", + "shortName": "delete_support_event_subscription" + }, + "description": "Sample for DeleteSupportEventSubscription", + "file": "cloudsupport_v2beta_generated_support_event_subscription_service_delete_support_event_subscription_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2beta_generated_SupportEventSubscriptionService_DeleteSupportEventSubscription_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudsupport_v2beta_generated_support_event_subscription_service_delete_support_event_subscription_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceClient", + "shortName": "SupportEventSubscriptionServiceClient" + }, + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceClient.delete_support_event_subscription", + "method": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService.DeleteSupportEventSubscription", + "service": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "DeleteSupportEventSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2beta.types.DeleteSupportEventSubscriptionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2beta.types.SupportEventSubscription", + "shortName": "delete_support_event_subscription" + }, + "description": "Sample for DeleteSupportEventSubscription", + "file": "cloudsupport_v2beta_generated_support_event_subscription_service_delete_support_event_subscription_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2beta_generated_SupportEventSubscriptionService_DeleteSupportEventSubscription_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudsupport_v2beta_generated_support_event_subscription_service_delete_support_event_subscription_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceAsyncClient", + "shortName": "SupportEventSubscriptionServiceAsyncClient" + }, + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceAsyncClient.get_support_event_subscription", + "method": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService.GetSupportEventSubscription", + "service": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "GetSupportEventSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2beta.types.GetSupportEventSubscriptionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2beta.types.SupportEventSubscription", + "shortName": "get_support_event_subscription" + }, + "description": "Sample for GetSupportEventSubscription", + "file": "cloudsupport_v2beta_generated_support_event_subscription_service_get_support_event_subscription_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2beta_generated_SupportEventSubscriptionService_GetSupportEventSubscription_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudsupport_v2beta_generated_support_event_subscription_service_get_support_event_subscription_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceClient", + "shortName": "SupportEventSubscriptionServiceClient" + }, + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceClient.get_support_event_subscription", + "method": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService.GetSupportEventSubscription", + "service": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "GetSupportEventSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2beta.types.GetSupportEventSubscriptionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2beta.types.SupportEventSubscription", + "shortName": "get_support_event_subscription" + }, + "description": "Sample for GetSupportEventSubscription", + "file": "cloudsupport_v2beta_generated_support_event_subscription_service_get_support_event_subscription_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2beta_generated_SupportEventSubscriptionService_GetSupportEventSubscription_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudsupport_v2beta_generated_support_event_subscription_service_get_support_event_subscription_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceAsyncClient", + "shortName": "SupportEventSubscriptionServiceAsyncClient" + }, + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceAsyncClient.list_support_event_subscriptions", + "method": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService.ListSupportEventSubscriptions", + "service": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "ListSupportEventSubscriptions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2beta.types.ListSupportEventSubscriptionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2beta.services.support_event_subscription_service.pagers.ListSupportEventSubscriptionsAsyncPager", + "shortName": "list_support_event_subscriptions" + }, + "description": "Sample for ListSupportEventSubscriptions", + "file": "cloudsupport_v2beta_generated_support_event_subscription_service_list_support_event_subscriptions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2beta_generated_SupportEventSubscriptionService_ListSupportEventSubscriptions_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudsupport_v2beta_generated_support_event_subscription_service_list_support_event_subscriptions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceClient", + "shortName": "SupportEventSubscriptionServiceClient" + }, + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceClient.list_support_event_subscriptions", + "method": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService.ListSupportEventSubscriptions", + "service": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "ListSupportEventSubscriptions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2beta.types.ListSupportEventSubscriptionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2beta.services.support_event_subscription_service.pagers.ListSupportEventSubscriptionsPager", + "shortName": "list_support_event_subscriptions" + }, + "description": "Sample for ListSupportEventSubscriptions", + "file": "cloudsupport_v2beta_generated_support_event_subscription_service_list_support_event_subscriptions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2beta_generated_SupportEventSubscriptionService_ListSupportEventSubscriptions_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudsupport_v2beta_generated_support_event_subscription_service_list_support_event_subscriptions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceAsyncClient", + "shortName": "SupportEventSubscriptionServiceAsyncClient" + }, + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceAsyncClient.undelete_support_event_subscription", + "method": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService.UndeleteSupportEventSubscription", + "service": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "UndeleteSupportEventSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2beta.types.UndeleteSupportEventSubscriptionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2beta.types.SupportEventSubscription", + "shortName": "undelete_support_event_subscription" + }, + "description": "Sample for UndeleteSupportEventSubscription", + "file": "cloudsupport_v2beta_generated_support_event_subscription_service_undelete_support_event_subscription_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2beta_generated_SupportEventSubscriptionService_UndeleteSupportEventSubscription_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudsupport_v2beta_generated_support_event_subscription_service_undelete_support_event_subscription_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceClient", + "shortName": "SupportEventSubscriptionServiceClient" + }, + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceClient.undelete_support_event_subscription", + "method": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService.UndeleteSupportEventSubscription", + "service": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "UndeleteSupportEventSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2beta.types.UndeleteSupportEventSubscriptionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2beta.types.SupportEventSubscription", + "shortName": "undelete_support_event_subscription" + }, + "description": "Sample for UndeleteSupportEventSubscription", + "file": "cloudsupport_v2beta_generated_support_event_subscription_service_undelete_support_event_subscription_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2beta_generated_SupportEventSubscriptionService_UndeleteSupportEventSubscription_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudsupport_v2beta_generated_support_event_subscription_service_undelete_support_event_subscription_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceAsyncClient", + "shortName": "SupportEventSubscriptionServiceAsyncClient" + }, + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceAsyncClient.update_support_event_subscription", + "method": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService.UpdateSupportEventSubscription", + "service": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "UpdateSupportEventSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2beta.types.UpdateSupportEventSubscriptionRequest" + }, + { + "name": "support_event_subscription", + "type": "google.cloud.support_v2beta.types.SupportEventSubscription" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2beta.types.SupportEventSubscription", + "shortName": "update_support_event_subscription" + }, + "description": "Sample for UpdateSupportEventSubscription", + "file": "cloudsupport_v2beta_generated_support_event_subscription_service_update_support_event_subscription_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2beta_generated_SupportEventSubscriptionService_UpdateSupportEventSubscription_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": "cloudsupport_v2beta_generated_support_event_subscription_service_update_support_event_subscription_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceClient", + "shortName": "SupportEventSubscriptionServiceClient" + }, + "fullName": "google.cloud.support_v2beta.SupportEventSubscriptionServiceClient.update_support_event_subscription", + "method": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService.UpdateSupportEventSubscription", + "service": { + "fullName": "google.cloud.support.v2beta.SupportEventSubscriptionService", + "shortName": "SupportEventSubscriptionService" + }, + "shortName": "UpdateSupportEventSubscription" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.support_v2beta.types.UpdateSupportEventSubscriptionRequest" + }, + { + "name": "support_event_subscription", + "type": "google.cloud.support_v2beta.types.SupportEventSubscription" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.support_v2beta.types.SupportEventSubscription", + "shortName": "update_support_event_subscription" + }, + "description": "Sample for UpdateSupportEventSubscription", + "file": "cloudsupport_v2beta_generated_support_event_subscription_service_update_support_event_subscription_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudsupport_v2beta_generated_SupportEventSubscriptionService_UpdateSupportEventSubscription_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": "cloudsupport_v2beta_generated_support_event_subscription_service_update_support_event_subscription_sync.py" } ] } diff --git a/packages/google-cloud-support/tests/unit/gapic/support_v2/test_support_event_subscription_service.py b/packages/google-cloud-support/tests/unit/gapic/support_v2/test_support_event_subscription_service.py new file mode 100644 index 000000000000..b33845137a60 --- /dev/null +++ b/packages/google-cloud-support/tests/unit/gapic/support_v2/test_support_event_subscription_service.py @@ -0,0 +1,7498 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.auth +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + +from google.cloud.support_v2.services.support_event_subscription_service import ( + SupportEventSubscriptionServiceAsyncClient, + SupportEventSubscriptionServiceClient, + pagers, + transports, +) +from google.cloud.support_v2.types import ( + support_event_subscription, + support_event_subscription_service, +) +from google.cloud.support_v2.types import ( + support_event_subscription as gcs_support_event_subscription, +) + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +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" + custom_endpoint = ".custom" + + assert ( + SupportEventSubscriptionServiceClient._get_default_mtls_endpoint(None) is None + ) + assert ( + SupportEventSubscriptionServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + SupportEventSubscriptionServiceClient._get_default_mtls_endpoint( + api_mtls_endpoint + ) + == api_mtls_endpoint + ) + assert ( + SupportEventSubscriptionServiceClient._get_default_mtls_endpoint( + sandbox_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + SupportEventSubscriptionServiceClient._get_default_mtls_endpoint( + sandbox_mtls_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + SupportEventSubscriptionServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + assert ( + SupportEventSubscriptionServiceClient._get_default_mtls_endpoint( + custom_endpoint + ) + == custom_endpoint + ) + + +def test__read_environment_variables(): + assert SupportEventSubscriptionServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SupportEventSubscriptionServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert SupportEventSubscriptionServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + SupportEventSubscriptionServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert ( + SupportEventSubscriptionServiceClient._read_environment_variables() + == ( + False, + "auto", + None, + ) + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert SupportEventSubscriptionServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert SupportEventSubscriptionServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert SupportEventSubscriptionServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + SupportEventSubscriptionServiceClient._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 SupportEventSubscriptionServiceClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=True + ): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is True + ) + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=False + ): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is False + ) + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is True + ) + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is False + ) + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is True + ) + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} + ): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is False + ) + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is True + ) + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} + ): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is False + ) + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is False + ) + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + with pytest.raises(ValueError): + SupportEventSubscriptionServiceClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is False + ) + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is False + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert ( + SupportEventSubscriptionServiceClient._get_client_cert_source(None, False) + is None + ) + assert ( + SupportEventSubscriptionServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + SupportEventSubscriptionServiceClient._get_client_cert_source( + mock_provided_cert_source, True + ) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + SupportEventSubscriptionServiceClient._get_client_cert_source( + None, True + ) + is mock_default_cert_source + ) + assert ( + SupportEventSubscriptionServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + SupportEventSubscriptionServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SupportEventSubscriptionServiceClient), +) +@mock.patch.object( + SupportEventSubscriptionServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SupportEventSubscriptionServiceAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = SupportEventSubscriptionServiceClient._DEFAULT_UNIVERSE + default_endpoint = ( + SupportEventSubscriptionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) + mock_universe = "bar.com" + mock_endpoint = ( + SupportEventSubscriptionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + ) + + assert ( + SupportEventSubscriptionServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + SupportEventSubscriptionServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == SupportEventSubscriptionServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SupportEventSubscriptionServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + SupportEventSubscriptionServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == SupportEventSubscriptionServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SupportEventSubscriptionServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == SupportEventSubscriptionServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SupportEventSubscriptionServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + SupportEventSubscriptionServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + SupportEventSubscriptionServiceClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + SupportEventSubscriptionServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + SupportEventSubscriptionServiceClient._get_universe_domain( + None, universe_domain_env + ) + == universe_domain_env + ) + assert ( + SupportEventSubscriptionServiceClient._get_universe_domain(None, None) + == SupportEventSubscriptionServiceClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + SupportEventSubscriptionServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = SupportEventSubscriptionServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = SupportEventSubscriptionServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (SupportEventSubscriptionServiceClient, "grpc"), + (SupportEventSubscriptionServiceAsyncClient, "grpc_asyncio"), + (SupportEventSubscriptionServiceClient, "rest"), + ], +) +def test_support_event_subscription_service_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "cloudsupport.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudsupport.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.SupportEventSubscriptionServiceGrpcTransport, "grpc"), + ( + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (transports.SupportEventSubscriptionServiceRestTransport, "rest"), + ], +) +def test_support_event_subscription_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (SupportEventSubscriptionServiceClient, "grpc"), + (SupportEventSubscriptionServiceAsyncClient, "grpc_asyncio"), + (SupportEventSubscriptionServiceClient, "rest"), + ], +) +def test_support_event_subscription_service_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "cloudsupport.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudsupport.googleapis.com" + ) + + +def test_support_event_subscription_service_client_get_transport_class(): + transport = SupportEventSubscriptionServiceClient.get_transport_class() + available_transports = [ + transports.SupportEventSubscriptionServiceGrpcTransport, + transports.SupportEventSubscriptionServiceRestTransport, + ] + assert transport in available_transports + + transport = SupportEventSubscriptionServiceClient.get_transport_class("grpc") + assert transport == transports.SupportEventSubscriptionServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceGrpcTransport, + "grpc", + ), + ( + SupportEventSubscriptionServiceAsyncClient, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + SupportEventSubscriptionServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SupportEventSubscriptionServiceClient), +) +@mock.patch.object( + SupportEventSubscriptionServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SupportEventSubscriptionServiceAsyncClient), +) +def test_support_event_subscription_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object( + SupportEventSubscriptionServiceClient, "get_transport_class" + ) as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object( + SupportEventSubscriptionServiceClient, "get_transport_class" + ) as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check 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 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", + [ + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceGrpcTransport, + "grpc", + "true", + ), + ( + SupportEventSubscriptionServiceAsyncClient, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceGrpcTransport, + "grpc", + "false", + ), + ( + SupportEventSubscriptionServiceAsyncClient, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceRestTransport, + "rest", + "true", + ), + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + SupportEventSubscriptionServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SupportEventSubscriptionServiceClient), +) +@mock.patch.object( + SupportEventSubscriptionServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SupportEventSubscriptionServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_support_event_subscription_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", + [SupportEventSubscriptionServiceClient, SupportEventSubscriptionServiceAsyncClient], +) +@mock.patch.object( + SupportEventSubscriptionServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SupportEventSubscriptionServiceClient), +) +@mock.patch.object( + SupportEventSubscriptionServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SupportEventSubscriptionServiceAsyncClient), +) +def test_support_event_subscription_service_client_get_mtls_endpoint_and_cert_source( + client_class, +): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + 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 cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # 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`" + ) + + +@pytest.mark.parametrize( + "client_class", + [SupportEventSubscriptionServiceClient, SupportEventSubscriptionServiceAsyncClient], +) +@mock.patch.object( + SupportEventSubscriptionServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SupportEventSubscriptionServiceClient), +) +@mock.patch.object( + SupportEventSubscriptionServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SupportEventSubscriptionServiceAsyncClient), +) +def test_support_event_subscription_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = SupportEventSubscriptionServiceClient._DEFAULT_UNIVERSE + default_endpoint = ( + SupportEventSubscriptionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) + mock_universe = "bar.com" + mock_endpoint = ( + SupportEventSubscriptionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + 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", + [ + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceGrpcTransport, + "grpc", + ), + ( + SupportEventSubscriptionServiceAsyncClient, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceRestTransport, + "rest", + ), + ], +) +def test_support_event_subscription_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SupportEventSubscriptionServiceAsyncClient, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceRestTransport, + "rest", + None, + ), + ], +) +def test_support_event_subscription_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_support_event_subscription_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.support_v2.services.support_event_subscription_service.transports.SupportEventSubscriptionServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = SupportEventSubscriptionServiceClient( + 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", + [ + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SupportEventSubscriptionServiceAsyncClient, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_support_event_subscription_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudsupport.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="cloudsupport.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.CreateSupportEventSubscriptionRequest(), + {}, + ], +) +def test_create_support_event_subscription(request_type, transport: str = "grpc"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=gcs_support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + response = client.create_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.CreateSupportEventSubscriptionRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == gcs_support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +def test_create_support_event_subscription_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = support_event_subscription_service.CreateSupportEventSubscriptionRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_support_event_subscription), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_support_event_subscription(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.CreateSupportEventSubscriptionRequest( + parent="parent_value", + ) + ) + assert args[0] == request_msg + + +def test_create_support_event_subscription_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_support_event_subscription + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_support_event_subscription + ] = mock_rpc + request = {} + client.create_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_support_event_subscription_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_support_event_subscription + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_support_event_subscription + ] = mock_rpc + + request = {} + await client.create_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.CreateSupportEventSubscriptionRequest(), + {}, + ], +) +async def test_create_support_event_subscription_async( + request_type, transport: str = "grpc_asyncio" +): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=gcs_support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + ) + response = await client.create_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.CreateSupportEventSubscriptionRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == gcs_support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +def test_create_support_event_subscription_field_headers(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = support_event_subscription_service.CreateSupportEventSubscriptionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_support_event_subscription), "__call__" + ) as call: + call.return_value = gcs_support_event_subscription.SupportEventSubscription() + client.create_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_support_event_subscription_field_headers_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = support_event_subscription_service.CreateSupportEventSubscriptionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_support_event_subscription), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_support_event_subscription.SupportEventSubscription() + ) + await client.create_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_support_event_subscription_flattened(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_support_event_subscription.SupportEventSubscription() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_support_event_subscription( + parent="parent_value", + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + ) + + # Establish that the underlying call was made with the expected + # request object 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].support_event_subscription + mock_val = gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ) + assert arg == mock_val + + +def test_create_support_event_subscription_flattened_error(): + client = SupportEventSubscriptionServiceClient( + credentials=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_support_event_subscription( + support_event_subscription_service.CreateSupportEventSubscriptionRequest(), + parent="parent_value", + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + ) + + +@pytest.mark.asyncio +async def test_create_support_event_subscription_flattened_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_support_event_subscription.SupportEventSubscription() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_support_event_subscription.SupportEventSubscription() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_support_event_subscription( + parent="parent_value", + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + ) + + # Establish that the underlying call was made with the expected + # request 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].support_event_subscription + mock_val = gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_support_event_subscription_flattened_error_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_support_event_subscription( + support_event_subscription_service.CreateSupportEventSubscriptionRequest(), + parent="parent_value", + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.GetSupportEventSubscriptionRequest(), + {}, + ], +) +def test_get_support_event_subscription(request_type, transport: str = "grpc"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + response = client.get_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.GetSupportEventSubscriptionRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +def test_get_support_event_subscription_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = support_event_subscription_service.GetSupportEventSubscriptionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_support_event_subscription), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_support_event_subscription(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.GetSupportEventSubscriptionRequest( + name="name_value", + ) + ) + assert args[0] == request_msg + + +def test_get_support_event_subscription_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_support_event_subscription + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_support_event_subscription + ] = mock_rpc + request = {} + client.get_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_support_event_subscription_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_support_event_subscription + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_support_event_subscription + ] = mock_rpc + + request = {} + await client.get_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.GetSupportEventSubscriptionRequest(), + {}, + ], +) +async def test_get_support_event_subscription_async( + request_type, transport: str = "grpc_asyncio" +): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + ) + response = await client.get_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.GetSupportEventSubscriptionRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +def test_get_support_event_subscription_field_headers(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = support_event_subscription_service.GetSupportEventSubscriptionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_support_event_subscription), "__call__" + ) as call: + call.return_value = support_event_subscription.SupportEventSubscription() + client.get_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_support_event_subscription_field_headers_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = support_event_subscription_service.GetSupportEventSubscriptionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_support_event_subscription), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription() + ) + await client.get_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_support_event_subscription_flattened(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = support_event_subscription.SupportEventSubscription() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_support_event_subscription( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_support_event_subscription_flattened_error(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_support_event_subscription( + support_event_subscription_service.GetSupportEventSubscriptionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_support_event_subscription_flattened_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = support_event_subscription.SupportEventSubscription() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_support_event_subscription( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_support_event_subscription_flattened_error_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_support_event_subscription( + support_event_subscription_service.GetSupportEventSubscriptionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.ListSupportEventSubscriptionsRequest(), + {}, + ], +) +def test_list_support_event_subscriptions(request_type, transport: str = "grpc"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + next_page_token="next_page_token_value", + ) + ) + response = client.list_support_event_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSupportEventSubscriptionsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_support_event_subscriptions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = support_event_subscription_service.ListSupportEventSubscriptionsRequest( + 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_support_event_subscriptions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_support_event_subscriptions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest( + parent="parent_value", + filter="filter_value", + page_token="page_token_value", + ) + ) + assert args[0] == request_msg + + +def test_list_support_event_subscriptions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_support_event_subscriptions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_support_event_subscriptions + ] = mock_rpc + request = {} + client.list_support_event_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_support_event_subscriptions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_support_event_subscriptions_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_support_event_subscriptions + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_support_event_subscriptions + ] = mock_rpc + + request = {} + await client.list_support_event_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_support_event_subscriptions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.ListSupportEventSubscriptionsRequest(), + {}, + ], +) +async def test_list_support_event_subscriptions_async( + request_type, transport: str = "grpc_asyncio" +): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_support_event_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSupportEventSubscriptionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_support_event_subscriptions_field_headers(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = support_event_subscription_service.ListSupportEventSubscriptionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + call.return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse() + ) + client.list_support_event_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_support_event_subscriptions_field_headers_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = support_event_subscription_service.ListSupportEventSubscriptionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription_service.ListSupportEventSubscriptionsResponse() + ) + await client.list_support_event_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_support_event_subscriptions_flattened(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_support_event_subscriptions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_support_event_subscriptions_flattened_error(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_support_event_subscriptions( + support_event_subscription_service.ListSupportEventSubscriptionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_support_event_subscriptions_flattened_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription_service.ListSupportEventSubscriptionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_support_event_subscriptions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_support_event_subscriptions_flattened_error_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_support_event_subscriptions( + support_event_subscription_service.ListSupportEventSubscriptionsRequest(), + parent="parent_value", + ) + + +def test_list_support_event_subscriptions_pager(transport_name: str = "grpc"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + ], + next_page_token="abc", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[], + next_page_token="def", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + ], + next_page_token="ghi", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_support_event_subscriptions( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, support_event_subscription.SupportEventSubscription) + for i in results + ) + + +def test_list_support_event_subscriptions_pages(transport_name: str = "grpc"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + ], + next_page_token="abc", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[], + next_page_token="def", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + ], + next_page_token="ghi", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + ], + ), + RuntimeError, + ) + pages = list(client.list_support_event_subscriptions(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_support_event_subscriptions_async_pager(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + ], + next_page_token="abc", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[], + next_page_token="def", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + ], + next_page_token="ghi", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_support_event_subscriptions( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, support_event_subscription.SupportEventSubscription) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_support_event_subscriptions_async_pages(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + ], + next_page_token="abc", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[], + next_page_token="def", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + ], + next_page_token="ghi", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_support_event_subscriptions(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.UpdateSupportEventSubscriptionRequest(), + {}, + ], +) +def test_update_support_event_subscription(request_type, transport: str = "grpc"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=gcs_support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + response = client.update_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == gcs_support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +def test_update_support_event_subscription_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_support_event_subscription), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_support_event_subscription(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +def test_update_support_event_subscription_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_support_event_subscription + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_support_event_subscription + ] = mock_rpc + request = {} + client.update_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_support_event_subscription_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_support_event_subscription + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_support_event_subscription + ] = mock_rpc + + request = {} + await client.update_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.UpdateSupportEventSubscriptionRequest(), + {}, + ], +) +async def test_update_support_event_subscription_async( + request_type, transport: str = "grpc_asyncio" +): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=gcs_support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + ) + response = await client.update_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == gcs_support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +def test_update_support_event_subscription_field_headers(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + + request.support_event_subscription.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_support_event_subscription), "__call__" + ) as call: + call.return_value = gcs_support_event_subscription.SupportEventSubscription() + client.update_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "support_event_subscription.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_support_event_subscription_field_headers_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + + request.support_event_subscription.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_support_event_subscription), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_support_event_subscription.SupportEventSubscription() + ) + await client.update_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "support_event_subscription.name=name_value", + ) in kw["metadata"] + + +def test_update_support_event_subscription_flattened(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_support_event_subscription.SupportEventSubscription() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_support_event_subscription( + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + update_mask=field_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].support_event_subscription + mock_val = gcs_support_event_subscription.SupportEventSubscription( + name="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_support_event_subscription_flattened_error(): + client = SupportEventSubscriptionServiceClient( + credentials=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_support_event_subscription( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest(), + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_support_event_subscription_flattened_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_support_event_subscription.SupportEventSubscription() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_support_event_subscription.SupportEventSubscription() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_support_event_subscription( + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + update_mask=field_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].support_event_subscription + mock_val = gcs_support_event_subscription.SupportEventSubscription( + name="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_support_event_subscription_flattened_error_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_support_event_subscription( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest(), + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.DeleteSupportEventSubscriptionRequest(), + {}, + ], +) +def test_delete_support_event_subscription(request_type, transport: str = "grpc"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + response = client.delete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +def test_delete_support_event_subscription_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = support_event_subscription_service.DeleteSupportEventSubscriptionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_support_event_subscription), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_support_event_subscription(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest( + name="name_value", + ) + ) + assert args[0] == request_msg + + +def test_delete_support_event_subscription_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_support_event_subscription + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_support_event_subscription + ] = mock_rpc + request = {} + client.delete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_support_event_subscription_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_support_event_subscription + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_support_event_subscription + ] = mock_rpc + + request = {} + await client.delete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.DeleteSupportEventSubscriptionRequest(), + {}, + ], +) +async def test_delete_support_event_subscription_async( + request_type, transport: str = "grpc_asyncio" +): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + ) + response = await client.delete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +def test_delete_support_event_subscription_field_headers(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = support_event_subscription_service.DeleteSupportEventSubscriptionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_support_event_subscription), "__call__" + ) as call: + call.return_value = support_event_subscription.SupportEventSubscription() + client.delete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_support_event_subscription_field_headers_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = support_event_subscription_service.DeleteSupportEventSubscriptionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_support_event_subscription), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription() + ) + await client.delete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_support_event_subscription_flattened(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = support_event_subscription.SupportEventSubscription() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_support_event_subscription( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_support_event_subscription_flattened_error(): + client = SupportEventSubscriptionServiceClient( + credentials=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_support_event_subscription( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_support_event_subscription_flattened_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = support_event_subscription.SupportEventSubscription() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_support_event_subscription( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_support_event_subscription_flattened_error_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_support_event_subscription( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest(), + {}, + ], +) +def test_undelete_support_event_subscription(request_type, transport: str = "grpc"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + response = client.undelete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +def test_undelete_support_event_subscription_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = ( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest( + name="name_value", + ) + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_support_event_subscription), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.undelete_support_event_subscription(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest( + name="name_value", + ) + ) + assert args[0] == request_msg + + +def test_undelete_support_event_subscription_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.undelete_support_event_subscription + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.undelete_support_event_subscription + ] = mock_rpc + request = {} + client.undelete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.undelete_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_undelete_support_event_subscription_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.undelete_support_event_subscription + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.undelete_support_event_subscription + ] = mock_rpc + + request = {} + await client.undelete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.undelete_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest(), + {}, + ], +) +async def test_undelete_support_event_subscription_async( + request_type, transport: str = "grpc_asyncio" +): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + ) + response = await client.undelete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +def test_undelete_support_event_subscription_field_headers(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest() + ) + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_support_event_subscription), "__call__" + ) as call: + call.return_value = support_event_subscription.SupportEventSubscription() + client.undelete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_undelete_support_event_subscription_field_headers_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest() + ) + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_support_event_subscription), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription() + ) + await client.undelete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_create_support_event_subscription_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_support_event_subscription + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_support_event_subscription + ] = mock_rpc + + request = {} + client.create_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_support_event_subscription_rest_required_fields( + request_type=support_event_subscription_service.CreateSupportEventSubscriptionRequest, +): + transport_class = transports.SupportEventSubscriptionServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_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_support_event_subscription._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_support_event_subscription._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_support_event_subscription.SupportEventSubscription() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["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_support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_support_event_subscription(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_support_event_subscription_rest_unset_required_fields(): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.create_support_event_subscription._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "supportEventSubscription", + ) + ) + ) + + +def test_create_support_event_subscription_rest_flattened(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcs_support_event_subscription.SupportEventSubscription() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "sample1/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_support_event_subscription(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=*/*}/supportEventSubscriptions" % client.transport._host, + args[1], + ) + + +def test_create_support_event_subscription_rest_flattened_error( + transport: str = "rest", +): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.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_support_event_subscription( + support_event_subscription_service.CreateSupportEventSubscriptionRequest(), + parent="parent_value", + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + ) + + +def test_get_support_event_subscription_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_support_event_subscription + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_support_event_subscription + ] = mock_rpc + + request = {} + client.get_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_support_event_subscription_rest_required_fields( + request_type=support_event_subscription_service.GetSupportEventSubscriptionRequest, +): + transport_class = transports.SupportEventSubscriptionServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_support_event_subscription._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_support_event_subscription._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = support_event_subscription.SupportEventSubscription() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_support_event_subscription(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_support_event_subscription_rest_unset_required_fields(): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_support_event_subscription._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_support_event_subscription_rest_flattened(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = support_event_subscription.SupportEventSubscription() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "sample1/sample2/supportEventSubscriptions/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 = support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_support_event_subscription(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=*/*/supportEventSubscriptions/*}" % client.transport._host, + args[1], + ) + + +def test_get_support_event_subscription_rest_flattened_error(transport: str = "rest"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_support_event_subscription( + support_event_subscription_service.GetSupportEventSubscriptionRequest(), + name="name_value", + ) + + +def test_list_support_event_subscriptions_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_support_event_subscriptions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_support_event_subscriptions + ] = mock_rpc + + request = {} + client.list_support_event_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_support_event_subscriptions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_support_event_subscriptions_rest_required_fields( + request_type=support_event_subscription_service.ListSupportEventSubscriptionsRequest, +): + transport_class = transports.SupportEventSubscriptionServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_support_event_subscriptions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_support_event_subscriptions._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", + "show_deleted", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse() + ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = support_event_subscription_service.ListSupportEventSubscriptionsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_support_event_subscriptions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_support_event_subscriptions_rest_unset_required_fields(): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.list_support_event_subscriptions._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + "showDeleted", + ) + ) + & set(("parent",)) + ) + + +def test_list_support_event_subscriptions_rest_flattened(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse() + ) + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "sample1/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 = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_support_event_subscriptions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=*/*}/supportEventSubscriptions" % client.transport._host, + args[1], + ) + + +def test_list_support_event_subscriptions_rest_flattened_error(transport: str = "rest"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.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_support_event_subscriptions( + support_event_subscription_service.ListSupportEventSubscriptionsRequest(), + parent="parent_value", + ) + + +def test_list_support_event_subscriptions_rest_pager(transport: str = "rest"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + ], + next_page_token="abc", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[], + next_page_token="def", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + ], + next_page_token="ghi", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + support_event_subscription_service.ListSupportEventSubscriptionsResponse.to_json( + x + ) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "sample1/sample2"} + + pager = client.list_support_event_subscriptions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, support_event_subscription.SupportEventSubscription) + for i in results + ) + + pages = list( + client.list_support_event_subscriptions(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_update_support_event_subscription_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_support_event_subscription + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_support_event_subscription + ] = mock_rpc + + request = {} + client.update_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_support_event_subscription_rest_required_fields( + request_type=support_event_subscription_service.UpdateSupportEventSubscriptionRequest, +): + transport_class = transports.SupportEventSubscriptionServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_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_support_event_subscription._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_support_event_subscription._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_support_event_subscription.SupportEventSubscription() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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_support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_support_event_subscription(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_support_event_subscription_rest_unset_required_fields(): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.update_support_event_subscription._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set(("updateMask",)) & set(("supportEventSubscription",)) + ) + + +def test_update_support_event_subscription_rest_flattened(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcs_support_event_subscription.SupportEventSubscription() + + # get arguments that satisfy an http rule for this method + sample_request = { + "support_event_subscription": { + "name": "sample1/sample2/supportEventSubscriptions/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + 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_support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_support_event_subscription(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{support_event_subscription.name=*/*/supportEventSubscriptions/*}" + % client.transport._host, + args[1], + ) + + +def test_update_support_event_subscription_rest_flattened_error( + transport: str = "rest", +): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.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_support_event_subscription( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest(), + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_support_event_subscription_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_support_event_subscription + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_support_event_subscription + ] = mock_rpc + + request = {} + client.delete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_support_event_subscription_rest_required_fields( + request_type=support_event_subscription_service.DeleteSupportEventSubscriptionRequest, +): + transport_class = transports.SupportEventSubscriptionServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_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_support_event_subscription._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_support_event_subscription._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = support_event_subscription.SupportEventSubscription() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + # Convert return value to protobuf type + return_value = support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_support_event_subscription(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_support_event_subscription_rest_unset_required_fields(): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.delete_support_event_subscription._get_unset_required_fields({}) + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_support_event_subscription_rest_flattened(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = support_event_subscription.SupportEventSubscription() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "sample1/sample2/supportEventSubscriptions/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 = support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_support_event_subscription(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=*/*/supportEventSubscriptions/*}" % client.transport._host, + args[1], + ) + + +def test_delete_support_event_subscription_rest_flattened_error( + transport: str = "rest", +): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.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_support_event_subscription( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest(), + name="name_value", + ) + + +def test_undelete_support_event_subscription_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.undelete_support_event_subscription + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.undelete_support_event_subscription + ] = mock_rpc + + request = {} + client.undelete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.undelete_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_undelete_support_event_subscription_rest_required_fields( + request_type=support_event_subscription_service.UndeleteSupportEventSubscriptionRequest, +): + transport_class = transports.SupportEventSubscriptionServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).undelete_support_event_subscription._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).undelete_support_event_subscription._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = support_event_subscription.SupportEventSubscription() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.undelete_support_event_subscription(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_undelete_support_event_subscription_rest_unset_required_fields(): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.undelete_support_event_subscription._get_unset_required_fields({}) + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SupportEventSubscriptionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SupportEventSubscriptionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SupportEventSubscriptionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SupportEventSubscriptionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SupportEventSubscriptionServiceClient( + 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 = SupportEventSubscriptionServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SupportEventSubscriptionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SupportEventSubscriptionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SupportEventSubscriptionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SupportEventSubscriptionServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SupportEventSubscriptionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SupportEventSubscriptionServiceGrpcTransport, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + transports.SupportEventSubscriptionServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = SupportEventSubscriptionServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_support_event_subscription_empty_call_grpc(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_support_event_subscription), "__call__" + ) as call: + call.return_value = gcs_support_event_subscription.SupportEventSubscription() + client.create_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.CreateSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_support_event_subscription_empty_call_grpc(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_support_event_subscription), "__call__" + ) as call: + call.return_value = support_event_subscription.SupportEventSubscription() + client.get_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.GetSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_support_event_subscriptions_empty_call_grpc(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + call.return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse() + ) + client.list_support_event_subscriptions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_support_event_subscription_empty_call_grpc(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_support_event_subscription), "__call__" + ) as call: + call.return_value = gcs_support_event_subscription.SupportEventSubscription() + client.update_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_support_event_subscription_empty_call_grpc(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_support_event_subscription), "__call__" + ) as call: + call.return_value = support_event_subscription.SupportEventSubscription() + client.delete_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_undelete_support_event_subscription_empty_call_grpc(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.undelete_support_event_subscription), "__call__" + ) as call: + call.return_value = support_event_subscription.SupportEventSubscription() + client.undelete_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = SupportEventSubscriptionServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_support_event_subscription_empty_call_grpc_asyncio(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=gcs_support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + ) + await client.create_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.CreateSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_support_event_subscription_empty_call_grpc_asyncio(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + ) + await client.get_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.GetSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_support_event_subscriptions_empty_call_grpc_asyncio(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_support_event_subscriptions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_support_event_subscription_empty_call_grpc_asyncio(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=gcs_support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + ) + await client.update_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_support_event_subscription_empty_call_grpc_asyncio(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + ) + await client.delete_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_undelete_support_event_subscription_empty_call_grpc_asyncio(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.undelete_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + ) + await client.undelete_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = SupportEventSubscriptionServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_support_event_subscription_rest_bad_request( + request_type=support_event_subscription_service.CreateSupportEventSubscriptionRequest, +): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "sample1/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_support_event_subscription(request) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.CreateSupportEventSubscriptionRequest, + dict, + ], +) +def test_create_support_event_subscription_rest_call_success(request_type): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "sample1/sample2"} + request_init["support_event_subscription"] = { + "name": "name_value", + "pub_sub_topic": "pub_sub_topic_value", + "state": 1, + "failure_reason": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "purge_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 = support_event_subscription_service.CreateSupportEventSubscriptionRequest.meta.fields[ + "support_event_subscription" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "support_event_subscription" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["support_event_subscription"][field]) + ): + del request_init["support_event_subscription"][field][i][subfield] + else: + del request_init["support_event_subscription"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcs_support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=gcs_support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcs_support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_support_event_subscription(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == gcs_support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_support_event_subscription_rest_interceptors(null_interceptor): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SupportEventSubscriptionServiceRestInterceptor(), + ) + client = SupportEventSubscriptionServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_create_support_event_subscription", + ) as post, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_create_support_event_subscription_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "pre_create_support_event_subscription", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = support_event_subscription_service.CreateSupportEventSubscriptionRequest.pb( + support_event_subscription_service.CreateSupportEventSubscriptionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcs_support_event_subscription.SupportEventSubscription.to_json( + gcs_support_event_subscription.SupportEventSubscription() + ) + req.return_value.content = return_value + + request = ( + support_event_subscription_service.CreateSupportEventSubscriptionRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_support_event_subscription.SupportEventSubscription() + post_with_metadata.return_value = ( + gcs_support_event_subscription.SupportEventSubscription(), + metadata, + ) + + client.create_support_event_subscription( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_support_event_subscription_rest_bad_request( + request_type=support_event_subscription_service.GetSupportEventSubscriptionRequest, +): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "sample1/sample2/supportEventSubscriptions/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_support_event_subscription(request) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.GetSupportEventSubscriptionRequest, + dict, + ], +) +def test_get_support_event_subscription_rest_call_success(request_type): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "sample1/sample2/supportEventSubscriptions/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 = support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_support_event_subscription(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_support_event_subscription_rest_interceptors(null_interceptor): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SupportEventSubscriptionServiceRestInterceptor(), + ) + client = SupportEventSubscriptionServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_get_support_event_subscription", + ) as post, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_get_support_event_subscription_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "pre_get_support_event_subscription", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = ( + support_event_subscription_service.GetSupportEventSubscriptionRequest.pb( + support_event_subscription_service.GetSupportEventSubscriptionRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = support_event_subscription.SupportEventSubscription.to_json( + support_event_subscription.SupportEventSubscription() + ) + req.return_value.content = return_value + + request = ( + support_event_subscription_service.GetSupportEventSubscriptionRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = support_event_subscription.SupportEventSubscription() + post_with_metadata.return_value = ( + support_event_subscription.SupportEventSubscription(), + metadata, + ) + + client.get_support_event_subscription( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_support_event_subscriptions_rest_bad_request( + request_type=support_event_subscription_service.ListSupportEventSubscriptionsRequest, +): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "sample1/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_support_event_subscriptions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.ListSupportEventSubscriptionsRequest, + dict, + ], +) +def test_list_support_event_subscriptions_rest_call_success(request_type): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "sample1/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + next_page_token="next_page_token_value", + ) + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_support_event_subscriptions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSupportEventSubscriptionsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_support_event_subscriptions_rest_interceptors(null_interceptor): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SupportEventSubscriptionServiceRestInterceptor(), + ) + client = SupportEventSubscriptionServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_list_support_event_subscriptions", + ) as post, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_list_support_event_subscriptions_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "pre_list_support_event_subscriptions", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = support_event_subscription_service.ListSupportEventSubscriptionsRequest.pb( + support_event_subscription_service.ListSupportEventSubscriptionsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = support_event_subscription_service.ListSupportEventSubscriptionsResponse.to_json( + support_event_subscription_service.ListSupportEventSubscriptionsResponse() + ) + req.return_value.content = return_value + + request = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse() + ) + post_with_metadata.return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse(), + metadata, + ) + + client.list_support_event_subscriptions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_support_event_subscription_rest_bad_request( + request_type=support_event_subscription_service.UpdateSupportEventSubscriptionRequest, +): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "support_event_subscription": { + "name": "sample1/sample2/supportEventSubscriptions/sample3" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_support_event_subscription(request) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.UpdateSupportEventSubscriptionRequest, + dict, + ], +) +def test_update_support_event_subscription_rest_call_success(request_type): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "support_event_subscription": { + "name": "sample1/sample2/supportEventSubscriptions/sample3" + } + } + request_init["support_event_subscription"] = { + "name": "sample1/sample2/supportEventSubscriptions/sample3", + "pub_sub_topic": "pub_sub_topic_value", + "state": 1, + "failure_reason": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "purge_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 = support_event_subscription_service.UpdateSupportEventSubscriptionRequest.meta.fields[ + "support_event_subscription" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "support_event_subscription" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["support_event_subscription"][field]) + ): + del request_init["support_event_subscription"][field][i][subfield] + else: + del request_init["support_event_subscription"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcs_support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=gcs_support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcs_support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_support_event_subscription(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == gcs_support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_support_event_subscription_rest_interceptors(null_interceptor): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SupportEventSubscriptionServiceRestInterceptor(), + ) + client = SupportEventSubscriptionServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_update_support_event_subscription", + ) as post, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_update_support_event_subscription_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "pre_update_support_event_subscription", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = support_event_subscription_service.UpdateSupportEventSubscriptionRequest.pb( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcs_support_event_subscription.SupportEventSubscription.to_json( + gcs_support_event_subscription.SupportEventSubscription() + ) + req.return_value.content = return_value + + request = ( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_support_event_subscription.SupportEventSubscription() + post_with_metadata.return_value = ( + gcs_support_event_subscription.SupportEventSubscription(), + metadata, + ) + + client.update_support_event_subscription( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_support_event_subscription_rest_bad_request( + request_type=support_event_subscription_service.DeleteSupportEventSubscriptionRequest, +): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "sample1/sample2/supportEventSubscriptions/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_support_event_subscription(request) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.DeleteSupportEventSubscriptionRequest, + dict, + ], +) +def test_delete_support_event_subscription_rest_call_success(request_type): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "sample1/sample2/supportEventSubscriptions/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 = support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_support_event_subscription(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_support_event_subscription_rest_interceptors(null_interceptor): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SupportEventSubscriptionServiceRestInterceptor(), + ) + client = SupportEventSubscriptionServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_delete_support_event_subscription", + ) as post, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_delete_support_event_subscription_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "pre_delete_support_event_subscription", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = support_event_subscription_service.DeleteSupportEventSubscriptionRequest.pb( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = support_event_subscription.SupportEventSubscription.to_json( + support_event_subscription.SupportEventSubscription() + ) + req.return_value.content = return_value + + request = ( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = support_event_subscription.SupportEventSubscription() + post_with_metadata.return_value = ( + support_event_subscription.SupportEventSubscription(), + metadata, + ) + + client.delete_support_event_subscription( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_undelete_support_event_subscription_rest_bad_request( + request_type=support_event_subscription_service.UndeleteSupportEventSubscriptionRequest, +): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "sample1/sample2/supportEventSubscriptions/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.undelete_support_event_subscription(request) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest, + dict, + ], +) +def test_undelete_support_event_subscription_rest_call_success(request_type): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "sample1/sample2/supportEventSubscriptions/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 = support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.undelete_support_event_subscription(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_undelete_support_event_subscription_rest_interceptors(null_interceptor): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SupportEventSubscriptionServiceRestInterceptor(), + ) + client = SupportEventSubscriptionServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_undelete_support_event_subscription", + ) as post, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_undelete_support_event_subscription_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "pre_undelete_support_event_subscription", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = support_event_subscription_service.UndeleteSupportEventSubscriptionRequest.pb( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = support_event_subscription.SupportEventSubscription.to_json( + support_event_subscription.SupportEventSubscription() + ) + req.return_value.content = return_value + + request = ( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = support_event_subscription.SupportEventSubscription() + post_with_metadata.return_value = ( + support_event_subscription.SupportEventSubscription(), + metadata, + ) + + client.undelete_support_event_subscription( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_initialize_client_w_rest(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_support_event_subscription_empty_call_rest(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_support_event_subscription), "__call__" + ) as call: + client.create_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.CreateSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_support_event_subscription_empty_call_rest(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_support_event_subscription), "__call__" + ) as call: + client.get_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.GetSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_support_event_subscriptions_empty_call_rest(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + client.list_support_event_subscriptions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_support_event_subscription_empty_call_rest(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_support_event_subscription), "__call__" + ) as call: + client.update_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_support_event_subscription_empty_call_rest(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_support_event_subscription), "__call__" + ) as call: + client.delete_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_undelete_support_event_subscription_empty_call_rest(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.undelete_support_event_subscription), "__call__" + ) as call: + client.undelete_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SupportEventSubscriptionServiceGrpcTransport, + ) + + +def test_support_event_subscription_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SupportEventSubscriptionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_support_event_subscription_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.support_v2.services.support_event_subscription_service.transports.SupportEventSubscriptionServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.SupportEventSubscriptionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_support_event_subscription", + "get_support_event_subscription", + "list_support_event_subscriptions", + "update_support_event_subscription", + "delete_support_event_subscription", + "undelete_support_event_subscription", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_support_event_subscription_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch( + "google.cloud.support_v2.services.support_event_subscription_service.transports.SupportEventSubscriptionServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SupportEventSubscriptionServiceTransport( + 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_support_event_subscription_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch( + "google.cloud.support_v2.services.support_event_subscription_service.transports.SupportEventSubscriptionServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SupportEventSubscriptionServiceTransport() + adc.assert_called_once() + + +def test_support_event_subscription_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SupportEventSubscriptionServiceClient() + 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.SupportEventSubscriptionServiceGrpcTransport, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + ], +) +def test_support_event_subscription_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SupportEventSubscriptionServiceGrpcTransport, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + transports.SupportEventSubscriptionServiceRestTransport, + ], +) +def test_support_event_subscription_service_transport_auth_gdch_credentials( + transport_class, +): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SupportEventSubscriptionServiceGrpcTransport, grpc_helpers), + ( + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + grpc_helpers_async, + ), + ], +) +def test_support_event_subscription_service_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudsupport.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="cloudsupport.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SupportEventSubscriptionServiceGrpcTransport, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + ], +) +def test_support_event_subscription_service_grpc_transport_client_cert_source_for_mtls( + transport_class, +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_support_event_subscription_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.SupportEventSubscriptionServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_support_event_subscription_service_host_no_port(transport_name): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudsupport.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "cloudsupport.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudsupport.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_support_event_subscription_service_host_with_port(transport_name): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudsupport.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "cloudsupport.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudsupport.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_support_event_subscription_service_client_transport_session_collision( + transport_name, +): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SupportEventSubscriptionServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SupportEventSubscriptionServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_support_event_subscription._session + session2 = client2.transport.create_support_event_subscription._session + assert session1 != session2 + session1 = client1.transport.get_support_event_subscription._session + session2 = client2.transport.get_support_event_subscription._session + assert session1 != session2 + session1 = client1.transport.list_support_event_subscriptions._session + session2 = client2.transport.list_support_event_subscriptions._session + assert session1 != session2 + session1 = client1.transport.update_support_event_subscription._session + session2 = client2.transport.update_support_event_subscription._session + assert session1 != session2 + session1 = client1.transport.delete_support_event_subscription._session + session2 = client2.transport.delete_support_event_subscription._session + assert session1 != session2 + session1 = client1.transport.undelete_support_event_subscription._session + session2 = client2.transport.undelete_support_event_subscription._session + assert session1 != session2 + + +def test_support_event_subscription_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SupportEventSubscriptionServiceGrpcTransport( + 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_support_event_subscription_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport( + 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.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [ + transports.SupportEventSubscriptionServiceGrpcTransport, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + ], +) +def test_support_event_subscription_service_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.SupportEventSubscriptionServiceGrpcTransport, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + ], +) +def test_support_event_subscription_service_transport_channel_mtls_with_adc( + transport_class, +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_support_event_subscription_path(): + organization = "squid" + support_event_subscription = "clam" + expected = "organizations/{organization}/supportEventSubscriptions/{support_event_subscription}".format( + organization=organization, + support_event_subscription=support_event_subscription, + ) + actual = SupportEventSubscriptionServiceClient.support_event_subscription_path( + organization, support_event_subscription + ) + assert expected == actual + + +def test_parse_support_event_subscription_path(): + expected = { + "organization": "whelk", + "support_event_subscription": "octopus", + } + path = SupportEventSubscriptionServiceClient.support_event_subscription_path( + **expected + ) + + # Check that the path construction is reversible. + actual = ( + SupportEventSubscriptionServiceClient.parse_support_event_subscription_path( + path + ) + ) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = SupportEventSubscriptionServiceClient.common_billing_account_path( + billing_account + ) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = SupportEventSubscriptionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SupportEventSubscriptionServiceClient.parse_common_billing_account_path( + path + ) + assert expected == actual + + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = SupportEventSubscriptionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = SupportEventSubscriptionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SupportEventSubscriptionServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = SupportEventSubscriptionServiceClient.common_organization_path( + organization + ) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = SupportEventSubscriptionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SupportEventSubscriptionServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format( + project=project, + ) + actual = SupportEventSubscriptionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = SupportEventSubscriptionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SupportEventSubscriptionServiceClient.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 = SupportEventSubscriptionServiceClient.common_location_path( + project, location + ) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = SupportEventSubscriptionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SupportEventSubscriptionServiceClient.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.SupportEventSubscriptionServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.SupportEventSubscriptionServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = SupportEventSubscriptionServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close_grpc(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = SupportEventSubscriptionServiceClient( + 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", + [ + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceGrpcTransport, + ), + ( + SupportEventSubscriptionServiceAsyncClient, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + ), + ], +) +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-support/tests/unit/gapic/support_v2beta/test_support_event_subscription_service.py b/packages/google-cloud-support/tests/unit/gapic/support_v2beta/test_support_event_subscription_service.py new file mode 100644 index 000000000000..9d18b49a94a6 --- /dev/null +++ b/packages/google-cloud-support/tests/unit/gapic/support_v2beta/test_support_event_subscription_service.py @@ -0,0 +1,7498 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.auth +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + +from google.cloud.support_v2beta.services.support_event_subscription_service import ( + SupportEventSubscriptionServiceAsyncClient, + SupportEventSubscriptionServiceClient, + pagers, + transports, +) +from google.cloud.support_v2beta.types import ( + support_event_subscription, + support_event_subscription_service, +) +from google.cloud.support_v2beta.types import ( + support_event_subscription as gcs_support_event_subscription, +) + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +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" + custom_endpoint = ".custom" + + assert ( + SupportEventSubscriptionServiceClient._get_default_mtls_endpoint(None) is None + ) + assert ( + SupportEventSubscriptionServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + SupportEventSubscriptionServiceClient._get_default_mtls_endpoint( + api_mtls_endpoint + ) + == api_mtls_endpoint + ) + assert ( + SupportEventSubscriptionServiceClient._get_default_mtls_endpoint( + sandbox_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + SupportEventSubscriptionServiceClient._get_default_mtls_endpoint( + sandbox_mtls_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + SupportEventSubscriptionServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + assert ( + SupportEventSubscriptionServiceClient._get_default_mtls_endpoint( + custom_endpoint + ) + == custom_endpoint + ) + + +def test__read_environment_variables(): + assert SupportEventSubscriptionServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SupportEventSubscriptionServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert SupportEventSubscriptionServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + SupportEventSubscriptionServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert ( + SupportEventSubscriptionServiceClient._read_environment_variables() + == ( + False, + "auto", + None, + ) + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert SupportEventSubscriptionServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert SupportEventSubscriptionServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert SupportEventSubscriptionServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + SupportEventSubscriptionServiceClient._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 SupportEventSubscriptionServiceClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=True + ): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is True + ) + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=False + ): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is False + ) + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is True + ) + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is False + ) + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is True + ) + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} + ): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is False + ) + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is True + ) + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} + ): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is False + ) + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is False + ) + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + with pytest.raises(ValueError): + SupportEventSubscriptionServiceClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is False + ) + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert ( + SupportEventSubscriptionServiceClient._use_client_cert_effective() + is False + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert ( + SupportEventSubscriptionServiceClient._get_client_cert_source(None, False) + is None + ) + assert ( + SupportEventSubscriptionServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + SupportEventSubscriptionServiceClient._get_client_cert_source( + mock_provided_cert_source, True + ) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + SupportEventSubscriptionServiceClient._get_client_cert_source( + None, True + ) + is mock_default_cert_source + ) + assert ( + SupportEventSubscriptionServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + SupportEventSubscriptionServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SupportEventSubscriptionServiceClient), +) +@mock.patch.object( + SupportEventSubscriptionServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SupportEventSubscriptionServiceAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = SupportEventSubscriptionServiceClient._DEFAULT_UNIVERSE + default_endpoint = ( + SupportEventSubscriptionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) + mock_universe = "bar.com" + mock_endpoint = ( + SupportEventSubscriptionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + ) + + assert ( + SupportEventSubscriptionServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + SupportEventSubscriptionServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == SupportEventSubscriptionServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SupportEventSubscriptionServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + SupportEventSubscriptionServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == SupportEventSubscriptionServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SupportEventSubscriptionServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == SupportEventSubscriptionServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SupportEventSubscriptionServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + SupportEventSubscriptionServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + SupportEventSubscriptionServiceClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + SupportEventSubscriptionServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + SupportEventSubscriptionServiceClient._get_universe_domain( + None, universe_domain_env + ) + == universe_domain_env + ) + assert ( + SupportEventSubscriptionServiceClient._get_universe_domain(None, None) + == SupportEventSubscriptionServiceClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + SupportEventSubscriptionServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = SupportEventSubscriptionServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = SupportEventSubscriptionServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (SupportEventSubscriptionServiceClient, "grpc"), + (SupportEventSubscriptionServiceAsyncClient, "grpc_asyncio"), + (SupportEventSubscriptionServiceClient, "rest"), + ], +) +def test_support_event_subscription_service_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "cloudsupport.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudsupport.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.SupportEventSubscriptionServiceGrpcTransport, "grpc"), + ( + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (transports.SupportEventSubscriptionServiceRestTransport, "rest"), + ], +) +def test_support_event_subscription_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (SupportEventSubscriptionServiceClient, "grpc"), + (SupportEventSubscriptionServiceAsyncClient, "grpc_asyncio"), + (SupportEventSubscriptionServiceClient, "rest"), + ], +) +def test_support_event_subscription_service_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "cloudsupport.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudsupport.googleapis.com" + ) + + +def test_support_event_subscription_service_client_get_transport_class(): + transport = SupportEventSubscriptionServiceClient.get_transport_class() + available_transports = [ + transports.SupportEventSubscriptionServiceGrpcTransport, + transports.SupportEventSubscriptionServiceRestTransport, + ] + assert transport in available_transports + + transport = SupportEventSubscriptionServiceClient.get_transport_class("grpc") + assert transport == transports.SupportEventSubscriptionServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceGrpcTransport, + "grpc", + ), + ( + SupportEventSubscriptionServiceAsyncClient, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + SupportEventSubscriptionServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SupportEventSubscriptionServiceClient), +) +@mock.patch.object( + SupportEventSubscriptionServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SupportEventSubscriptionServiceAsyncClient), +) +def test_support_event_subscription_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object( + SupportEventSubscriptionServiceClient, "get_transport_class" + ) as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object( + SupportEventSubscriptionServiceClient, "get_transport_class" + ) as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check 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 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", + [ + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceGrpcTransport, + "grpc", + "true", + ), + ( + SupportEventSubscriptionServiceAsyncClient, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceGrpcTransport, + "grpc", + "false", + ), + ( + SupportEventSubscriptionServiceAsyncClient, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceRestTransport, + "rest", + "true", + ), + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + SupportEventSubscriptionServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SupportEventSubscriptionServiceClient), +) +@mock.patch.object( + SupportEventSubscriptionServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SupportEventSubscriptionServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_support_event_subscription_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", + [SupportEventSubscriptionServiceClient, SupportEventSubscriptionServiceAsyncClient], +) +@mock.patch.object( + SupportEventSubscriptionServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SupportEventSubscriptionServiceClient), +) +@mock.patch.object( + SupportEventSubscriptionServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SupportEventSubscriptionServiceAsyncClient), +) +def test_support_event_subscription_service_client_get_mtls_endpoint_and_cert_source( + client_class, +): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + 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 cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # 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`" + ) + + +@pytest.mark.parametrize( + "client_class", + [SupportEventSubscriptionServiceClient, SupportEventSubscriptionServiceAsyncClient], +) +@mock.patch.object( + SupportEventSubscriptionServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SupportEventSubscriptionServiceClient), +) +@mock.patch.object( + SupportEventSubscriptionServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SupportEventSubscriptionServiceAsyncClient), +) +def test_support_event_subscription_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = SupportEventSubscriptionServiceClient._DEFAULT_UNIVERSE + default_endpoint = ( + SupportEventSubscriptionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) + mock_universe = "bar.com" + mock_endpoint = ( + SupportEventSubscriptionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + 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", + [ + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceGrpcTransport, + "grpc", + ), + ( + SupportEventSubscriptionServiceAsyncClient, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceRestTransport, + "rest", + ), + ], +) +def test_support_event_subscription_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SupportEventSubscriptionServiceAsyncClient, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceRestTransport, + "rest", + None, + ), + ], +) +def test_support_event_subscription_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_support_event_subscription_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.support_v2beta.services.support_event_subscription_service.transports.SupportEventSubscriptionServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = SupportEventSubscriptionServiceClient( + 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", + [ + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SupportEventSubscriptionServiceAsyncClient, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_support_event_subscription_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudsupport.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="cloudsupport.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.CreateSupportEventSubscriptionRequest(), + {}, + ], +) +def test_create_support_event_subscription(request_type, transport: str = "grpc"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=gcs_support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + response = client.create_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.CreateSupportEventSubscriptionRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == gcs_support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +def test_create_support_event_subscription_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = support_event_subscription_service.CreateSupportEventSubscriptionRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_support_event_subscription), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_support_event_subscription(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.CreateSupportEventSubscriptionRequest( + parent="parent_value", + ) + ) + assert args[0] == request_msg + + +def test_create_support_event_subscription_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_support_event_subscription + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_support_event_subscription + ] = mock_rpc + request = {} + client.create_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_support_event_subscription_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_support_event_subscription + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_support_event_subscription + ] = mock_rpc + + request = {} + await client.create_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.CreateSupportEventSubscriptionRequest(), + {}, + ], +) +async def test_create_support_event_subscription_async( + request_type, transport: str = "grpc_asyncio" +): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=gcs_support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + ) + response = await client.create_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.CreateSupportEventSubscriptionRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == gcs_support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +def test_create_support_event_subscription_field_headers(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = support_event_subscription_service.CreateSupportEventSubscriptionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_support_event_subscription), "__call__" + ) as call: + call.return_value = gcs_support_event_subscription.SupportEventSubscription() + client.create_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_support_event_subscription_field_headers_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = support_event_subscription_service.CreateSupportEventSubscriptionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_support_event_subscription), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_support_event_subscription.SupportEventSubscription() + ) + await client.create_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_support_event_subscription_flattened(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_support_event_subscription.SupportEventSubscription() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_support_event_subscription( + parent="parent_value", + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + ) + + # Establish that the underlying call was made with the expected + # request object 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].support_event_subscription + mock_val = gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ) + assert arg == mock_val + + +def test_create_support_event_subscription_flattened_error(): + client = SupportEventSubscriptionServiceClient( + credentials=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_support_event_subscription( + support_event_subscription_service.CreateSupportEventSubscriptionRequest(), + parent="parent_value", + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + ) + + +@pytest.mark.asyncio +async def test_create_support_event_subscription_flattened_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_support_event_subscription.SupportEventSubscription() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_support_event_subscription.SupportEventSubscription() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_support_event_subscription( + parent="parent_value", + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + ) + + # Establish that the underlying call was made with the expected + # request 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].support_event_subscription + mock_val = gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_support_event_subscription_flattened_error_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_support_event_subscription( + support_event_subscription_service.CreateSupportEventSubscriptionRequest(), + parent="parent_value", + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.GetSupportEventSubscriptionRequest(), + {}, + ], +) +def test_get_support_event_subscription(request_type, transport: str = "grpc"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + response = client.get_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.GetSupportEventSubscriptionRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +def test_get_support_event_subscription_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = support_event_subscription_service.GetSupportEventSubscriptionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_support_event_subscription), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_support_event_subscription(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.GetSupportEventSubscriptionRequest( + name="name_value", + ) + ) + assert args[0] == request_msg + + +def test_get_support_event_subscription_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_support_event_subscription + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_support_event_subscription + ] = mock_rpc + request = {} + client.get_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_support_event_subscription_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_support_event_subscription + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_support_event_subscription + ] = mock_rpc + + request = {} + await client.get_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.GetSupportEventSubscriptionRequest(), + {}, + ], +) +async def test_get_support_event_subscription_async( + request_type, transport: str = "grpc_asyncio" +): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + ) + response = await client.get_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.GetSupportEventSubscriptionRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +def test_get_support_event_subscription_field_headers(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = support_event_subscription_service.GetSupportEventSubscriptionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_support_event_subscription), "__call__" + ) as call: + call.return_value = support_event_subscription.SupportEventSubscription() + client.get_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_support_event_subscription_field_headers_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = support_event_subscription_service.GetSupportEventSubscriptionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_support_event_subscription), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription() + ) + await client.get_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_support_event_subscription_flattened(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = support_event_subscription.SupportEventSubscription() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_support_event_subscription( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_support_event_subscription_flattened_error(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_support_event_subscription( + support_event_subscription_service.GetSupportEventSubscriptionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_support_event_subscription_flattened_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = support_event_subscription.SupportEventSubscription() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_support_event_subscription( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_support_event_subscription_flattened_error_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_support_event_subscription( + support_event_subscription_service.GetSupportEventSubscriptionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.ListSupportEventSubscriptionsRequest(), + {}, + ], +) +def test_list_support_event_subscriptions(request_type, transport: str = "grpc"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + next_page_token="next_page_token_value", + ) + ) + response = client.list_support_event_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSupportEventSubscriptionsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_support_event_subscriptions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = support_event_subscription_service.ListSupportEventSubscriptionsRequest( + 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_support_event_subscriptions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_support_event_subscriptions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest( + parent="parent_value", + filter="filter_value", + page_token="page_token_value", + ) + ) + assert args[0] == request_msg + + +def test_list_support_event_subscriptions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_support_event_subscriptions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_support_event_subscriptions + ] = mock_rpc + request = {} + client.list_support_event_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_support_event_subscriptions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_support_event_subscriptions_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_support_event_subscriptions + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_support_event_subscriptions + ] = mock_rpc + + request = {} + await client.list_support_event_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_support_event_subscriptions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.ListSupportEventSubscriptionsRequest(), + {}, + ], +) +async def test_list_support_event_subscriptions_async( + request_type, transport: str = "grpc_asyncio" +): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_support_event_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSupportEventSubscriptionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_support_event_subscriptions_field_headers(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = support_event_subscription_service.ListSupportEventSubscriptionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + call.return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse() + ) + client.list_support_event_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_support_event_subscriptions_field_headers_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = support_event_subscription_service.ListSupportEventSubscriptionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription_service.ListSupportEventSubscriptionsResponse() + ) + await client.list_support_event_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_support_event_subscriptions_flattened(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_support_event_subscriptions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_support_event_subscriptions_flattened_error(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_support_event_subscriptions( + support_event_subscription_service.ListSupportEventSubscriptionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_support_event_subscriptions_flattened_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription_service.ListSupportEventSubscriptionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_support_event_subscriptions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_support_event_subscriptions_flattened_error_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_support_event_subscriptions( + support_event_subscription_service.ListSupportEventSubscriptionsRequest(), + parent="parent_value", + ) + + +def test_list_support_event_subscriptions_pager(transport_name: str = "grpc"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + ], + next_page_token="abc", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[], + next_page_token="def", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + ], + next_page_token="ghi", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_support_event_subscriptions( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, support_event_subscription.SupportEventSubscription) + for i in results + ) + + +def test_list_support_event_subscriptions_pages(transport_name: str = "grpc"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + ], + next_page_token="abc", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[], + next_page_token="def", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + ], + next_page_token="ghi", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + ], + ), + RuntimeError, + ) + pages = list(client.list_support_event_subscriptions(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_support_event_subscriptions_async_pager(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + ], + next_page_token="abc", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[], + next_page_token="def", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + ], + next_page_token="ghi", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_support_event_subscriptions( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, support_event_subscription.SupportEventSubscription) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_support_event_subscriptions_async_pages(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + ], + next_page_token="abc", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[], + next_page_token="def", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + ], + next_page_token="ghi", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_support_event_subscriptions(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.UpdateSupportEventSubscriptionRequest(), + {}, + ], +) +def test_update_support_event_subscription(request_type, transport: str = "grpc"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=gcs_support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + response = client.update_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == gcs_support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +def test_update_support_event_subscription_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_support_event_subscription), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_support_event_subscription(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +def test_update_support_event_subscription_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_support_event_subscription + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_support_event_subscription + ] = mock_rpc + request = {} + client.update_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_support_event_subscription_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_support_event_subscription + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_support_event_subscription + ] = mock_rpc + + request = {} + await client.update_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.UpdateSupportEventSubscriptionRequest(), + {}, + ], +) +async def test_update_support_event_subscription_async( + request_type, transport: str = "grpc_asyncio" +): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=gcs_support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + ) + response = await client.update_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == gcs_support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +def test_update_support_event_subscription_field_headers(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + + request.support_event_subscription.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_support_event_subscription), "__call__" + ) as call: + call.return_value = gcs_support_event_subscription.SupportEventSubscription() + client.update_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "support_event_subscription.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_support_event_subscription_field_headers_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + + request.support_event_subscription.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_support_event_subscription), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_support_event_subscription.SupportEventSubscription() + ) + await client.update_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "support_event_subscription.name=name_value", + ) in kw["metadata"] + + +def test_update_support_event_subscription_flattened(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_support_event_subscription.SupportEventSubscription() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_support_event_subscription( + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + update_mask=field_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].support_event_subscription + mock_val = gcs_support_event_subscription.SupportEventSubscription( + name="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_support_event_subscription_flattened_error(): + client = SupportEventSubscriptionServiceClient( + credentials=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_support_event_subscription( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest(), + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_support_event_subscription_flattened_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_support_event_subscription.SupportEventSubscription() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_support_event_subscription.SupportEventSubscription() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_support_event_subscription( + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + update_mask=field_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].support_event_subscription + mock_val = gcs_support_event_subscription.SupportEventSubscription( + name="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_support_event_subscription_flattened_error_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_support_event_subscription( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest(), + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.DeleteSupportEventSubscriptionRequest(), + {}, + ], +) +def test_delete_support_event_subscription(request_type, transport: str = "grpc"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + response = client.delete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +def test_delete_support_event_subscription_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = support_event_subscription_service.DeleteSupportEventSubscriptionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_support_event_subscription), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_support_event_subscription(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest( + name="name_value", + ) + ) + assert args[0] == request_msg + + +def test_delete_support_event_subscription_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_support_event_subscription + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_support_event_subscription + ] = mock_rpc + request = {} + client.delete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_support_event_subscription_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap 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_support_event_subscription + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_support_event_subscription + ] = mock_rpc + + request = {} + await client.delete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.DeleteSupportEventSubscriptionRequest(), + {}, + ], +) +async def test_delete_support_event_subscription_async( + request_type, transport: str = "grpc_asyncio" +): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + ) + response = await client.delete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +def test_delete_support_event_subscription_field_headers(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = support_event_subscription_service.DeleteSupportEventSubscriptionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_support_event_subscription), "__call__" + ) as call: + call.return_value = support_event_subscription.SupportEventSubscription() + client.delete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_support_event_subscription_field_headers_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = support_event_subscription_service.DeleteSupportEventSubscriptionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_support_event_subscription), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription() + ) + await client.delete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_support_event_subscription_flattened(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = support_event_subscription.SupportEventSubscription() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_support_event_subscription( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_support_event_subscription_flattened_error(): + client = SupportEventSubscriptionServiceClient( + credentials=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_support_event_subscription( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_support_event_subscription_flattened_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = support_event_subscription.SupportEventSubscription() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_support_event_subscription( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_support_event_subscription_flattened_error_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_support_event_subscription( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest(), + {}, + ], +) +def test_undelete_support_event_subscription(request_type, transport: str = "grpc"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + response = client.undelete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +def test_undelete_support_event_subscription_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = ( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest( + name="name_value", + ) + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_support_event_subscription), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.undelete_support_event_subscription(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest( + name="name_value", + ) + ) + assert args[0] == request_msg + + +def test_undelete_support_event_subscription_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.undelete_support_event_subscription + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.undelete_support_event_subscription + ] = mock_rpc + request = {} + client.undelete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.undelete_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_undelete_support_event_subscription_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.undelete_support_event_subscription + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.undelete_support_event_subscription + ] = mock_rpc + + request = {} + await client.undelete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.undelete_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest(), + {}, + ], +) +async def test_undelete_support_event_subscription_async( + request_type, transport: str = "grpc_asyncio" +): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + ) + response = await client.undelete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = ( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest() + ) + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +def test_undelete_support_event_subscription_field_headers(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest() + ) + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_support_event_subscription), "__call__" + ) as call: + call.return_value = support_event_subscription.SupportEventSubscription() + client.undelete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_undelete_support_event_subscription_field_headers_async(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest() + ) + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_support_event_subscription), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription() + ) + await client.undelete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_create_support_event_subscription_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_support_event_subscription + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_support_event_subscription + ] = mock_rpc + + request = {} + client.create_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_support_event_subscription_rest_required_fields( + request_type=support_event_subscription_service.CreateSupportEventSubscriptionRequest, +): + transport_class = transports.SupportEventSubscriptionServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_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_support_event_subscription._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_support_event_subscription._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_support_event_subscription.SupportEventSubscription() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["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_support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_support_event_subscription(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_support_event_subscription_rest_unset_required_fields(): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.create_support_event_subscription._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "supportEventSubscription", + ) + ) + ) + + +def test_create_support_event_subscription_rest_flattened(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcs_support_event_subscription.SupportEventSubscription() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "sample1/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcs_support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_support_event_subscription(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2beta/{parent=*/*}/supportEventSubscriptions" % client.transport._host, + args[1], + ) + + +def test_create_support_event_subscription_rest_flattened_error( + transport: str = "rest", +): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.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_support_event_subscription( + support_event_subscription_service.CreateSupportEventSubscriptionRequest(), + parent="parent_value", + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + ) + + +def test_get_support_event_subscription_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_support_event_subscription + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_support_event_subscription + ] = mock_rpc + + request = {} + client.get_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_support_event_subscription_rest_required_fields( + request_type=support_event_subscription_service.GetSupportEventSubscriptionRequest, +): + transport_class = transports.SupportEventSubscriptionServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_support_event_subscription._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_support_event_subscription._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = support_event_subscription.SupportEventSubscription() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_support_event_subscription(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_support_event_subscription_rest_unset_required_fields(): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_support_event_subscription._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_support_event_subscription_rest_flattened(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = support_event_subscription.SupportEventSubscription() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "sample1/sample2/supportEventSubscriptions/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 = support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_support_event_subscription(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2beta/{name=*/*/supportEventSubscriptions/*}" % client.transport._host, + args[1], + ) + + +def test_get_support_event_subscription_rest_flattened_error(transport: str = "rest"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_support_event_subscription( + support_event_subscription_service.GetSupportEventSubscriptionRequest(), + name="name_value", + ) + + +def test_list_support_event_subscriptions_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_support_event_subscriptions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_support_event_subscriptions + ] = mock_rpc + + request = {} + client.list_support_event_subscriptions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_support_event_subscriptions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_support_event_subscriptions_rest_required_fields( + request_type=support_event_subscription_service.ListSupportEventSubscriptionsRequest, +): + transport_class = transports.SupportEventSubscriptionServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_support_event_subscriptions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_support_event_subscriptions._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", + "show_deleted", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse() + ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = support_event_subscription_service.ListSupportEventSubscriptionsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_support_event_subscriptions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_support_event_subscriptions_rest_unset_required_fields(): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.list_support_event_subscriptions._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + "showDeleted", + ) + ) + & set(("parent",)) + ) + + +def test_list_support_event_subscriptions_rest_flattened(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse() + ) + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "sample1/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 = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_support_event_subscriptions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2beta/{parent=*/*}/supportEventSubscriptions" % client.transport._host, + args[1], + ) + + +def test_list_support_event_subscriptions_rest_flattened_error(transport: str = "rest"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.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_support_event_subscriptions( + support_event_subscription_service.ListSupportEventSubscriptionsRequest(), + parent="parent_value", + ) + + +def test_list_support_event_subscriptions_rest_pager(transport: str = "rest"): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + ], + next_page_token="abc", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[], + next_page_token="def", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + ], + next_page_token="ghi", + ), + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + support_event_subscriptions=[ + support_event_subscription.SupportEventSubscription(), + support_event_subscription.SupportEventSubscription(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + support_event_subscription_service.ListSupportEventSubscriptionsResponse.to_json( + x + ) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "sample1/sample2"} + + pager = client.list_support_event_subscriptions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, support_event_subscription.SupportEventSubscription) + for i in results + ) + + pages = list( + client.list_support_event_subscriptions(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_update_support_event_subscription_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_support_event_subscription + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_support_event_subscription + ] = mock_rpc + + request = {} + client.update_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_support_event_subscription_rest_required_fields( + request_type=support_event_subscription_service.UpdateSupportEventSubscriptionRequest, +): + transport_class = transports.SupportEventSubscriptionServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_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_support_event_subscription._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_support_event_subscription._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcs_support_event_subscription.SupportEventSubscription() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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_support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_support_event_subscription(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_support_event_subscription_rest_unset_required_fields(): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.update_support_event_subscription._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set(("updateMask",)) & set(("supportEventSubscription",)) + ) + + +def test_update_support_event_subscription_rest_flattened(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcs_support_event_subscription.SupportEventSubscription() + + # get arguments that satisfy an http rule for this method + sample_request = { + "support_event_subscription": { + "name": "sample1/sample2/supportEventSubscriptions/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + 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_support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_support_event_subscription(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2beta/{support_event_subscription.name=*/*/supportEventSubscriptions/*}" + % client.transport._host, + args[1], + ) + + +def test_update_support_event_subscription_rest_flattened_error( + transport: str = "rest", +): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.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_support_event_subscription( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest(), + support_event_subscription=gcs_support_event_subscription.SupportEventSubscription( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_support_event_subscription_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_support_event_subscription + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_support_event_subscription + ] = mock_rpc + + request = {} + client.delete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_support_event_subscription_rest_required_fields( + request_type=support_event_subscription_service.DeleteSupportEventSubscriptionRequest, +): + transport_class = transports.SupportEventSubscriptionServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_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_support_event_subscription._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_support_event_subscription._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = support_event_subscription.SupportEventSubscription() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force 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 + + # Convert return value to protobuf type + return_value = support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_support_event_subscription(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_support_event_subscription_rest_unset_required_fields(): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.delete_support_event_subscription._get_unset_required_fields({}) + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_support_event_subscription_rest_flattened(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = support_event_subscription.SupportEventSubscription() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "sample1/sample2/supportEventSubscriptions/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 = support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_support_event_subscription(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2beta/{name=*/*/supportEventSubscriptions/*}" % client.transport._host, + args[1], + ) + + +def test_delete_support_event_subscription_rest_flattened_error( + transport: str = "rest", +): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.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_support_event_subscription( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest(), + name="name_value", + ) + + +def test_undelete_support_event_subscription_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.undelete_support_event_subscription + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.undelete_support_event_subscription + ] = mock_rpc + + request = {} + client.undelete_support_event_subscription(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.undelete_support_event_subscription(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_undelete_support_event_subscription_rest_required_fields( + request_type=support_event_subscription_service.UndeleteSupportEventSubscriptionRequest, +): + transport_class = transports.SupportEventSubscriptionServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).undelete_support_event_subscription._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).undelete_support_event_subscription._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = support_event_subscription.SupportEventSubscription() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.undelete_support_event_subscription(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_undelete_support_event_subscription_rest_unset_required_fields(): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.undelete_support_event_subscription._get_unset_required_fields({}) + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SupportEventSubscriptionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SupportEventSubscriptionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SupportEventSubscriptionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SupportEventSubscriptionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SupportEventSubscriptionServiceClient( + 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 = SupportEventSubscriptionServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SupportEventSubscriptionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SupportEventSubscriptionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SupportEventSubscriptionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SupportEventSubscriptionServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SupportEventSubscriptionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SupportEventSubscriptionServiceGrpcTransport, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + transports.SupportEventSubscriptionServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = SupportEventSubscriptionServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_support_event_subscription_empty_call_grpc(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_support_event_subscription), "__call__" + ) as call: + call.return_value = gcs_support_event_subscription.SupportEventSubscription() + client.create_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.CreateSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_support_event_subscription_empty_call_grpc(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_support_event_subscription), "__call__" + ) as call: + call.return_value = support_event_subscription.SupportEventSubscription() + client.get_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.GetSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_support_event_subscriptions_empty_call_grpc(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + call.return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse() + ) + client.list_support_event_subscriptions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_support_event_subscription_empty_call_grpc(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_support_event_subscription), "__call__" + ) as call: + call.return_value = gcs_support_event_subscription.SupportEventSubscription() + client.update_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_support_event_subscription_empty_call_grpc(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_support_event_subscription), "__call__" + ) as call: + call.return_value = support_event_subscription.SupportEventSubscription() + client.delete_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_undelete_support_event_subscription_empty_call_grpc(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.undelete_support_event_subscription), "__call__" + ) as call: + call.return_value = support_event_subscription.SupportEventSubscription() + client.undelete_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = SupportEventSubscriptionServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_support_event_subscription_empty_call_grpc_asyncio(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=gcs_support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + ) + await client.create_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.CreateSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_support_event_subscription_empty_call_grpc_asyncio(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + ) + await client.get_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.GetSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_support_event_subscriptions_empty_call_grpc_asyncio(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_support_event_subscriptions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_support_event_subscription_empty_call_grpc_asyncio(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=gcs_support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + ) + await client.update_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_support_event_subscription_empty_call_grpc_asyncio(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + ) + await client.delete_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_undelete_support_event_subscription_empty_call_grpc_asyncio(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.undelete_support_event_subscription), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + ) + await client.undelete_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = SupportEventSubscriptionServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_support_event_subscription_rest_bad_request( + request_type=support_event_subscription_service.CreateSupportEventSubscriptionRequest, +): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "sample1/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_support_event_subscription(request) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.CreateSupportEventSubscriptionRequest, + dict, + ], +) +def test_create_support_event_subscription_rest_call_success(request_type): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "sample1/sample2"} + request_init["support_event_subscription"] = { + "name": "name_value", + "pub_sub_topic": "pub_sub_topic_value", + "state": 1, + "failure_reason": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "purge_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 = support_event_subscription_service.CreateSupportEventSubscriptionRequest.meta.fields[ + "support_event_subscription" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "support_event_subscription" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["support_event_subscription"][field]) + ): + del request_init["support_event_subscription"][field][i][subfield] + else: + del request_init["support_event_subscription"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcs_support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=gcs_support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcs_support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_support_event_subscription(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == gcs_support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_support_event_subscription_rest_interceptors(null_interceptor): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SupportEventSubscriptionServiceRestInterceptor(), + ) + client = SupportEventSubscriptionServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_create_support_event_subscription", + ) as post, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_create_support_event_subscription_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "pre_create_support_event_subscription", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = support_event_subscription_service.CreateSupportEventSubscriptionRequest.pb( + support_event_subscription_service.CreateSupportEventSubscriptionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcs_support_event_subscription.SupportEventSubscription.to_json( + gcs_support_event_subscription.SupportEventSubscription() + ) + req.return_value.content = return_value + + request = ( + support_event_subscription_service.CreateSupportEventSubscriptionRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_support_event_subscription.SupportEventSubscription() + post_with_metadata.return_value = ( + gcs_support_event_subscription.SupportEventSubscription(), + metadata, + ) + + client.create_support_event_subscription( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_support_event_subscription_rest_bad_request( + request_type=support_event_subscription_service.GetSupportEventSubscriptionRequest, +): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "sample1/sample2/supportEventSubscriptions/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_support_event_subscription(request) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.GetSupportEventSubscriptionRequest, + dict, + ], +) +def test_get_support_event_subscription_rest_call_success(request_type): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "sample1/sample2/supportEventSubscriptions/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 = support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_support_event_subscription(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_support_event_subscription_rest_interceptors(null_interceptor): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SupportEventSubscriptionServiceRestInterceptor(), + ) + client = SupportEventSubscriptionServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_get_support_event_subscription", + ) as post, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_get_support_event_subscription_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "pre_get_support_event_subscription", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = ( + support_event_subscription_service.GetSupportEventSubscriptionRequest.pb( + support_event_subscription_service.GetSupportEventSubscriptionRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = support_event_subscription.SupportEventSubscription.to_json( + support_event_subscription.SupportEventSubscription() + ) + req.return_value.content = return_value + + request = ( + support_event_subscription_service.GetSupportEventSubscriptionRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = support_event_subscription.SupportEventSubscription() + post_with_metadata.return_value = ( + support_event_subscription.SupportEventSubscription(), + metadata, + ) + + client.get_support_event_subscription( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_support_event_subscriptions_rest_bad_request( + request_type=support_event_subscription_service.ListSupportEventSubscriptionsRequest, +): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "sample1/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_support_event_subscriptions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.ListSupportEventSubscriptionsRequest, + dict, + ], +) +def test_list_support_event_subscriptions_rest_call_success(request_type): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "sample1/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse( + next_page_token="next_page_token_value", + ) + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_support_event_subscriptions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSupportEventSubscriptionsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_support_event_subscriptions_rest_interceptors(null_interceptor): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SupportEventSubscriptionServiceRestInterceptor(), + ) + client = SupportEventSubscriptionServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_list_support_event_subscriptions", + ) as post, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_list_support_event_subscriptions_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "pre_list_support_event_subscriptions", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = support_event_subscription_service.ListSupportEventSubscriptionsRequest.pb( + support_event_subscription_service.ListSupportEventSubscriptionsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = support_event_subscription_service.ListSupportEventSubscriptionsResponse.to_json( + support_event_subscription_service.ListSupportEventSubscriptionsResponse() + ) + req.return_value.content = return_value + + request = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse() + ) + post_with_metadata.return_value = ( + support_event_subscription_service.ListSupportEventSubscriptionsResponse(), + metadata, + ) + + client.list_support_event_subscriptions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_support_event_subscription_rest_bad_request( + request_type=support_event_subscription_service.UpdateSupportEventSubscriptionRequest, +): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "support_event_subscription": { + "name": "sample1/sample2/supportEventSubscriptions/sample3" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_support_event_subscription(request) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.UpdateSupportEventSubscriptionRequest, + dict, + ], +) +def test_update_support_event_subscription_rest_call_success(request_type): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "support_event_subscription": { + "name": "sample1/sample2/supportEventSubscriptions/sample3" + } + } + request_init["support_event_subscription"] = { + "name": "sample1/sample2/supportEventSubscriptions/sample3", + "pub_sub_topic": "pub_sub_topic_value", + "state": 1, + "failure_reason": 1, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "purge_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 = support_event_subscription_service.UpdateSupportEventSubscriptionRequest.meta.fields[ + "support_event_subscription" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "support_event_subscription" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["support_event_subscription"][field]) + ): + del request_init["support_event_subscription"][field][i][subfield] + else: + del request_init["support_event_subscription"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcs_support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=gcs_support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcs_support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_support_event_subscription(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == gcs_support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == gcs_support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_support_event_subscription_rest_interceptors(null_interceptor): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SupportEventSubscriptionServiceRestInterceptor(), + ) + client = SupportEventSubscriptionServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_update_support_event_subscription", + ) as post, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_update_support_event_subscription_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "pre_update_support_event_subscription", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = support_event_subscription_service.UpdateSupportEventSubscriptionRequest.pb( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcs_support_event_subscription.SupportEventSubscription.to_json( + gcs_support_event_subscription.SupportEventSubscription() + ) + req.return_value.content = return_value + + request = ( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcs_support_event_subscription.SupportEventSubscription() + post_with_metadata.return_value = ( + gcs_support_event_subscription.SupportEventSubscription(), + metadata, + ) + + client.update_support_event_subscription( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_support_event_subscription_rest_bad_request( + request_type=support_event_subscription_service.DeleteSupportEventSubscriptionRequest, +): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "sample1/sample2/supportEventSubscriptions/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_support_event_subscription(request) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.DeleteSupportEventSubscriptionRequest, + dict, + ], +) +def test_delete_support_event_subscription_rest_call_success(request_type): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "sample1/sample2/supportEventSubscriptions/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 = support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_support_event_subscription(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_support_event_subscription_rest_interceptors(null_interceptor): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SupportEventSubscriptionServiceRestInterceptor(), + ) + client = SupportEventSubscriptionServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_delete_support_event_subscription", + ) as post, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_delete_support_event_subscription_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "pre_delete_support_event_subscription", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = support_event_subscription_service.DeleteSupportEventSubscriptionRequest.pb( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = support_event_subscription.SupportEventSubscription.to_json( + support_event_subscription.SupportEventSubscription() + ) + req.return_value.content = return_value + + request = ( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = support_event_subscription.SupportEventSubscription() + post_with_metadata.return_value = ( + support_event_subscription.SupportEventSubscription(), + metadata, + ) + + client.delete_support_event_subscription( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_undelete_support_event_subscription_rest_bad_request( + request_type=support_event_subscription_service.UndeleteSupportEventSubscriptionRequest, +): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "sample1/sample2/supportEventSubscriptions/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.undelete_support_event_subscription(request) + + +@pytest.mark.parametrize( + "request_type", + [ + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest, + dict, + ], +) +def test_undelete_support_event_subscription_rest_call_success(request_type): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "sample1/sample2/supportEventSubscriptions/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 = support_event_subscription.SupportEventSubscription( + name="name_value", + pub_sub_topic="pub_sub_topic_value", + state=support_event_subscription.SupportEventSubscription.State.WORKING, + failure_reason=support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = support_event_subscription.SupportEventSubscription.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.undelete_support_event_subscription(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, support_event_subscription.SupportEventSubscription) + assert response.name == "name_value" + assert response.pub_sub_topic == "pub_sub_topic_value" + assert ( + response.state + == support_event_subscription.SupportEventSubscription.State.WORKING + ) + assert ( + response.failure_reason + == support_event_subscription.SupportEventSubscription.FailureReason.PERMISSION_DENIED + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_undelete_support_event_subscription_rest_interceptors(null_interceptor): + transport = transports.SupportEventSubscriptionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SupportEventSubscriptionServiceRestInterceptor(), + ) + client = SupportEventSubscriptionServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_undelete_support_event_subscription", + ) as post, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "post_undelete_support_event_subscription_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SupportEventSubscriptionServiceRestInterceptor, + "pre_undelete_support_event_subscription", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = support_event_subscription_service.UndeleteSupportEventSubscriptionRequest.pb( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = support_event_subscription.SupportEventSubscription.to_json( + support_event_subscription.SupportEventSubscription() + ) + req.return_value.content = return_value + + request = ( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest() + ) + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = support_event_subscription.SupportEventSubscription() + post_with_metadata.return_value = ( + support_event_subscription.SupportEventSubscription(), + metadata, + ) + + client.undelete_support_event_subscription( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_initialize_client_w_rest(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_support_event_subscription_empty_call_rest(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_support_event_subscription), "__call__" + ) as call: + client.create_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.CreateSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_support_event_subscription_empty_call_rest(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_support_event_subscription), "__call__" + ) as call: + client.get_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.GetSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_support_event_subscriptions_empty_call_rest(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_support_event_subscriptions), "__call__" + ) as call: + client.list_support_event_subscriptions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.ListSupportEventSubscriptionsRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_support_event_subscription_empty_call_rest(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_support_event_subscription), "__call__" + ) as call: + client.update_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.UpdateSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_support_event_subscription_empty_call_rest(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_support_event_subscription), "__call__" + ) as call: + client.delete_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.DeleteSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_undelete_support_event_subscription_empty_call_rest(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.undelete_support_event_subscription), "__call__" + ) as call: + client.undelete_support_event_subscription(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + support_event_subscription_service.UndeleteSupportEventSubscriptionRequest() + ) + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SupportEventSubscriptionServiceGrpcTransport, + ) + + +def test_support_event_subscription_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SupportEventSubscriptionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_support_event_subscription_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.support_v2beta.services.support_event_subscription_service.transports.SupportEventSubscriptionServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.SupportEventSubscriptionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_support_event_subscription", + "get_support_event_subscription", + "list_support_event_subscriptions", + "update_support_event_subscription", + "delete_support_event_subscription", + "undelete_support_event_subscription", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_support_event_subscription_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch( + "google.cloud.support_v2beta.services.support_event_subscription_service.transports.SupportEventSubscriptionServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SupportEventSubscriptionServiceTransport( + 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_support_event_subscription_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch( + "google.cloud.support_v2beta.services.support_event_subscription_service.transports.SupportEventSubscriptionServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SupportEventSubscriptionServiceTransport() + adc.assert_called_once() + + +def test_support_event_subscription_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SupportEventSubscriptionServiceClient() + 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.SupportEventSubscriptionServiceGrpcTransport, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + ], +) +def test_support_event_subscription_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SupportEventSubscriptionServiceGrpcTransport, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + transports.SupportEventSubscriptionServiceRestTransport, + ], +) +def test_support_event_subscription_service_transport_auth_gdch_credentials( + transport_class, +): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SupportEventSubscriptionServiceGrpcTransport, grpc_helpers), + ( + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + grpc_helpers_async, + ), + ], +) +def test_support_event_subscription_service_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudsupport.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="cloudsupport.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SupportEventSubscriptionServiceGrpcTransport, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + ], +) +def test_support_event_subscription_service_grpc_transport_client_cert_source_for_mtls( + transport_class, +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_support_event_subscription_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.SupportEventSubscriptionServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_support_event_subscription_service_host_no_port(transport_name): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudsupport.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "cloudsupport.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudsupport.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_support_event_subscription_service_host_with_port(transport_name): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudsupport.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "cloudsupport.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudsupport.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_support_event_subscription_service_client_transport_session_collision( + transport_name, +): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SupportEventSubscriptionServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SupportEventSubscriptionServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_support_event_subscription._session + session2 = client2.transport.create_support_event_subscription._session + assert session1 != session2 + session1 = client1.transport.get_support_event_subscription._session + session2 = client2.transport.get_support_event_subscription._session + assert session1 != session2 + session1 = client1.transport.list_support_event_subscriptions._session + session2 = client2.transport.list_support_event_subscriptions._session + assert session1 != session2 + session1 = client1.transport.update_support_event_subscription._session + session2 = client2.transport.update_support_event_subscription._session + assert session1 != session2 + session1 = client1.transport.delete_support_event_subscription._session + session2 = client2.transport.delete_support_event_subscription._session + assert session1 != session2 + session1 = client1.transport.undelete_support_event_subscription._session + session2 = client2.transport.undelete_support_event_subscription._session + assert session1 != session2 + + +def test_support_event_subscription_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SupportEventSubscriptionServiceGrpcTransport( + 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_support_event_subscription_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport( + 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.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [ + transports.SupportEventSubscriptionServiceGrpcTransport, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + ], +) +def test_support_event_subscription_service_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.SupportEventSubscriptionServiceGrpcTransport, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + ], +) +def test_support_event_subscription_service_transport_channel_mtls_with_adc( + transport_class, +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_support_event_subscription_path(): + organization = "squid" + support_event_subscription = "clam" + expected = "organizations/{organization}/supportEventSubscriptions/{support_event_subscription}".format( + organization=organization, + support_event_subscription=support_event_subscription, + ) + actual = SupportEventSubscriptionServiceClient.support_event_subscription_path( + organization, support_event_subscription + ) + assert expected == actual + + +def test_parse_support_event_subscription_path(): + expected = { + "organization": "whelk", + "support_event_subscription": "octopus", + } + path = SupportEventSubscriptionServiceClient.support_event_subscription_path( + **expected + ) + + # Check that the path construction is reversible. + actual = ( + SupportEventSubscriptionServiceClient.parse_support_event_subscription_path( + path + ) + ) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = SupportEventSubscriptionServiceClient.common_billing_account_path( + billing_account + ) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = SupportEventSubscriptionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SupportEventSubscriptionServiceClient.parse_common_billing_account_path( + path + ) + assert expected == actual + + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = SupportEventSubscriptionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = SupportEventSubscriptionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SupportEventSubscriptionServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = SupportEventSubscriptionServiceClient.common_organization_path( + organization + ) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = SupportEventSubscriptionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SupportEventSubscriptionServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format( + project=project, + ) + actual = SupportEventSubscriptionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = SupportEventSubscriptionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SupportEventSubscriptionServiceClient.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 = SupportEventSubscriptionServiceClient.common_location_path( + project, location + ) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = SupportEventSubscriptionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SupportEventSubscriptionServiceClient.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.SupportEventSubscriptionServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.SupportEventSubscriptionServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = SupportEventSubscriptionServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close_grpc(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = SupportEventSubscriptionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = SupportEventSubscriptionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = SupportEventSubscriptionServiceClient( + 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", + [ + ( + SupportEventSubscriptionServiceClient, + transports.SupportEventSubscriptionServiceGrpcTransport, + ), + ( + SupportEventSubscriptionServiceAsyncClient, + transports.SupportEventSubscriptionServiceGrpcAsyncIOTransport, + ), + ], +) +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, + )