diff --git a/packages/google-cloud-iam/.OwlBot.yaml b/packages/google-cloud-iam/.OwlBot.yaml index 6a9402d07efb..fb786396bf00 100644 --- a/packages/google-cloud-iam/.OwlBot.yaml +++ b/packages/google-cloud-iam/.OwlBot.yaml @@ -17,6 +17,8 @@ deep-remove-regex: - /owl-bot-staging deep-copy-regex: + - source: /google/iam/admin/(v.*)/.*-py + dest: /owl-bot-staging/google-cloud-iam/$1 - source: /google/iam/credentials/(v.*)/.*-py dest: /owl-bot-staging/google-cloud-iam/$1 - source: /google/iam/v2beta/.*-py diff --git a/packages/google-cloud-iam/docs/iam_admin_v1/iam.rst b/packages/google-cloud-iam/docs/iam_admin_v1/iam.rst new file mode 100644 index 000000000000..8f7968c99156 --- /dev/null +++ b/packages/google-cloud-iam/docs/iam_admin_v1/iam.rst @@ -0,0 +1,10 @@ +IAM +--------------------- + +.. automodule:: google.cloud.iam_admin_v1.services.iam + :members: + :inherited-members: + +.. automodule:: google.cloud.iam_admin_v1.services.iam.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-iam/docs/iam_admin_v1/services_.rst b/packages/google-cloud-iam/docs/iam_admin_v1/services_.rst new file mode 100644 index 000000000000..b4aae19fc70f --- /dev/null +++ b/packages/google-cloud-iam/docs/iam_admin_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Iam Admin v1 API +========================================== +.. toctree:: + :maxdepth: 2 + + iam diff --git a/packages/google-cloud-iam/docs/iam_admin_v1/types_.rst b/packages/google-cloud-iam/docs/iam_admin_v1/types_.rst new file mode 100644 index 000000000000..5d97e75cf7ce --- /dev/null +++ b/packages/google-cloud-iam/docs/iam_admin_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Iam Admin v1 API +======================================= + +.. automodule:: google.cloud.iam_admin_v1.types + :members: + :show-inheritance: diff --git a/packages/google-cloud-iam/docs/index.rst b/packages/google-cloud-iam/docs/index.rst index 103ba1ff2cd4..79cab44791e1 100644 --- a/packages/google-cloud-iam/docs/index.rst +++ b/packages/google-cloud-iam/docs/index.rst @@ -14,6 +14,14 @@ API Reference iam_v2/services_ iam_v2/types_ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + iam_admin_v1/services_ + iam_admin_v1/types_ + API Reference ------------- .. toctree:: diff --git a/packages/google-cloud-iam/google/cloud/iam_admin/__init__.py b/packages/google-cloud-iam/google/cloud/iam_admin/__init__.py new file mode 100644 index 000000000000..ceb674ceb342 --- /dev/null +++ b/packages/google-cloud-iam/google/cloud/iam_admin/__init__.py @@ -0,0 +1,125 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.iam_admin import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.iam_admin_v1.services.iam.async_client import IAMAsyncClient +from google.cloud.iam_admin_v1.services.iam.client import IAMClient +from google.cloud.iam_admin_v1.types.audit_data import AuditData +from google.cloud.iam_admin_v1.types.iam import ( + CreateRoleRequest, + CreateServiceAccountKeyRequest, + CreateServiceAccountRequest, + DeleteRoleRequest, + DeleteServiceAccountKeyRequest, + DeleteServiceAccountRequest, + DisableServiceAccountKeyRequest, + DisableServiceAccountRequest, + EnableServiceAccountKeyRequest, + EnableServiceAccountRequest, + GetRoleRequest, + GetServiceAccountKeyRequest, + GetServiceAccountRequest, + LintPolicyRequest, + LintPolicyResponse, + LintResult, + ListRolesRequest, + ListRolesResponse, + ListServiceAccountKeysRequest, + ListServiceAccountKeysResponse, + ListServiceAccountsRequest, + ListServiceAccountsResponse, + PatchServiceAccountRequest, + Permission, + QueryAuditableServicesRequest, + QueryAuditableServicesResponse, + QueryGrantableRolesRequest, + QueryGrantableRolesResponse, + QueryTestablePermissionsRequest, + QueryTestablePermissionsResponse, + Role, + RoleView, + ServiceAccount, + ServiceAccountKey, + ServiceAccountKeyAlgorithm, + ServiceAccountKeyOrigin, + ServiceAccountPrivateKeyType, + ServiceAccountPublicKeyType, + SignBlobRequest, + SignBlobResponse, + SignJwtRequest, + SignJwtResponse, + UndeleteRoleRequest, + UndeleteServiceAccountRequest, + UndeleteServiceAccountResponse, + UpdateRoleRequest, + UploadServiceAccountKeyRequest, +) + +__all__ = ( + "IAMClient", + "IAMAsyncClient", + "AuditData", + "CreateRoleRequest", + "CreateServiceAccountKeyRequest", + "CreateServiceAccountRequest", + "DeleteRoleRequest", + "DeleteServiceAccountKeyRequest", + "DeleteServiceAccountRequest", + "DisableServiceAccountKeyRequest", + "DisableServiceAccountRequest", + "EnableServiceAccountKeyRequest", + "EnableServiceAccountRequest", + "GetRoleRequest", + "GetServiceAccountKeyRequest", + "GetServiceAccountRequest", + "LintPolicyRequest", + "LintPolicyResponse", + "LintResult", + "ListRolesRequest", + "ListRolesResponse", + "ListServiceAccountKeysRequest", + "ListServiceAccountKeysResponse", + "ListServiceAccountsRequest", + "ListServiceAccountsResponse", + "PatchServiceAccountRequest", + "Permission", + "QueryAuditableServicesRequest", + "QueryAuditableServicesResponse", + "QueryGrantableRolesRequest", + "QueryGrantableRolesResponse", + "QueryTestablePermissionsRequest", + "QueryTestablePermissionsResponse", + "Role", + "ServiceAccount", + "ServiceAccountKey", + "SignBlobRequest", + "SignBlobResponse", + "SignJwtRequest", + "SignJwtResponse", + "UndeleteRoleRequest", + "UndeleteServiceAccountRequest", + "UndeleteServiceAccountResponse", + "UpdateRoleRequest", + "UploadServiceAccountKeyRequest", + "RoleView", + "ServiceAccountKeyAlgorithm", + "ServiceAccountKeyOrigin", + "ServiceAccountPrivateKeyType", + "ServiceAccountPublicKeyType", +) diff --git a/packages/google-cloud-iam/google/cloud/iam_admin/gapic_version.py b/packages/google-cloud-iam/google/cloud/iam_admin/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/packages/google-cloud-iam/google/cloud/iam_admin/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-iam/google/cloud/iam_admin/py.typed b/packages/google-cloud-iam/google/cloud/iam_admin/py.typed new file mode 100644 index 000000000000..a8a7868953e6 --- /dev/null +++ b/packages/google-cloud-iam/google/cloud/iam_admin/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-iam package uses inline types. diff --git a/packages/google-cloud-iam/google/cloud/iam_admin_v1/__init__.py b/packages/google-cloud-iam/google/cloud/iam_admin_v1/__init__.py new file mode 100644 index 000000000000..d4b8d711d2b7 --- /dev/null +++ b/packages/google-cloud-iam/google/cloud/iam_admin_v1/__init__.py @@ -0,0 +1,124 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.iam_admin_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.iam import IAMAsyncClient, IAMClient +from .types.audit_data import AuditData +from .types.iam import ( + CreateRoleRequest, + CreateServiceAccountKeyRequest, + CreateServiceAccountRequest, + DeleteRoleRequest, + DeleteServiceAccountKeyRequest, + DeleteServiceAccountRequest, + DisableServiceAccountKeyRequest, + DisableServiceAccountRequest, + EnableServiceAccountKeyRequest, + EnableServiceAccountRequest, + GetRoleRequest, + GetServiceAccountKeyRequest, + GetServiceAccountRequest, + LintPolicyRequest, + LintPolicyResponse, + LintResult, + ListRolesRequest, + ListRolesResponse, + ListServiceAccountKeysRequest, + ListServiceAccountKeysResponse, + ListServiceAccountsRequest, + ListServiceAccountsResponse, + PatchServiceAccountRequest, + Permission, + QueryAuditableServicesRequest, + QueryAuditableServicesResponse, + QueryGrantableRolesRequest, + QueryGrantableRolesResponse, + QueryTestablePermissionsRequest, + QueryTestablePermissionsResponse, + Role, + RoleView, + ServiceAccount, + ServiceAccountKey, + ServiceAccountKeyAlgorithm, + ServiceAccountKeyOrigin, + ServiceAccountPrivateKeyType, + ServiceAccountPublicKeyType, + SignBlobRequest, + SignBlobResponse, + SignJwtRequest, + SignJwtResponse, + UndeleteRoleRequest, + UndeleteServiceAccountRequest, + UndeleteServiceAccountResponse, + UpdateRoleRequest, + UploadServiceAccountKeyRequest, +) + +__all__ = ( + "IAMAsyncClient", + "AuditData", + "CreateRoleRequest", + "CreateServiceAccountKeyRequest", + "CreateServiceAccountRequest", + "DeleteRoleRequest", + "DeleteServiceAccountKeyRequest", + "DeleteServiceAccountRequest", + "DisableServiceAccountKeyRequest", + "DisableServiceAccountRequest", + "EnableServiceAccountKeyRequest", + "EnableServiceAccountRequest", + "GetRoleRequest", + "GetServiceAccountKeyRequest", + "GetServiceAccountRequest", + "IAMClient", + "LintPolicyRequest", + "LintPolicyResponse", + "LintResult", + "ListRolesRequest", + "ListRolesResponse", + "ListServiceAccountKeysRequest", + "ListServiceAccountKeysResponse", + "ListServiceAccountsRequest", + "ListServiceAccountsResponse", + "PatchServiceAccountRequest", + "Permission", + "QueryAuditableServicesRequest", + "QueryAuditableServicesResponse", + "QueryGrantableRolesRequest", + "QueryGrantableRolesResponse", + "QueryTestablePermissionsRequest", + "QueryTestablePermissionsResponse", + "Role", + "RoleView", + "ServiceAccount", + "ServiceAccountKey", + "ServiceAccountKeyAlgorithm", + "ServiceAccountKeyOrigin", + "ServiceAccountPrivateKeyType", + "ServiceAccountPublicKeyType", + "SignBlobRequest", + "SignBlobResponse", + "SignJwtRequest", + "SignJwtResponse", + "UndeleteRoleRequest", + "UndeleteServiceAccountRequest", + "UndeleteServiceAccountResponse", + "UpdateRoleRequest", + "UploadServiceAccountKeyRequest", +) diff --git a/packages/google-cloud-iam/google/cloud/iam_admin_v1/gapic_metadata.json b/packages/google-cloud-iam/google/cloud/iam_admin_v1/gapic_metadata.json new file mode 100644 index 000000000000..7de812d7d0c5 --- /dev/null +++ b/packages/google-cloud-iam/google/cloud/iam_admin_v1/gapic_metadata.json @@ -0,0 +1,333 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.iam_admin_v1", + "protoPackage": "google.iam.admin.v1", + "schema": "1.0", + "services": { + "IAM": { + "clients": { + "grpc": { + "libraryClient": "IAMClient", + "rpcs": { + "CreateRole": { + "methods": [ + "create_role" + ] + }, + "CreateServiceAccount": { + "methods": [ + "create_service_account" + ] + }, + "CreateServiceAccountKey": { + "methods": [ + "create_service_account_key" + ] + }, + "DeleteRole": { + "methods": [ + "delete_role" + ] + }, + "DeleteServiceAccount": { + "methods": [ + "delete_service_account" + ] + }, + "DeleteServiceAccountKey": { + "methods": [ + "delete_service_account_key" + ] + }, + "DisableServiceAccount": { + "methods": [ + "disable_service_account" + ] + }, + "DisableServiceAccountKey": { + "methods": [ + "disable_service_account_key" + ] + }, + "EnableServiceAccount": { + "methods": [ + "enable_service_account" + ] + }, + "EnableServiceAccountKey": { + "methods": [ + "enable_service_account_key" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetRole": { + "methods": [ + "get_role" + ] + }, + "GetServiceAccount": { + "methods": [ + "get_service_account" + ] + }, + "GetServiceAccountKey": { + "methods": [ + "get_service_account_key" + ] + }, + "LintPolicy": { + "methods": [ + "lint_policy" + ] + }, + "ListRoles": { + "methods": [ + "list_roles" + ] + }, + "ListServiceAccountKeys": { + "methods": [ + "list_service_account_keys" + ] + }, + "ListServiceAccounts": { + "methods": [ + "list_service_accounts" + ] + }, + "PatchServiceAccount": { + "methods": [ + "patch_service_account" + ] + }, + "QueryAuditableServices": { + "methods": [ + "query_auditable_services" + ] + }, + "QueryGrantableRoles": { + "methods": [ + "query_grantable_roles" + ] + }, + "QueryTestablePermissions": { + "methods": [ + "query_testable_permissions" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SignBlob": { + "methods": [ + "sign_blob" + ] + }, + "SignJwt": { + "methods": [ + "sign_jwt" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UndeleteRole": { + "methods": [ + "undelete_role" + ] + }, + "UndeleteServiceAccount": { + "methods": [ + "undelete_service_account" + ] + }, + "UpdateRole": { + "methods": [ + "update_role" + ] + }, + "UpdateServiceAccount": { + "methods": [ + "update_service_account" + ] + }, + "UploadServiceAccountKey": { + "methods": [ + "upload_service_account_key" + ] + } + } + }, + "grpc-async": { + "libraryClient": "IAMAsyncClient", + "rpcs": { + "CreateRole": { + "methods": [ + "create_role" + ] + }, + "CreateServiceAccount": { + "methods": [ + "create_service_account" + ] + }, + "CreateServiceAccountKey": { + "methods": [ + "create_service_account_key" + ] + }, + "DeleteRole": { + "methods": [ + "delete_role" + ] + }, + "DeleteServiceAccount": { + "methods": [ + "delete_service_account" + ] + }, + "DeleteServiceAccountKey": { + "methods": [ + "delete_service_account_key" + ] + }, + "DisableServiceAccount": { + "methods": [ + "disable_service_account" + ] + }, + "DisableServiceAccountKey": { + "methods": [ + "disable_service_account_key" + ] + }, + "EnableServiceAccount": { + "methods": [ + "enable_service_account" + ] + }, + "EnableServiceAccountKey": { + "methods": [ + "enable_service_account_key" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetRole": { + "methods": [ + "get_role" + ] + }, + "GetServiceAccount": { + "methods": [ + "get_service_account" + ] + }, + "GetServiceAccountKey": { + "methods": [ + "get_service_account_key" + ] + }, + "LintPolicy": { + "methods": [ + "lint_policy" + ] + }, + "ListRoles": { + "methods": [ + "list_roles" + ] + }, + "ListServiceAccountKeys": { + "methods": [ + "list_service_account_keys" + ] + }, + "ListServiceAccounts": { + "methods": [ + "list_service_accounts" + ] + }, + "PatchServiceAccount": { + "methods": [ + "patch_service_account" + ] + }, + "QueryAuditableServices": { + "methods": [ + "query_auditable_services" + ] + }, + "QueryGrantableRoles": { + "methods": [ + "query_grantable_roles" + ] + }, + "QueryTestablePermissions": { + "methods": [ + "query_testable_permissions" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "SignBlob": { + "methods": [ + "sign_blob" + ] + }, + "SignJwt": { + "methods": [ + "sign_jwt" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UndeleteRole": { + "methods": [ + "undelete_role" + ] + }, + "UndeleteServiceAccount": { + "methods": [ + "undelete_service_account" + ] + }, + "UpdateRole": { + "methods": [ + "update_role" + ] + }, + "UpdateServiceAccount": { + "methods": [ + "update_service_account" + ] + }, + "UploadServiceAccountKey": { + "methods": [ + "upload_service_account_key" + ] + } + } + } + } + } + } +} diff --git a/packages/google-cloud-iam/google/cloud/iam_admin_v1/gapic_version.py b/packages/google-cloud-iam/google/cloud/iam_admin_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/packages/google-cloud-iam/google/cloud/iam_admin_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-iam/google/cloud/iam_admin_v1/py.typed b/packages/google-cloud-iam/google/cloud/iam_admin_v1/py.typed new file mode 100644 index 000000000000..a8a7868953e6 --- /dev/null +++ b/packages/google-cloud-iam/google/cloud/iam_admin_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-iam package uses inline types. diff --git a/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/__init__.py b/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/__init__.py b/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/__init__.py new file mode 100644 index 000000000000..7d15186cd561 --- /dev/null +++ b/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import IAMAsyncClient +from .client import IAMClient + +__all__ = ( + "IAMClient", + "IAMAsyncClient", +) diff --git a/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/async_client.py b/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/async_client.py new file mode 100644 index 000000000000..b32e1544e54b --- /dev/null +++ b/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/async_client.py @@ -0,0 +1,3812 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) +import warnings + +from google.api_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.iam_admin_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.iam_admin_v1.services.iam import pagers +from google.cloud.iam_admin_v1.types import iam + +from .client import IAMClient +from .transports.base import DEFAULT_CLIENT_INFO, IAMTransport +from .transports.grpc_asyncio import IAMGrpcAsyncIOTransport + + +class IAMAsyncClient: + """Creates and manages Identity and Access Management (IAM) resources. + + You can use this service to work with all of the following + resources: + + - **Service accounts**, which identify an application or a virtual + machine (VM) instance rather than a person + - **Service account keys**, which service accounts use to + authenticate with Google APIs + - **IAM policies for service accounts**, which specify the roles + that a principal has for the service account + - **IAM custom roles**, which help you limit the number of + permissions that you grant to principals + + In addition, you can use this service to complete the following + tasks, among others: + + - Test whether a service account can use specific permissions + - Check which roles you can grant for a specific resource + - Lint, or validate, condition expressions in an IAM policy + + When you read data from the IAM API, each read is eventually + consistent. In other words, if you write data with the IAM API, then + immediately read that data, the read operation might return an older + version of the data. To deal with this behavior, your application + can retry the request with truncated exponential backoff. + + In contrast, writing data to the IAM API is sequentially consistent. + In other words, write operations are always processed in the order + in which they were received. + """ + + _client: IAMClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = IAMClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = IAMClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = IAMClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = IAMClient._DEFAULT_UNIVERSE + + key_path = staticmethod(IAMClient.key_path) + parse_key_path = staticmethod(IAMClient.parse_key_path) + service_account_path = staticmethod(IAMClient.service_account_path) + parse_service_account_path = staticmethod(IAMClient.parse_service_account_path) + common_billing_account_path = staticmethod(IAMClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod( + IAMClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(IAMClient.common_folder_path) + parse_common_folder_path = staticmethod(IAMClient.parse_common_folder_path) + common_organization_path = staticmethod(IAMClient.common_organization_path) + parse_common_organization_path = staticmethod( + IAMClient.parse_common_organization_path + ) + common_project_path = staticmethod(IAMClient.common_project_path) + parse_common_project_path = staticmethod(IAMClient.parse_common_project_path) + common_location_path = staticmethod(IAMClient.common_location_path) + parse_common_location_path = staticmethod(IAMClient.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: + IAMAsyncClient: The constructed client. + """ + return IAMClient.from_service_account_info.__func__(IAMAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + IAMAsyncClient: The constructed client. + """ + return IAMClient.from_service_account_file.__func__(IAMAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return IAMClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> IAMTransport: + """Returns the transport used by the client instance. + + Returns: + IAMTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial( + type(IAMClient).get_transport_class, type(IAMClient) + ) + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, IAMTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the iam 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 (Union[str, ~.IAMTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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 = IAMClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def list_service_accounts( + self, + request: Optional[Union[iam.ListServiceAccountsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServiceAccountsAsyncPager: + r"""Lists every [ServiceAccount][google.iam.admin.v1.ServiceAccount] + that belongs to a specific project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_list_service_accounts(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.ListServiceAccountsRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_service_accounts(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.ListServiceAccountsRequest, dict]]): + The request object. The service account list request. + name (:class:`str`): + Required. The resource name of the project associated + with the service accounts, such as + ``projects/my-project-123``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.services.iam.pagers.ListServiceAccountsAsyncPager: + The service account list response. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = iam.ListServiceAccountsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_service_accounts, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListServiceAccountsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_service_account( + self, + request: Optional[Union[iam.GetServiceAccountRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.ServiceAccount: + r"""Gets a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_get_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.GetServiceAccountRequest( + name="name_value", + ) + + # Make the request + response = await client.get_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.GetServiceAccountRequest, dict]]): + The request object. The service account get request. + name (:class:`str`): + Required. The resource name of the service account in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccount: + An IAM service account. + + A service account is an account for an application or + a virtual machine (VM) instance, not a person. You + can use a service account to call Google APIs. To + learn more, read the [overview of service + accounts](\ https://cloud.google.com/iam/help/service-accounts/overview). + + When you create a service account, you specify the + project ID that owns the service account, as well as + a name that must be unique within the project. IAM + uses these values to create an email address that + identifies the service account. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = iam.GetServiceAccountRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_service_account, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_service_account( + self, + request: Optional[Union[iam.CreateServiceAccountRequest, dict]] = None, + *, + name: Optional[str] = None, + account_id: Optional[str] = None, + service_account: Optional[iam.ServiceAccount] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.ServiceAccount: + r"""Creates a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_create_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.CreateServiceAccountRequest( + name="name_value", + account_id="account_id_value", + ) + + # Make the request + response = await client.create_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.CreateServiceAccountRequest, dict]]): + The request object. The service account create request. + name (:class:`str`): + Required. The resource name of the project associated + with the service accounts, such as + ``projects/my-project-123``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + account_id (:class:`str`): + Required. The account id that is used to generate the + service account email address and a stable unique id. It + is unique within a project, must be 6-30 characters + long, and match the regular expression + ``[a-z]([-a-z0-9]*[a-z0-9])`` to comply with RFC1035. + + This corresponds to the ``account_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_account (:class:`google.cloud.iam_admin_v1.types.ServiceAccount`): + The [ServiceAccount][google.iam.admin.v1.ServiceAccount] + resource to create. Currently, only the following values + are user assignable: ``display_name`` and + ``description``. + + This corresponds to the ``service_account`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccount: + An IAM service account. + + A service account is an account for an application or + a virtual machine (VM) instance, not a person. You + can use a service account to call Google APIs. To + learn more, read the [overview of service + accounts](\ https://cloud.google.com/iam/help/service-accounts/overview). + + When you create a service account, you specify the + project ID that owns the service account, as well as + a name that must be unique within the project. IAM + uses these values to create an email address that + identifies the service account. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, account_id, service_account]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = iam.CreateServiceAccountRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if account_id is not None: + request.account_id = account_id + if service_account is not None: + request.service_account = service_account + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_service_account, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_service_account( + self, + request: Optional[Union[iam.ServiceAccount, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.ServiceAccount: + r"""**Note:** We are in the process of deprecating this method. Use + [PatchServiceAccount][google.iam.admin.v1.IAM.PatchServiceAccount] + instead. + + Updates a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + You can update only the ``display_name`` field. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_update_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.ServiceAccount( + ) + + # Make the request + response = await client.update_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.ServiceAccount, dict]]): + The request object. An IAM service account. + + A service account is an account for an application or a + virtual machine (VM) instance, not a person. You can use + a service account to call Google APIs. To learn more, + read the `overview of service + accounts `__. + + When you create a service account, you specify the + project ID that owns the service account, as well as a + name that must be unique within the project. IAM uses + these values to create an email address that identifies + the service account. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccount: + An IAM service account. + + A service account is an account for an application or + a virtual machine (VM) instance, not a person. You + can use a service account to call Google APIs. To + learn more, read the [overview of service + accounts](\ https://cloud.google.com/iam/help/service-accounts/overview). + + When you create a service account, you specify the + project ID that owns the service account, as well as + a name that must be unique within the project. IAM + uses these values to create an email address that + identifies the service account. + + """ + # Create or coerce a protobuf request object. + request = iam.ServiceAccount(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_service_account, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def patch_service_account( + self, + request: Optional[Union[iam.PatchServiceAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.ServiceAccount: + r"""Patches a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_patch_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.PatchServiceAccountRequest( + ) + + # Make the request + response = await client.patch_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.PatchServiceAccountRequest, dict]]): + The request object. The service account patch request. + + You can patch only the ``display_name`` and + ``description`` fields. You must use the ``update_mask`` + field to specify which of these fields you want to + patch. + + Only the fields specified in the request are guaranteed + to be returned in the response. Other fields may be + empty in the response. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccount: + An IAM service account. + + A service account is an account for an application or + a virtual machine (VM) instance, not a person. You + can use a service account to call Google APIs. To + learn more, read the [overview of service + accounts](\ https://cloud.google.com/iam/help/service-accounts/overview). + + When you create a service account, you specify the + project ID that owns the service account, as well as + a name that must be unique within the project. IAM + uses these values to create an email address that + identifies the service account. + + """ + # Create or coerce a protobuf request object. + request = iam.PatchServiceAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.patch_service_account, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("service_account.name", request.service_account.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_service_account( + self, + request: Optional[Union[iam.DeleteServiceAccountRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + **Warning:** After you delete a service account, you might not + be able to undelete it. If you know that you need to re-enable + the service account in the future, use + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount] + instead. + + If you delete a service account, IAM permanently removes the + service account 30 days later. Google Cloud cannot recover the + service account after it is permanently removed, even if you + file a support request. + + To help avoid unplanned outages, we recommend that you disable + the service account before you delete it. Use + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount] + to disable the service account, then wait at least 24 hours and + watch for unintended consequences. If there are no unintended + consequences, you can delete the service account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_delete_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.DeleteServiceAccountRequest( + name="name_value", + ) + + # Make the request + await client.delete_service_account(request=request) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.DeleteServiceAccountRequest, dict]]): + The request object. The service account delete request. + name (:class:`str`): + Required. The resource name of the service account in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = iam.DeleteServiceAccountRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_service_account, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def undelete_service_account( + self, + request: Optional[Union[iam.UndeleteServiceAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.UndeleteServiceAccountResponse: + r"""Restores a deleted + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + **Important:** It is not always possible to restore a deleted + service account. Use this method only as a last resort. + + After you delete a service account, IAM permanently removes the + service account 30 days later. There is no way to restore a + deleted service account that has been permanently removed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_undelete_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.UndeleteServiceAccountRequest( + ) + + # Make the request + response = await client.undelete_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.UndeleteServiceAccountRequest, dict]]): + The request object. The service account undelete request. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.UndeleteServiceAccountResponse: + + """ + # Create or coerce a protobuf request object. + request = iam.UndeleteServiceAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.undelete_service_account, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def enable_service_account( + self, + request: Optional[Union[iam.EnableServiceAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Enables a [ServiceAccount][google.iam.admin.v1.ServiceAccount] + that was disabled by + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount]. + + If the service account is already enabled, then this method has + no effect. + + If the service account was disabled by other means—for example, + if Google disabled the service account because it was + compromised—you cannot use this method to enable the service + account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_enable_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.EnableServiceAccountRequest( + ) + + # Make the request + await client.enable_service_account(request=request) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.EnableServiceAccountRequest, dict]]): + The request object. The service account enable request. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + request = iam.EnableServiceAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.enable_service_account, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def disable_service_account( + self, + request: Optional[Union[iam.DisableServiceAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Disables a [ServiceAccount][google.iam.admin.v1.ServiceAccount] + immediately. + + If an application uses the service account to authenticate, that + application can no longer call Google APIs or access Google + Cloud resources. Existing access tokens for the service account + are rejected, and requests for new access tokens will fail. + + To re-enable the service account, use + [EnableServiceAccount][google.iam.admin.v1.IAM.EnableServiceAccount]. + After you re-enable the service account, its existing access + tokens will be accepted, and you can request new access tokens. + + To help avoid unplanned outages, we recommend that you disable + the service account before you delete it. Use this method to + disable the service account, then wait at least 24 hours and + watch for unintended consequences. If there are no unintended + consequences, you can delete the service account with + [DeleteServiceAccount][google.iam.admin.v1.IAM.DeleteServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_disable_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.DisableServiceAccountRequest( + ) + + # Make the request + await client.disable_service_account(request=request) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.DisableServiceAccountRequest, dict]]): + The request object. The service account disable request. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + request = iam.DisableServiceAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.disable_service_account, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_service_account_keys( + self, + request: Optional[Union[iam.ListServiceAccountKeysRequest, dict]] = None, + *, + name: Optional[str] = None, + key_types: Optional[ + MutableSequence[iam.ListServiceAccountKeysRequest.KeyType] + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.ListServiceAccountKeysResponse: + r"""Lists every + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey] for a + service account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_list_service_account_keys(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.ListServiceAccountKeysRequest( + name="name_value", + ) + + # Make the request + response = await client.list_service_account_keys(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.ListServiceAccountKeysRequest, dict]]): + The request object. The service account keys list + request. + name (:class:`str`): + Required. The resource name of the service account in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID``, will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_types (:class:`MutableSequence[google.cloud.iam_admin_v1.types.ListServiceAccountKeysRequest.KeyType]`): + Filters the types of keys the user + wants to include in the list response. + Duplicate key types are not allowed. If + no key type is provided, all keys are + returned. + + This corresponds to the ``key_types`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.ListServiceAccountKeysResponse: + The service account keys list + response. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, key_types]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = iam.ListServiceAccountKeysRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if key_types: + request.key_types.extend(key_types) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_service_account_keys, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_service_account_key( + self, + request: Optional[Union[iam.GetServiceAccountKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + public_key_type: Optional[iam.ServiceAccountPublicKeyType] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.ServiceAccountKey: + r"""Gets a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_get_service_account_key(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.GetServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_service_account_key(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.GetServiceAccountKeyRequest, dict]]): + The request object. The service account key get by id + request. + name (:class:`str`): + Required. The resource name of the service account key + in the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + public_key_type (:class:`google.cloud.iam_admin_v1.types.ServiceAccountPublicKeyType`): + Optional. The output format of the public key. The + default is ``TYPE_NONE``, which means that the public + key is not returned. + + This corresponds to the ``public_key_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccountKey: + Represents a service account key. + + A service account has two sets of + key-pairs: user-managed, and + system-managed. + + User-managed key-pairs can be created + and deleted by users. Users are + responsible for rotating these keys + periodically to ensure security of their + service accounts. Users retain the + private key of these key-pairs, and + Google retains ONLY the public key. + + System-managed keys are automatically + rotated by Google, and are used for + signing for a maximum of two weeks. The + rotation process is probabilistic, and + usage of the new key will gradually ramp + up and down over the key's lifetime. + + If you cache the public key set for a + service account, we recommend that you + update the cache every 15 minutes. + User-managed keys can be added and + removed at any time, so it is important + to update the cache frequently. For + Google-managed keys, Google will publish + a key at least 6 hours before it is + first used for signing and will keep + publishing it for at least 6 hours after + it was last used for signing. + + Public keys for all service accounts are + also published at the OAuth2 Service + Account API. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, public_key_type]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = iam.GetServiceAccountKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if public_key_type is not None: + request.public_key_type = public_key_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_service_account_key, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_service_account_key( + self, + request: Optional[Union[iam.CreateServiceAccountKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + private_key_type: Optional[iam.ServiceAccountPrivateKeyType] = None, + key_algorithm: Optional[iam.ServiceAccountKeyAlgorithm] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.ServiceAccountKey: + r"""Creates a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_create_service_account_key(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.CreateServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + response = await client.create_service_account_key(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.CreateServiceAccountKeyRequest, dict]]): + The request object. The service account key create + request. + name (:class:`str`): + Required. The resource name of the service account in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + private_key_type (:class:`google.cloud.iam_admin_v1.types.ServiceAccountPrivateKeyType`): + The output format of the private key. The default value + is ``TYPE_GOOGLE_CREDENTIALS_FILE``, which is the Google + Credentials File format. + + This corresponds to the ``private_key_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_algorithm (:class:`google.cloud.iam_admin_v1.types.ServiceAccountKeyAlgorithm`): + Which type of key and algorithm to + use for the key. The default is + currently a 2K RSA key. However this + may change in the future. + + This corresponds to the ``key_algorithm`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccountKey: + Represents a service account key. + + A service account has two sets of + key-pairs: user-managed, and + system-managed. + + User-managed key-pairs can be created + and deleted by users. Users are + responsible for rotating these keys + periodically to ensure security of their + service accounts. Users retain the + private key of these key-pairs, and + Google retains ONLY the public key. + + System-managed keys are automatically + rotated by Google, and are used for + signing for a maximum of two weeks. The + rotation process is probabilistic, and + usage of the new key will gradually ramp + up and down over the key's lifetime. + + If you cache the public key set for a + service account, we recommend that you + update the cache every 15 minutes. + User-managed keys can be added and + removed at any time, so it is important + to update the cache frequently. For + Google-managed keys, Google will publish + a key at least 6 hours before it is + first used for signing and will keep + publishing it for at least 6 hours after + it was last used for signing. + + Public keys for all service accounts are + also published at the OAuth2 Service + Account API. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, private_key_type, key_algorithm]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = iam.CreateServiceAccountKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if private_key_type is not None: + request.private_key_type = private_key_type + if key_algorithm is not None: + request.key_algorithm = key_algorithm + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_service_account_key, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def upload_service_account_key( + self, + request: Optional[Union[iam.UploadServiceAccountKeyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.ServiceAccountKey: + r"""Uploads the public key portion of a key pair that you manage, + and associates the public key with a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + After you upload the public key, you can use the private key + from the key pair as a service account key. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_upload_service_account_key(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.UploadServiceAccountKeyRequest( + ) + + # Make the request + response = await client.upload_service_account_key(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.UploadServiceAccountKeyRequest, dict]]): + The request object. The service account key upload + request. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccountKey: + Represents a service account key. + + A service account has two sets of + key-pairs: user-managed, and + system-managed. + + User-managed key-pairs can be created + and deleted by users. Users are + responsible for rotating these keys + periodically to ensure security of their + service accounts. Users retain the + private key of these key-pairs, and + Google retains ONLY the public key. + + System-managed keys are automatically + rotated by Google, and are used for + signing for a maximum of two weeks. The + rotation process is probabilistic, and + usage of the new key will gradually ramp + up and down over the key's lifetime. + + If you cache the public key set for a + service account, we recommend that you + update the cache every 15 minutes. + User-managed keys can be added and + removed at any time, so it is important + to update the cache frequently. For + Google-managed keys, Google will publish + a key at least 6 hours before it is + first used for signing and will keep + publishing it for at least 6 hours after + it was last used for signing. + + Public keys for all service accounts are + also published at the OAuth2 Service + Account API. + + """ + # Create or coerce a protobuf request object. + request = iam.UploadServiceAccountKeyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.upload_service_account_key, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_service_account_key( + self, + request: Optional[Union[iam.DeleteServiceAccountKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + Deleting a service account key does not revoke short-lived + credentials that have been issued based on the service account + key. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_delete_service_account_key(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.DeleteServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + await client.delete_service_account_key(request=request) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.DeleteServiceAccountKeyRequest, dict]]): + The request object. The service account key delete + request. + name (:class:`str`): + Required. The resource name of the service account key + in the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = iam.DeleteServiceAccountKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_service_account_key, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def disable_service_account_key( + self, + request: Optional[Union[iam.DisableServiceAccountKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Disable a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. A + disabled service account key can be re-enabled with + [EnableServiceAccountKey][google.iam.admin.v1.IAM.EnableServiceAccountKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_disable_service_account_key(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.DisableServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + await client.disable_service_account_key(request=request) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.DisableServiceAccountKeyRequest, dict]]): + The request object. The service account key disable + request. + name (:class:`str`): + Required. The resource name of the service account key + in the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = iam.DisableServiceAccountKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.disable_service_account_key, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def enable_service_account_key( + self, + request: Optional[Union[iam.EnableServiceAccountKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Enable a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_enable_service_account_key(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.EnableServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + await client.enable_service_account_key(request=request) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.EnableServiceAccountKeyRequest, dict]]): + The request object. The service account key enable + request. + name (:class:`str`): + Required. The resource name of the service account key + in the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = iam.EnableServiceAccountKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.enable_service_account_key, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def sign_blob( + self, + request: Optional[Union[iam.SignBlobRequest, dict]] = None, + *, + name: Optional[str] = None, + bytes_to_sign: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.SignBlobResponse: + r"""**Note:** This method is deprecated. Use the + ```signBlob`` `__ + method in the IAM Service Account Credentials API instead. If + you currently use this method, see the `migration + guide `__ + for instructions. + + Signs a blob using the system-managed private key for a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_sign_blob(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.SignBlobRequest( + name="name_value", + bytes_to_sign=b'bytes_to_sign_blob', + ) + + # Make the request + response = await client.sign_blob(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.SignBlobRequest, dict]]): + The request object. Deprecated. `Migrate to Service Account Credentials + API `__. + + The service account sign blob request. + name (:class:`str`): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The resource name of the service account in the + following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + bytes_to_sign (:class:`bytes`): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The bytes to sign. + + This corresponds to the ``bytes_to_sign`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.SignBlobResponse: + Deprecated. [Migrate to Service Account Credentials + API](\ https://cloud.google.com/iam/help/credentials/migrate-api). + + The service account sign blob response. + + """ + warnings.warn("IAMAsyncClient.sign_blob is deprecated", DeprecationWarning) + + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, bytes_to_sign]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = iam.SignBlobRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if bytes_to_sign is not None: + request.bytes_to_sign = bytes_to_sign + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.sign_blob, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def sign_jwt( + self, + request: Optional[Union[iam.SignJwtRequest, dict]] = None, + *, + name: Optional[str] = None, + payload: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.SignJwtResponse: + r"""**Note:** This method is deprecated. Use the + ```signJwt`` `__ + method in the IAM Service Account Credentials API instead. If + you currently use this method, see the `migration + guide `__ + for instructions. + + Signs a JSON Web Token (JWT) using the system-managed private + key for a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_sign_jwt(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.SignJwtRequest( + name="name_value", + payload="payload_value", + ) + + # Make the request + response = await client.sign_jwt(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.SignJwtRequest, dict]]): + The request object. Deprecated. `Migrate to Service Account Credentials + API `__. + + The service account sign JWT request. + name (:class:`str`): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The resource name of the service account in the + following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + payload (:class:`str`): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The JWT payload to sign. Must be a serialized JSON + object that contains a JWT Claims Set. For example: + ``{"sub": "user@example.com", "iat": 313435}`` + + If the JWT Claims Set contains an expiration time + (``exp``) claim, it must be an integer timestamp that is + not in the past and no more than 12 hours in the future. + + If the JWT Claims Set does not contain an expiration + time (``exp``) claim, this claim is added automatically, + with a timestamp that is 1 hour in the future. + + This corresponds to the ``payload`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.SignJwtResponse: + Deprecated. [Migrate to Service Account Credentials + API](\ https://cloud.google.com/iam/help/credentials/migrate-api). + + The service account sign JWT response. + + """ + warnings.warn("IAMAsyncClient.sign_jwt is deprecated", DeprecationWarning) + + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, payload]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = iam.SignJwtRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if payload is not None: + request.payload = payload + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.sign_jwt, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM policy that is attached to a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. This IAM + policy specifies which principals have access to the service + account. + + This method does not tell you whether the service account has + been granted any roles on other resources. To check whether a + service account has role grants on a resource, use the + ``getIamPolicy`` method for that resource. For example, to view + the role grants for a project, call the Resource Manager API's + ```projects.getIamPolicy`` `__ + method. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_get_iam_policy(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]): + The request object. Request message for ``GetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM policy that is attached to a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Use this method to grant or revoke access to the service + account. For example, you could grant a principal the ability to + impersonate the service account. + + This method does not enable the service account to access other + resources. To grant roles to a service account on a resource, + follow these steps: + + 1. Call the resource's ``getIamPolicy`` method to get its + current IAM policy. + 2. Edit the policy so that it binds the service account to an + IAM role for the resource. + 3. Call the resource's ``setIamPolicy`` method to update its IAM + policy. + + For detailed instructions, see `Manage access to project, + folders, and + organizations `__ + or `Manage access to other + resources `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_set_iam_policy(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]): + The request object. Request message for ``SetIamPolicy`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests whether the caller has the specified permissions on a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + async def sample_test_iam_permissions(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]]): + The request object. Request message for ``TestIamPermissions`` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`MutableSequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + request = iam_policy_pb2.TestIamPermissionsRequest( + resource=resource, permissions=permissions + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def query_grantable_roles( + self, + request: Optional[Union[iam.QueryGrantableRolesRequest, dict]] = None, + *, + full_resource_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.QueryGrantableRolesAsyncPager: + r"""Lists roles that can be granted on a Google Cloud + resource. A role is grantable if the IAM policy for the + resource can contain bindings to the role. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_query_grantable_roles(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.QueryGrantableRolesRequest( + full_resource_name="full_resource_name_value", + ) + + # Make the request + page_result = client.query_grantable_roles(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.QueryGrantableRolesRequest, dict]]): + The request object. The grantable role query request. + full_resource_name (:class:`str`): + Required. The full resource name to query from the list + of grantable roles. + + The name follows the Google Cloud Platform resource + format. For example, a Cloud Platform project with id + ``my-project`` will be named + ``//cloudresourcemanager.googleapis.com/projects/my-project``. + + This corresponds to the ``full_resource_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.services.iam.pagers.QueryGrantableRolesAsyncPager: + The grantable role query response. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([full_resource_name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = iam.QueryGrantableRolesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if full_resource_name is not None: + request.full_resource_name = full_resource_name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.query_grantable_roles, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.QueryGrantableRolesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_roles( + self, + request: Optional[Union[iam.ListRolesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListRolesAsyncPager: + r"""Lists every predefined [Role][google.iam.admin.v1.Role] that IAM + supports, or every custom role that is defined for an + organization or project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_list_roles(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.ListRolesRequest( + ) + + # Make the request + page_result = client.list_roles(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.ListRolesRequest, dict]]): + The request object. The request to get all roles defined + under a resource. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.services.iam.pagers.ListRolesAsyncPager: + The response containing the roles + defined under a resource. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + request = iam.ListRolesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_roles, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListRolesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_role( + self, + request: Optional[Union[iam.GetRoleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.Role: + r"""Gets the definition of a [Role][google.iam.admin.v1.Role]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_get_role(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.GetRoleRequest( + ) + + # Make the request + response = await client.get_role(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.GetRoleRequest, dict]]): + The request object. The request to get the definition of + an existing role. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.Role: + A role in the Identity and Access + Management API. + + """ + # Create or coerce a protobuf request object. + request = iam.GetRoleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_role, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_role( + self, + request: Optional[Union[iam.CreateRoleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.Role: + r"""Creates a new custom [Role][google.iam.admin.v1.Role]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_create_role(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.CreateRoleRequest( + ) + + # Make the request + response = await client.create_role(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.CreateRoleRequest, dict]]): + The request object. The request to create a new role. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.Role: + A role in the Identity and Access + Management API. + + """ + # Create or coerce a protobuf request object. + request = iam.CreateRoleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_role, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", 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_role( + self, + request: Optional[Union[iam.UpdateRoleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.Role: + r"""Updates the definition of a custom + [Role][google.iam.admin.v1.Role]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_update_role(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.UpdateRoleRequest( + ) + + # Make the request + response = await client.update_role(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.UpdateRoleRequest, dict]]): + The request object. The request to update a role. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.Role: + A role in the Identity and Access + Management API. + + """ + # Create or coerce a protobuf request object. + request = iam.UpdateRoleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_role, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_role( + self, + request: Optional[Union[iam.DeleteRoleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.Role: + r"""Deletes a custom [Role][google.iam.admin.v1.Role]. + + When you delete a custom role, the following changes occur + immediately: + + - You cannot bind a principal to the custom role in an IAM + [Policy][google.iam.v1.Policy]. + - Existing bindings to the custom role are not changed, but + they have no effect. + - By default, the response from + [ListRoles][google.iam.admin.v1.IAM.ListRoles] does not + include the custom role. + + You have 7 days to undelete the custom role. After 7 days, the + following changes occur: + + - The custom role is permanently deleted and cannot be + recovered. + - If an IAM policy contains a binding to the custom role, the + binding is permanently removed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_delete_role(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.DeleteRoleRequest( + ) + + # Make the request + response = await client.delete_role(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.DeleteRoleRequest, dict]]): + The request object. The request to delete an existing + role. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.Role: + A role in the Identity and Access + Management API. + + """ + # Create or coerce a protobuf request object. + request = iam.DeleteRoleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_role, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def undelete_role( + self, + request: Optional[Union[iam.UndeleteRoleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.Role: + r"""Undeletes a custom [Role][google.iam.admin.v1.Role]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_undelete_role(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.UndeleteRoleRequest( + ) + + # Make the request + response = await client.undelete_role(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.UndeleteRoleRequest, dict]]): + The request object. The request to undelete an existing + role. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.Role: + A role in the Identity and Access + Management API. + + """ + # Create or coerce a protobuf request object. + request = iam.UndeleteRoleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.undelete_role, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def query_testable_permissions( + self, + request: Optional[Union[iam.QueryTestablePermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.QueryTestablePermissionsAsyncPager: + r"""Lists every permission that you can test on a + resource. A permission is testable if you can check + whether a principal has that permission on the resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_query_testable_permissions(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.QueryTestablePermissionsRequest( + ) + + # Make the request + page_result = client.query_testable_permissions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.QueryTestablePermissionsRequest, dict]]): + The request object. A request to get permissions which + can be tested on a resource. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.services.iam.pagers.QueryTestablePermissionsAsyncPager: + The response containing permissions + which can be tested on a resource. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + request = iam.QueryTestablePermissionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.query_testable_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.QueryTestablePermissionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def query_auditable_services( + self, + request: Optional[Union[iam.QueryAuditableServicesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.QueryAuditableServicesResponse: + r"""Returns a list of services that allow you to opt into audit logs + that are not generated by default. + + To learn more about audit logs, see the `Logging + documentation `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_query_auditable_services(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.QueryAuditableServicesRequest( + ) + + # Make the request + response = await client.query_auditable_services(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.QueryAuditableServicesRequest, dict]]): + The request object. A request to get the list of + auditable services for a resource. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.QueryAuditableServicesResponse: + A response containing a list of + auditable services for a resource. + + """ + # Create or coerce a protobuf request object. + request = iam.QueryAuditableServicesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.query_auditable_services, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def lint_policy( + self, + request: Optional[Union[iam.LintPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.LintPolicyResponse: + r"""Lints, or validates, an IAM policy. Currently checks the + [google.iam.v1.Binding.condition][google.iam.v1.Binding.condition] + field, which contains a condition expression for a role binding. + + Successful calls to this method always return an HTTP ``200 OK`` + status code, even if the linter detects an issue in the IAM + policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + async def sample_lint_policy(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.LintPolicyRequest( + ) + + # Make the request + response = await client.lint_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.iam_admin_v1.types.LintPolicyRequest, dict]]): + The request object. The request to lint a Cloud IAM + policy object. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.LintPolicyResponse: + The response of a lint operation. An + empty response indicates the operation + was able to fully execute and no lint + issue was found. + + """ + # Create or coerce a protobuf request object. + request = iam.LintPolicyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.lint_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Validate the universe domain. + self._client._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) -> "IAMAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("IAMAsyncClient",) diff --git a/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/client.py b/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/client.py new file mode 100644 index 000000000000..9d71ddd7932e --- /dev/null +++ b/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/client.py @@ -0,0 +1,4208 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core 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.iam_admin_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 + +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.iam_admin_v1.services.iam import pagers +from google.cloud.iam_admin_v1.types import iam + +from .transports.base import DEFAULT_CLIENT_INFO, IAMTransport +from .transports.grpc import IAMGrpcTransport +from .transports.grpc_asyncio import IAMGrpcAsyncIOTransport + + +class IAMClientMeta(type): + """Metaclass for the IAM 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[IAMTransport]] + _transport_registry["grpc"] = IAMGrpcTransport + _transport_registry["grpc_asyncio"] = IAMGrpcAsyncIOTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[IAMTransport]: + """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 IAMClient(metaclass=IAMClientMeta): + """Creates and manages Identity and Access Management (IAM) resources. + + You can use this service to work with all of the following + resources: + + - **Service accounts**, which identify an application or a virtual + machine (VM) instance rather than a person + - **Service account keys**, which service accounts use to + authenticate with Google APIs + - **IAM policies for service accounts**, which specify the roles + that a principal has for the service account + - **IAM custom roles**, which help you limit the number of + permissions that you grant to principals + + In addition, you can use this service to complete the following + tasks, among others: + + - Test whether a service account can use specific permissions + - Check which roles you can grant for a specific resource + - Lint, or validate, condition expressions in an IAM policy + + When you read data from the IAM API, each read is eventually + consistent. In other words, if you write data with the IAM API, then + immediately read that data, the read operation might return an older + version of the data. To deal with this behavior, your application + can retry the request with truncated exponential backoff. + + In contrast, writing data to the IAM API is sequentially consistent. + In other words, write operations are always processed in the order + in which they were received. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "iam.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "iam.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + IAMClient: 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: + IAMClient: 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) -> IAMTransport: + """Returns the transport used by the client instance. + + Returns: + IAMTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def key_path( + project: str, + service_account: str, + key: str, + ) -> str: + """Returns a fully-qualified key string.""" + return "projects/{project}/serviceAccounts/{service_account}/keys/{key}".format( + project=project, + service_account=service_account, + key=key, + ) + + @staticmethod + def parse_key_path(path: str) -> Dict[str, str]: + """Parses a key path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/serviceAccounts/(?P.+?)/keys/(?P.+?)$", + path, + ) + 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 common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = IAMClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = IAMClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = IAMClient._DEFAULT_ENDPOINT_TEMPLATE.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 = IAMClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes( + client_universe: str, credentials: ga_credentials.Credentials + ) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = IAMClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError( + "The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default." + ) + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = ( + self._is_universe_domain_valid + or IAMClient._compare_universes( + self.universe_domain, self.transport._credentials + ) + ) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, IAMTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the iam client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, IAMTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + 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, + ) = IAMClient._read_environment_variables() + self._client_cert_source = IAMClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = IAMClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, IAMTransport) + if transport_provided: + # transport is a IAMTransport 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(IAMTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or IAMClient._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 = type(self).get_transport_class(cast(str, transport)) + self._transport = Transport( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def list_service_accounts( + self, + request: Optional[Union[iam.ListServiceAccountsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServiceAccountsPager: + r"""Lists every [ServiceAccount][google.iam.admin.v1.ServiceAccount] + that belongs to a specific project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_list_service_accounts(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.ListServiceAccountsRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_service_accounts(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.ListServiceAccountsRequest, dict]): + The request object. The service account list request. + name (str): + Required. The resource name of the project associated + with the service accounts, such as + ``projects/my-project-123``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.services.iam.pagers.ListServiceAccountsPager: + The service account list response. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a iam.ListServiceAccountsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.ListServiceAccountsRequest): + request = iam.ListServiceAccountsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_service_accounts] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListServiceAccountsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_service_account( + self, + request: Optional[Union[iam.GetServiceAccountRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.ServiceAccount: + r"""Gets a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_get_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.GetServiceAccountRequest( + name="name_value", + ) + + # Make the request + response = client.get_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.GetServiceAccountRequest, dict]): + The request object. The service account get request. + name (str): + Required. The resource name of the service account in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccount: + An IAM service account. + + A service account is an account for an application or + a virtual machine (VM) instance, not a person. You + can use a service account to call Google APIs. To + learn more, read the [overview of service + accounts](\ https://cloud.google.com/iam/help/service-accounts/overview). + + When you create a service account, you specify the + project ID that owns the service account, as well as + a name that must be unique within the project. IAM + uses these values to create an email address that + identifies the service account. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a iam.GetServiceAccountRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.GetServiceAccountRequest): + request = iam.GetServiceAccountRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_service_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_service_account( + self, + request: Optional[Union[iam.CreateServiceAccountRequest, dict]] = None, + *, + name: Optional[str] = None, + account_id: Optional[str] = None, + service_account: Optional[iam.ServiceAccount] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.ServiceAccount: + r"""Creates a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_create_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.CreateServiceAccountRequest( + name="name_value", + account_id="account_id_value", + ) + + # Make the request + response = client.create_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.CreateServiceAccountRequest, dict]): + The request object. The service account create request. + name (str): + Required. The resource name of the project associated + with the service accounts, such as + ``projects/my-project-123``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + account_id (str): + Required. The account id that is used to generate the + service account email address and a stable unique id. It + is unique within a project, must be 6-30 characters + long, and match the regular expression + ``[a-z]([-a-z0-9]*[a-z0-9])`` to comply with RFC1035. + + This corresponds to the ``account_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_account (google.cloud.iam_admin_v1.types.ServiceAccount): + The [ServiceAccount][google.iam.admin.v1.ServiceAccount] + resource to create. Currently, only the following values + are user assignable: ``display_name`` and + ``description``. + + This corresponds to the ``service_account`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccount: + An IAM service account. + + A service account is an account for an application or + a virtual machine (VM) instance, not a person. You + can use a service account to call Google APIs. To + learn more, read the [overview of service + accounts](\ https://cloud.google.com/iam/help/service-accounts/overview). + + When you create a service account, you specify the + project ID that owns the service account, as well as + a name that must be unique within the project. IAM + uses these values to create an email address that + identifies the service account. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, account_id, service_account]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a iam.CreateServiceAccountRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.CreateServiceAccountRequest): + request = iam.CreateServiceAccountRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if account_id is not None: + request.account_id = account_id + if service_account is not None: + request.service_account = service_account + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_service_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_service_account( + self, + request: Optional[Union[iam.ServiceAccount, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.ServiceAccount: + r"""**Note:** We are in the process of deprecating this method. Use + [PatchServiceAccount][google.iam.admin.v1.IAM.PatchServiceAccount] + instead. + + Updates a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + You can update only the ``display_name`` field. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_update_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.ServiceAccount( + ) + + # Make the request + response = client.update_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.ServiceAccount, dict]): + The request object. An IAM service account. + + A service account is an account for an application or a + virtual machine (VM) instance, not a person. You can use + a service account to call Google APIs. To learn more, + read the `overview of service + accounts `__. + + When you create a service account, you specify the + project ID that owns the service account, as well as a + name that must be unique within the project. IAM uses + these values to create an email address that identifies + the service account. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccount: + An IAM service account. + + A service account is an account for an application or + a virtual machine (VM) instance, not a person. You + can use a service account to call Google APIs. To + learn more, read the [overview of service + accounts](\ https://cloud.google.com/iam/help/service-accounts/overview). + + When you create a service account, you specify the + project ID that owns the service account, as well as + a name that must be unique within the project. IAM + uses these values to create an email address that + identifies the service account. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a iam.ServiceAccount. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.ServiceAccount): + request = iam.ServiceAccount(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_service_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def patch_service_account( + self, + request: Optional[Union[iam.PatchServiceAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.ServiceAccount: + r"""Patches a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_patch_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.PatchServiceAccountRequest( + ) + + # Make the request + response = client.patch_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.PatchServiceAccountRequest, dict]): + The request object. The service account patch request. + + You can patch only the ``display_name`` and + ``description`` fields. You must use the ``update_mask`` + field to specify which of these fields you want to + patch. + + Only the fields specified in the request are guaranteed + to be returned in the response. Other fields may be + empty in the response. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccount: + An IAM service account. + + A service account is an account for an application or + a virtual machine (VM) instance, not a person. You + can use a service account to call Google APIs. To + learn more, read the [overview of service + accounts](\ https://cloud.google.com/iam/help/service-accounts/overview). + + When you create a service account, you specify the + project ID that owns the service account, as well as + a name that must be unique within the project. IAM + uses these values to create an email address that + identifies the service account. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a iam.PatchServiceAccountRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.PatchServiceAccountRequest): + request = iam.PatchServiceAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.patch_service_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("service_account.name", request.service_account.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_service_account( + self, + request: Optional[Union[iam.DeleteServiceAccountRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + **Warning:** After you delete a service account, you might not + be able to undelete it. If you know that you need to re-enable + the service account in the future, use + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount] + instead. + + If you delete a service account, IAM permanently removes the + service account 30 days later. Google Cloud cannot recover the + service account after it is permanently removed, even if you + file a support request. + + To help avoid unplanned outages, we recommend that you disable + the service account before you delete it. Use + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount] + to disable the service account, then wait at least 24 hours and + watch for unintended consequences. If there are no unintended + consequences, you can delete the service account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_delete_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.DeleteServiceAccountRequest( + name="name_value", + ) + + # Make the request + client.delete_service_account(request=request) + + Args: + request (Union[google.cloud.iam_admin_v1.types.DeleteServiceAccountRequest, dict]): + The request object. The service account delete request. + name (str): + Required. The resource name of the service account in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a iam.DeleteServiceAccountRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.DeleteServiceAccountRequest): + request = iam.DeleteServiceAccountRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_service_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def undelete_service_account( + self, + request: Optional[Union[iam.UndeleteServiceAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.UndeleteServiceAccountResponse: + r"""Restores a deleted + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + **Important:** It is not always possible to restore a deleted + service account. Use this method only as a last resort. + + After you delete a service account, IAM permanently removes the + service account 30 days later. There is no way to restore a + deleted service account that has been permanently removed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_undelete_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.UndeleteServiceAccountRequest( + ) + + # Make the request + response = client.undelete_service_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.UndeleteServiceAccountRequest, dict]): + The request object. The service account undelete request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.UndeleteServiceAccountResponse: + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a iam.UndeleteServiceAccountRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.UndeleteServiceAccountRequest): + request = iam.UndeleteServiceAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.undelete_service_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def enable_service_account( + self, + request: Optional[Union[iam.EnableServiceAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Enables a [ServiceAccount][google.iam.admin.v1.ServiceAccount] + that was disabled by + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount]. + + If the service account is already enabled, then this method has + no effect. + + If the service account was disabled by other means—for example, + if Google disabled the service account because it was + compromised—you cannot use this method to enable the service + account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_enable_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.EnableServiceAccountRequest( + ) + + # Make the request + client.enable_service_account(request=request) + + Args: + request (Union[google.cloud.iam_admin_v1.types.EnableServiceAccountRequest, dict]): + The request object. The service account enable request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a iam.EnableServiceAccountRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.EnableServiceAccountRequest): + request = iam.EnableServiceAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.enable_service_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def disable_service_account( + self, + request: Optional[Union[iam.DisableServiceAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Disables a [ServiceAccount][google.iam.admin.v1.ServiceAccount] + immediately. + + If an application uses the service account to authenticate, that + application can no longer call Google APIs or access Google + Cloud resources. Existing access tokens for the service account + are rejected, and requests for new access tokens will fail. + + To re-enable the service account, use + [EnableServiceAccount][google.iam.admin.v1.IAM.EnableServiceAccount]. + After you re-enable the service account, its existing access + tokens will be accepted, and you can request new access tokens. + + To help avoid unplanned outages, we recommend that you disable + the service account before you delete it. Use this method to + disable the service account, then wait at least 24 hours and + watch for unintended consequences. If there are no unintended + consequences, you can delete the service account with + [DeleteServiceAccount][google.iam.admin.v1.IAM.DeleteServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_disable_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.DisableServiceAccountRequest( + ) + + # Make the request + client.disable_service_account(request=request) + + Args: + request (Union[google.cloud.iam_admin_v1.types.DisableServiceAccountRequest, dict]): + The request object. The service account disable request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a iam.DisableServiceAccountRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.DisableServiceAccountRequest): + request = iam.DisableServiceAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.disable_service_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_service_account_keys( + self, + request: Optional[Union[iam.ListServiceAccountKeysRequest, dict]] = None, + *, + name: Optional[str] = None, + key_types: Optional[ + MutableSequence[iam.ListServiceAccountKeysRequest.KeyType] + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.ListServiceAccountKeysResponse: + r"""Lists every + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey] for a + service account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_list_service_account_keys(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.ListServiceAccountKeysRequest( + name="name_value", + ) + + # Make the request + response = client.list_service_account_keys(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.ListServiceAccountKeysRequest, dict]): + The request object. The service account keys list + request. + name (str): + Required. The resource name of the service account in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID``, will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_types (MutableSequence[google.cloud.iam_admin_v1.types.ListServiceAccountKeysRequest.KeyType]): + Filters the types of keys the user + wants to include in the list response. + Duplicate key types are not allowed. If + no key type is provided, all keys are + returned. + + This corresponds to the ``key_types`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.ListServiceAccountKeysResponse: + The service account keys list + response. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, key_types]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a iam.ListServiceAccountKeysRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.ListServiceAccountKeysRequest): + request = iam.ListServiceAccountKeysRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if key_types is not None: + request.key_types = key_types + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_service_account_keys + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe 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_service_account_key( + self, + request: Optional[Union[iam.GetServiceAccountKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + public_key_type: Optional[iam.ServiceAccountPublicKeyType] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.ServiceAccountKey: + r"""Gets a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_get_service_account_key(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.GetServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + response = client.get_service_account_key(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.GetServiceAccountKeyRequest, dict]): + The request object. The service account key get by id + request. + name (str): + Required. The resource name of the service account key + in the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + public_key_type (google.cloud.iam_admin_v1.types.ServiceAccountPublicKeyType): + Optional. The output format of the public key. The + default is ``TYPE_NONE``, which means that the public + key is not returned. + + This corresponds to the ``public_key_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccountKey: + Represents a service account key. + + A service account has two sets of + key-pairs: user-managed, and + system-managed. + + User-managed key-pairs can be created + and deleted by users. Users are + responsible for rotating these keys + periodically to ensure security of their + service accounts. Users retain the + private key of these key-pairs, and + Google retains ONLY the public key. + + System-managed keys are automatically + rotated by Google, and are used for + signing for a maximum of two weeks. The + rotation process is probabilistic, and + usage of the new key will gradually ramp + up and down over the key's lifetime. + + If you cache the public key set for a + service account, we recommend that you + update the cache every 15 minutes. + User-managed keys can be added and + removed at any time, so it is important + to update the cache frequently. For + Google-managed keys, Google will publish + a key at least 6 hours before it is + first used for signing and will keep + publishing it for at least 6 hours after + it was last used for signing. + + Public keys for all service accounts are + also published at the OAuth2 Service + Account API. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, public_key_type]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a iam.GetServiceAccountKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.GetServiceAccountKeyRequest): + request = iam.GetServiceAccountKeyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if public_key_type is not None: + request.public_key_type = public_key_type + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_service_account_key] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_service_account_key( + self, + request: Optional[Union[iam.CreateServiceAccountKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + private_key_type: Optional[iam.ServiceAccountPrivateKeyType] = None, + key_algorithm: Optional[iam.ServiceAccountKeyAlgorithm] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.ServiceAccountKey: + r"""Creates a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_create_service_account_key(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.CreateServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + response = client.create_service_account_key(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.CreateServiceAccountKeyRequest, dict]): + The request object. The service account key create + request. + name (str): + Required. The resource name of the service account in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + private_key_type (google.cloud.iam_admin_v1.types.ServiceAccountPrivateKeyType): + The output format of the private key. The default value + is ``TYPE_GOOGLE_CREDENTIALS_FILE``, which is the Google + Credentials File format. + + This corresponds to the ``private_key_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_algorithm (google.cloud.iam_admin_v1.types.ServiceAccountKeyAlgorithm): + Which type of key and algorithm to + use for the key. The default is + currently a 2K RSA key. However this + may change in the future. + + This corresponds to the ``key_algorithm`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccountKey: + Represents a service account key. + + A service account has two sets of + key-pairs: user-managed, and + system-managed. + + User-managed key-pairs can be created + and deleted by users. Users are + responsible for rotating these keys + periodically to ensure security of their + service accounts. Users retain the + private key of these key-pairs, and + Google retains ONLY the public key. + + System-managed keys are automatically + rotated by Google, and are used for + signing for a maximum of two weeks. The + rotation process is probabilistic, and + usage of the new key will gradually ramp + up and down over the key's lifetime. + + If you cache the public key set for a + service account, we recommend that you + update the cache every 15 minutes. + User-managed keys can be added and + removed at any time, so it is important + to update the cache frequently. For + Google-managed keys, Google will publish + a key at least 6 hours before it is + first used for signing and will keep + publishing it for at least 6 hours after + it was last used for signing. + + Public keys for all service accounts are + also published at the OAuth2 Service + Account API. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, private_key_type, key_algorithm]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a iam.CreateServiceAccountKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.CreateServiceAccountKeyRequest): + request = iam.CreateServiceAccountKeyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if private_key_type is not None: + request.private_key_type = private_key_type + if key_algorithm is not None: + request.key_algorithm = key_algorithm + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_service_account_key + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def upload_service_account_key( + self, + request: Optional[Union[iam.UploadServiceAccountKeyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.ServiceAccountKey: + r"""Uploads the public key portion of a key pair that you manage, + and associates the public key with a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + After you upload the public key, you can use the private key + from the key pair as a service account key. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_upload_service_account_key(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.UploadServiceAccountKeyRequest( + ) + + # Make the request + response = client.upload_service_account_key(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.UploadServiceAccountKeyRequest, dict]): + The request object. The service account key upload + request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.ServiceAccountKey: + Represents a service account key. + + A service account has two sets of + key-pairs: user-managed, and + system-managed. + + User-managed key-pairs can be created + and deleted by users. Users are + responsible for rotating these keys + periodically to ensure security of their + service accounts. Users retain the + private key of these key-pairs, and + Google retains ONLY the public key. + + System-managed keys are automatically + rotated by Google, and are used for + signing for a maximum of two weeks. The + rotation process is probabilistic, and + usage of the new key will gradually ramp + up and down over the key's lifetime. + + If you cache the public key set for a + service account, we recommend that you + update the cache every 15 minutes. + User-managed keys can be added and + removed at any time, so it is important + to update the cache frequently. For + Google-managed keys, Google will publish + a key at least 6 hours before it is + first used for signing and will keep + publishing it for at least 6 hours after + it was last used for signing. + + Public keys for all service accounts are + also published at the OAuth2 Service + Account API. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a iam.UploadServiceAccountKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.UploadServiceAccountKeyRequest): + request = iam.UploadServiceAccountKeyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.upload_service_account_key + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe 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_service_account_key( + self, + request: Optional[Union[iam.DeleteServiceAccountKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + Deleting a service account key does not revoke short-lived + credentials that have been issued based on the service account + key. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_delete_service_account_key(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.DeleteServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + client.delete_service_account_key(request=request) + + Args: + request (Union[google.cloud.iam_admin_v1.types.DeleteServiceAccountKeyRequest, dict]): + The request object. The service account key delete + request. + name (str): + Required. The resource name of the service account key + in the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a iam.DeleteServiceAccountKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.DeleteServiceAccountKeyRequest): + request = iam.DeleteServiceAccountKeyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_service_account_key + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def disable_service_account_key( + self, + request: Optional[Union[iam.DisableServiceAccountKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Disable a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. A + disabled service account key can be re-enabled with + [EnableServiceAccountKey][google.iam.admin.v1.IAM.EnableServiceAccountKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_disable_service_account_key(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.DisableServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + client.disable_service_account_key(request=request) + + Args: + request (Union[google.cloud.iam_admin_v1.types.DisableServiceAccountKeyRequest, dict]): + The request object. The service account key disable + request. + name (str): + Required. The resource name of the service account key + in the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a iam.DisableServiceAccountKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.DisableServiceAccountKeyRequest): + request = iam.DisableServiceAccountKeyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.disable_service_account_key + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def enable_service_account_key( + self, + request: Optional[Union[iam.EnableServiceAccountKeyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Enable a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_enable_service_account_key(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.EnableServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + client.enable_service_account_key(request=request) + + Args: + request (Union[google.cloud.iam_admin_v1.types.EnableServiceAccountKeyRequest, dict]): + The request object. The service account key enable + request. + name (str): + Required. The resource name of the service account key + in the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a iam.EnableServiceAccountKeyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.EnableServiceAccountKeyRequest): + request = iam.EnableServiceAccountKeyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.enable_service_account_key + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def sign_blob( + self, + request: Optional[Union[iam.SignBlobRequest, dict]] = None, + *, + name: Optional[str] = None, + bytes_to_sign: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.SignBlobResponse: + r"""**Note:** This method is deprecated. Use the + ```signBlob`` `__ + method in the IAM Service Account Credentials API instead. If + you currently use this method, see the `migration + guide `__ + for instructions. + + Signs a blob using the system-managed private key for a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_sign_blob(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.SignBlobRequest( + name="name_value", + bytes_to_sign=b'bytes_to_sign_blob', + ) + + # Make the request + response = client.sign_blob(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.SignBlobRequest, dict]): + The request object. Deprecated. `Migrate to Service Account Credentials + API `__. + + The service account sign blob request. + name (str): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The resource name of the service account in the + following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + bytes_to_sign (bytes): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The bytes to sign. + + This corresponds to the ``bytes_to_sign`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.SignBlobResponse: + Deprecated. [Migrate to Service Account Credentials + API](\ https://cloud.google.com/iam/help/credentials/migrate-api). + + The service account sign blob response. + + """ + warnings.warn("IAMClient.sign_blob is deprecated", DeprecationWarning) + + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, bytes_to_sign]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a iam.SignBlobRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.SignBlobRequest): + request = iam.SignBlobRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if bytes_to_sign is not None: + request.bytes_to_sign = bytes_to_sign + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.sign_blob] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def sign_jwt( + self, + request: Optional[Union[iam.SignJwtRequest, dict]] = None, + *, + name: Optional[str] = None, + payload: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.SignJwtResponse: + r"""**Note:** This method is deprecated. Use the + ```signJwt`` `__ + method in the IAM Service Account Credentials API instead. If + you currently use this method, see the `migration + guide `__ + for instructions. + + Signs a JSON Web Token (JWT) using the system-managed private + key for a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_sign_jwt(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.SignJwtRequest( + name="name_value", + payload="payload_value", + ) + + # Make the request + response = client.sign_jwt(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.SignJwtRequest, dict]): + The request object. Deprecated. `Migrate to Service Account Credentials + API `__. + + The service account sign JWT request. + name (str): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The resource name of the service account in the + following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will + infer the project from the account. The ``ACCOUNT`` + value can be the ``email`` address or the ``unique_id`` + of the service account. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + payload (str): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The JWT payload to sign. Must be a serialized JSON + object that contains a JWT Claims Set. For example: + ``{"sub": "user@example.com", "iat": 313435}`` + + If the JWT Claims Set contains an expiration time + (``exp``) claim, it must be an integer timestamp that is + not in the past and no more than 12 hours in the future. + + If the JWT Claims Set does not contain an expiration + time (``exp``) claim, this claim is added automatically, + with a timestamp that is 1 hour in the future. + + This corresponds to the ``payload`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.SignJwtResponse: + Deprecated. [Migrate to Service Account Credentials + API](\ https://cloud.google.com/iam/help/credentials/migrate-api). + + The service account sign JWT response. + + """ + warnings.warn("IAMClient.sign_jwt is deprecated", DeprecationWarning) + + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, payload]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a iam.SignJwtRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.SignJwtRequest): + request = iam.SignJwtRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if payload is not None: + request.payload = payload + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.sign_jwt] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM policy that is attached to a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. This IAM + policy specifies which principals have access to the service + account. + + This method does not tell you whether the service account has + been granted any roles on other resources. To check whether a + service account has role grants on a resource, use the + ``getIamPolicy`` method for that resource. For example, to view + the role grants for a project, call the Resource Manager API's + ```projects.getIamPolicy`` `__ + method. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_get_iam_policy(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]): + The request object. Request message for ``GetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.GetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.GetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + resource: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM policy that is attached to a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Use this method to grant or revoke access to the service + account. For example, you could grant a principal the ability to + impersonate the service account. + + This method does not enable the service account to access other + resources. To grant roles to a service account on a resource, + follow these steps: + + 1. Call the resource's ``getIamPolicy`` method to get its + current IAM policy. + 2. Edit the policy so that it binds the service account to an + IAM role for the resource. + 3. Call the resource's ``setIamPolicy`` method to update its IAM + policy. + + For detailed instructions, see `Manage access to project, + folders, and + organizations `__ + or `Manage access to other + resources `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_set_iam_policy(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]): + The request object. Request message for ``SetIamPolicy`` method. + resource (str): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which specifies access + controls for Google Cloud resources. + + A Policy is a collection of bindings. A binding binds + one or more members, or principals, to a single role. + Principals can be user accounts, service accounts, + Google groups, and domains (such as G Suite). A role + is a named list of permissions; each role can be an + IAM predefined role or a user-created custom role. + + For some types of Google Cloud resources, a binding + can also specify a condition, which is a logical + expression that allows access to a resource only if + the expression evaluates to true. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the [IAM + documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). + + **JSON example:** + + :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \` + + **YAML example:** + + :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \` + + For a description of IAM and its features, see the + [IAM + documentation](\ https://cloud.google.com/iam/docs/). + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.SetIamPolicyRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.SetIamPolicyRequest() + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + resource: Optional[str] = None, + permissions: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests whether the caller has the specified permissions on a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + from google.iam.v1 import iam_policy_pb2 # type: ignore + + def sample_test_iam_permissions(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]): + The request object. Request message for ``TestIamPermissions`` method. + resource (str): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (MutableSequence[str]): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + + This corresponds to the ``permissions`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse: + Response message for TestIamPermissions method. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([resource, permissions]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + if isinstance(request, dict): + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + elif not request: + # Null request, just make one. + request = iam_policy_pb2.TestIamPermissionsRequest() + if resource is not None: + request.resource = resource + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def query_grantable_roles( + self, + request: Optional[Union[iam.QueryGrantableRolesRequest, dict]] = None, + *, + full_resource_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.QueryGrantableRolesPager: + r"""Lists roles that can be granted on a Google Cloud + resource. A role is grantable if the IAM policy for the + resource can contain bindings to the role. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_query_grantable_roles(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.QueryGrantableRolesRequest( + full_resource_name="full_resource_name_value", + ) + + # Make the request + page_result = client.query_grantable_roles(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.QueryGrantableRolesRequest, dict]): + The request object. The grantable role query request. + full_resource_name (str): + Required. The full resource name to query from the list + of grantable roles. + + The name follows the Google Cloud Platform resource + format. For example, a Cloud Platform project with id + ``my-project`` will be named + ``//cloudresourcemanager.googleapis.com/projects/my-project``. + + This corresponds to the ``full_resource_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.services.iam.pagers.QueryGrantableRolesPager: + The grantable role query response. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([full_resource_name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a iam.QueryGrantableRolesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.QueryGrantableRolesRequest): + request = iam.QueryGrantableRolesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if full_resource_name is not None: + request.full_resource_name = full_resource_name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.query_grantable_roles] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.QueryGrantableRolesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_roles( + self, + request: Optional[Union[iam.ListRolesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListRolesPager: + r"""Lists every predefined [Role][google.iam.admin.v1.Role] that IAM + supports, or every custom role that is defined for an + organization or project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_list_roles(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.ListRolesRequest( + ) + + # Make the request + page_result = client.list_roles(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.ListRolesRequest, dict]): + The request object. The request to get all roles defined + under a resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.services.iam.pagers.ListRolesPager: + The response containing the roles + defined under a resource. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a iam.ListRolesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.ListRolesRequest): + request = iam.ListRolesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_roles] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListRolesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_role( + self, + request: Optional[Union[iam.GetRoleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.Role: + r"""Gets the definition of a [Role][google.iam.admin.v1.Role]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_get_role(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.GetRoleRequest( + ) + + # Make the request + response = client.get_role(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.GetRoleRequest, dict]): + The request object. The request to get the definition of + an existing role. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.Role: + A role in the Identity and Access + Management API. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a iam.GetRoleRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.GetRoleRequest): + request = iam.GetRoleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_role] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_role( + self, + request: Optional[Union[iam.CreateRoleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.Role: + r"""Creates a new custom [Role][google.iam.admin.v1.Role]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_create_role(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.CreateRoleRequest( + ) + + # Make the request + response = client.create_role(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.CreateRoleRequest, dict]): + The request object. The request to create a new role. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.Role: + A role in the Identity and Access + Management API. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a iam.CreateRoleRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.CreateRoleRequest): + request = iam.CreateRoleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_role] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_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_role( + self, + request: Optional[Union[iam.UpdateRoleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.Role: + r"""Updates the definition of a custom + [Role][google.iam.admin.v1.Role]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_update_role(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.UpdateRoleRequest( + ) + + # Make the request + response = client.update_role(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.UpdateRoleRequest, dict]): + The request object. The request to update a role. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.Role: + A role in the Identity and Access + Management API. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a iam.UpdateRoleRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.UpdateRoleRequest): + request = iam.UpdateRoleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_role] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe 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_role( + self, + request: Optional[Union[iam.DeleteRoleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.Role: + r"""Deletes a custom [Role][google.iam.admin.v1.Role]. + + When you delete a custom role, the following changes occur + immediately: + + - You cannot bind a principal to the custom role in an IAM + [Policy][google.iam.v1.Policy]. + - Existing bindings to the custom role are not changed, but + they have no effect. + - By default, the response from + [ListRoles][google.iam.admin.v1.IAM.ListRoles] does not + include the custom role. + + You have 7 days to undelete the custom role. After 7 days, the + following changes occur: + + - The custom role is permanently deleted and cannot be + recovered. + - If an IAM policy contains a binding to the custom role, the + binding is permanently removed. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_delete_role(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.DeleteRoleRequest( + ) + + # Make the request + response = client.delete_role(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.DeleteRoleRequest, dict]): + The request object. The request to delete an existing + role. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.Role: + A role in the Identity and Access + Management API. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a iam.DeleteRoleRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.DeleteRoleRequest): + request = iam.DeleteRoleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_role] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe 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_role( + self, + request: Optional[Union[iam.UndeleteRoleRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.Role: + r"""Undeletes a custom [Role][google.iam.admin.v1.Role]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_undelete_role(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.UndeleteRoleRequest( + ) + + # Make the request + response = client.undelete_role(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.UndeleteRoleRequest, dict]): + The request object. The request to undelete an existing + role. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.Role: + A role in the Identity and Access + Management API. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a iam.UndeleteRoleRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.UndeleteRoleRequest): + request = iam.UndeleteRoleRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.undelete_role] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def query_testable_permissions( + self, + request: Optional[Union[iam.QueryTestablePermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.QueryTestablePermissionsPager: + r"""Lists every permission that you can test on a + resource. A permission is testable if you can check + whether a principal has that permission on the resource. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_query_testable_permissions(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.QueryTestablePermissionsRequest( + ) + + # Make the request + page_result = client.query_testable_permissions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.QueryTestablePermissionsRequest, dict]): + The request object. A request to get permissions which + can be tested on a resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.services.iam.pagers.QueryTestablePermissionsPager: + The response containing permissions + which can be tested on a resource. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a iam.QueryTestablePermissionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.QueryTestablePermissionsRequest): + request = iam.QueryTestablePermissionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.query_testable_permissions + ] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.QueryTestablePermissionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def query_auditable_services( + self, + request: Optional[Union[iam.QueryAuditableServicesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.QueryAuditableServicesResponse: + r"""Returns a list of services that allow you to opt into audit logs + that are not generated by default. + + To learn more about audit logs, see the `Logging + documentation `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_query_auditable_services(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.QueryAuditableServicesRequest( + ) + + # Make the request + response = client.query_auditable_services(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.QueryAuditableServicesRequest, dict]): + The request object. A request to get the list of + auditable services for a resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.QueryAuditableServicesResponse: + A response containing a list of + auditable services for a resource. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a iam.QueryAuditableServicesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.QueryAuditableServicesRequest): + request = iam.QueryAuditableServicesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.query_auditable_services] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def lint_policy( + self, + request: Optional[Union[iam.LintPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam.LintPolicyResponse: + r"""Lints, or validates, an IAM policy. Currently checks the + [google.iam.v1.Binding.condition][google.iam.v1.Binding.condition] + field, which contains a condition expression for a role binding. + + Successful calls to this method always return an HTTP ``200 OK`` + status code, even if the linter detects an issue in the IAM + policy. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import iam_admin_v1 + + def sample_lint_policy(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.LintPolicyRequest( + ) + + # Make the request + response = client.lint_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.iam_admin_v1.types.LintPolicyRequest, dict]): + The request object. The request to lint a Cloud IAM + policy object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.iam_admin_v1.types.LintPolicyResponse: + The response of a lint operation. An + empty response indicates the operation + was able to fully execute and no lint + issue was found. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a iam.LintPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, iam.LintPolicyRequest): + request = iam.LintPolicyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.lint_policy] + + # Validate the universe 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) -> "IAMClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("IAMClient",) diff --git a/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/pagers.py b/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/pagers.py new file mode 100644 index 000000000000..f248c7766d7a --- /dev/null +++ b/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/pagers.py @@ -0,0 +1,539 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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, +) + +from google.cloud.iam_admin_v1.types import iam + + +class ListServiceAccountsPager: + """A pager for iterating through ``list_service_accounts`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_admin_v1.types.ListServiceAccountsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``accounts`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListServiceAccounts`` requests and continue to iterate + through the ``accounts`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_admin_v1.types.ListServiceAccountsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., iam.ListServiceAccountsResponse], + request: iam.ListServiceAccountsRequest, + response: iam.ListServiceAccountsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_admin_v1.types.ListServiceAccountsRequest): + The initial request object. + response (google.cloud.iam_admin_v1.types.ListServiceAccountsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = iam.ListServiceAccountsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[iam.ListServiceAccountsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[iam.ServiceAccount]: + for page in self.pages: + yield from page.accounts + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListServiceAccountsAsyncPager: + """A pager for iterating through ``list_service_accounts`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_admin_v1.types.ListServiceAccountsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``accounts`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListServiceAccounts`` requests and continue to iterate + through the ``accounts`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_admin_v1.types.ListServiceAccountsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[iam.ListServiceAccountsResponse]], + request: iam.ListServiceAccountsRequest, + response: iam.ListServiceAccountsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_admin_v1.types.ListServiceAccountsRequest): + The initial request object. + response (google.cloud.iam_admin_v1.types.ListServiceAccountsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = iam.ListServiceAccountsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[iam.ListServiceAccountsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[iam.ServiceAccount]: + async def async_generator(): + async for page in self.pages: + for response in page.accounts: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class QueryGrantableRolesPager: + """A pager for iterating through ``query_grantable_roles`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_admin_v1.types.QueryGrantableRolesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``roles`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``QueryGrantableRoles`` requests and continue to iterate + through the ``roles`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_admin_v1.types.QueryGrantableRolesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., iam.QueryGrantableRolesResponse], + request: iam.QueryGrantableRolesRequest, + response: iam.QueryGrantableRolesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_admin_v1.types.QueryGrantableRolesRequest): + The initial request object. + response (google.cloud.iam_admin_v1.types.QueryGrantableRolesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = iam.QueryGrantableRolesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[iam.QueryGrantableRolesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[iam.Role]: + for page in self.pages: + yield from page.roles + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class QueryGrantableRolesAsyncPager: + """A pager for iterating through ``query_grantable_roles`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_admin_v1.types.QueryGrantableRolesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``roles`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``QueryGrantableRoles`` requests and continue to iterate + through the ``roles`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_admin_v1.types.QueryGrantableRolesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[iam.QueryGrantableRolesResponse]], + request: iam.QueryGrantableRolesRequest, + response: iam.QueryGrantableRolesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_admin_v1.types.QueryGrantableRolesRequest): + The initial request object. + response (google.cloud.iam_admin_v1.types.QueryGrantableRolesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = iam.QueryGrantableRolesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[iam.QueryGrantableRolesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[iam.Role]: + async def async_generator(): + async for page in self.pages: + for response in page.roles: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRolesPager: + """A pager for iterating through ``list_roles`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_admin_v1.types.ListRolesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``roles`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRoles`` requests and continue to iterate + through the ``roles`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_admin_v1.types.ListRolesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., iam.ListRolesResponse], + request: iam.ListRolesRequest, + response: iam.ListRolesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_admin_v1.types.ListRolesRequest): + The initial request object. + response (google.cloud.iam_admin_v1.types.ListRolesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = iam.ListRolesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[iam.ListRolesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[iam.Role]: + for page in self.pages: + yield from page.roles + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRolesAsyncPager: + """A pager for iterating through ``list_roles`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_admin_v1.types.ListRolesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``roles`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRoles`` requests and continue to iterate + through the ``roles`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_admin_v1.types.ListRolesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[iam.ListRolesResponse]], + request: iam.ListRolesRequest, + response: iam.ListRolesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_admin_v1.types.ListRolesRequest): + The initial request object. + response (google.cloud.iam_admin_v1.types.ListRolesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = iam.ListRolesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[iam.ListRolesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[iam.Role]: + async def async_generator(): + async for page in self.pages: + for response in page.roles: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class QueryTestablePermissionsPager: + """A pager for iterating through ``query_testable_permissions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_admin_v1.types.QueryTestablePermissionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``permissions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``QueryTestablePermissions`` requests and continue to iterate + through the ``permissions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_admin_v1.types.QueryTestablePermissionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., iam.QueryTestablePermissionsResponse], + request: iam.QueryTestablePermissionsRequest, + response: iam.QueryTestablePermissionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_admin_v1.types.QueryTestablePermissionsRequest): + The initial request object. + response (google.cloud.iam_admin_v1.types.QueryTestablePermissionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = iam.QueryTestablePermissionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[iam.QueryTestablePermissionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[iam.Permission]: + for page in self.pages: + yield from page.permissions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class QueryTestablePermissionsAsyncPager: + """A pager for iterating through ``query_testable_permissions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.iam_admin_v1.types.QueryTestablePermissionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``permissions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``QueryTestablePermissions`` requests and continue to iterate + through the ``permissions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.iam_admin_v1.types.QueryTestablePermissionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[iam.QueryTestablePermissionsResponse]], + request: iam.QueryTestablePermissionsRequest, + response: iam.QueryTestablePermissionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.iam_admin_v1.types.QueryTestablePermissionsRequest): + The initial request object. + response (google.cloud.iam_admin_v1.types.QueryTestablePermissionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = iam.QueryTestablePermissionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[iam.QueryTestablePermissionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[iam.Permission]: + async def async_generator(): + async for page in self.pages: + for response in page.permissions: + 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-iam/google/cloud/iam_admin_v1/services/iam/transports/__init__.py b/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/transports/__init__.py new file mode 100644 index 000000000000..1da1955bab25 --- /dev/null +++ b/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/transports/__init__.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 IAMTransport +from .grpc import IAMGrpcTransport +from .grpc_asyncio import IAMGrpcAsyncIOTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[IAMTransport]] +_transport_registry["grpc"] = IAMGrpcTransport +_transport_registry["grpc_asyncio"] = IAMGrpcAsyncIOTransport + +__all__ = ( + "IAMTransport", + "IAMGrpcTransport", + "IAMGrpcAsyncIOTransport", +) diff --git a/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/transports/base.py b/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/transports/base.py new file mode 100644 index 000000000000..715dab610075 --- /dev/null +++ b/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/transports/base.py @@ -0,0 +1,654 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.iam_admin_v1 import gapic_version as package_version +from google.cloud.iam_admin_v1.types import iam + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class IAMTransport(abc.ABC): + """Abstract transport class for IAM.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "iam.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.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: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_service_accounts: gapic_v1.method.wrap_method( + self.list_service_accounts, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_service_account: gapic_v1.method.wrap_method( + self.get_service_account, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_service_account: gapic_v1.method.wrap_method( + self.create_service_account, + default_timeout=60.0, + client_info=client_info, + ), + self.update_service_account: gapic_v1.method.wrap_method( + self.update_service_account, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.patch_service_account: gapic_v1.method.wrap_method( + self.patch_service_account, + default_timeout=None, + client_info=client_info, + ), + self.delete_service_account: gapic_v1.method.wrap_method( + self.delete_service_account, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.undelete_service_account: gapic_v1.method.wrap_method( + self.undelete_service_account, + default_timeout=None, + client_info=client_info, + ), + self.enable_service_account: gapic_v1.method.wrap_method( + self.enable_service_account, + default_timeout=None, + client_info=client_info, + ), + self.disable_service_account: gapic_v1.method.wrap_method( + self.disable_service_account, + default_timeout=None, + client_info=client_info, + ), + self.list_service_account_keys: gapic_v1.method.wrap_method( + self.list_service_account_keys, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_service_account_key: gapic_v1.method.wrap_method( + self.get_service_account_key, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_service_account_key: gapic_v1.method.wrap_method( + self.create_service_account_key, + default_timeout=60.0, + client_info=client_info, + ), + self.upload_service_account_key: gapic_v1.method.wrap_method( + self.upload_service_account_key, + default_timeout=None, + client_info=client_info, + ), + self.delete_service_account_key: gapic_v1.method.wrap_method( + self.delete_service_account_key, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.disable_service_account_key: gapic_v1.method.wrap_method( + self.disable_service_account_key, + default_timeout=None, + client_info=client_info, + ), + self.enable_service_account_key: gapic_v1.method.wrap_method( + self.enable_service_account_key, + default_timeout=None, + client_info=client_info, + ), + self.sign_blob: gapic_v1.method.wrap_method( + self.sign_blob, + default_timeout=60.0, + client_info=client_info, + ), + self.sign_jwt: gapic_v1.method.wrap_method( + self.sign_jwt, + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=60.0, + client_info=client_info, + ), + self.query_grantable_roles: gapic_v1.method.wrap_method( + self.query_grantable_roles, + default_timeout=60.0, + client_info=client_info, + ), + self.list_roles: gapic_v1.method.wrap_method( + self.list_roles, + default_timeout=None, + client_info=client_info, + ), + self.get_role: gapic_v1.method.wrap_method( + self.get_role, + default_timeout=None, + client_info=client_info, + ), + self.create_role: gapic_v1.method.wrap_method( + self.create_role, + default_timeout=None, + client_info=client_info, + ), + self.update_role: gapic_v1.method.wrap_method( + self.update_role, + default_timeout=None, + client_info=client_info, + ), + self.delete_role: gapic_v1.method.wrap_method( + self.delete_role, + default_timeout=None, + client_info=client_info, + ), + self.undelete_role: gapic_v1.method.wrap_method( + self.undelete_role, + default_timeout=None, + client_info=client_info, + ), + self.query_testable_permissions: gapic_v1.method.wrap_method( + self.query_testable_permissions, + default_timeout=None, + client_info=client_info, + ), + self.query_auditable_services: gapic_v1.method.wrap_method( + self.query_auditable_services, + default_timeout=None, + client_info=client_info, + ), + self.lint_policy: gapic_v1.method.wrap_method( + self.lint_policy, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_service_accounts( + self, + ) -> Callable[ + [iam.ListServiceAccountsRequest], + Union[ + iam.ListServiceAccountsResponse, Awaitable[iam.ListServiceAccountsResponse] + ], + ]: + raise NotImplementedError() + + @property + def get_service_account( + self, + ) -> Callable[ + [iam.GetServiceAccountRequest], + Union[iam.ServiceAccount, Awaitable[iam.ServiceAccount]], + ]: + raise NotImplementedError() + + @property + def create_service_account( + self, + ) -> Callable[ + [iam.CreateServiceAccountRequest], + Union[iam.ServiceAccount, Awaitable[iam.ServiceAccount]], + ]: + raise NotImplementedError() + + @property + def update_service_account( + self, + ) -> Callable[ + [iam.ServiceAccount], Union[iam.ServiceAccount, Awaitable[iam.ServiceAccount]] + ]: + raise NotImplementedError() + + @property + def patch_service_account( + self, + ) -> Callable[ + [iam.PatchServiceAccountRequest], + Union[iam.ServiceAccount, Awaitable[iam.ServiceAccount]], + ]: + raise NotImplementedError() + + @property + def delete_service_account( + self, + ) -> Callable[ + [iam.DeleteServiceAccountRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def undelete_service_account( + self, + ) -> Callable[ + [iam.UndeleteServiceAccountRequest], + Union[ + iam.UndeleteServiceAccountResponse, + Awaitable[iam.UndeleteServiceAccountResponse], + ], + ]: + raise NotImplementedError() + + @property + def enable_service_account( + self, + ) -> Callable[ + [iam.EnableServiceAccountRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def disable_service_account( + self, + ) -> Callable[ + [iam.DisableServiceAccountRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_service_account_keys( + self, + ) -> Callable[ + [iam.ListServiceAccountKeysRequest], + Union[ + iam.ListServiceAccountKeysResponse, + Awaitable[iam.ListServiceAccountKeysResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_service_account_key( + self, + ) -> Callable[ + [iam.GetServiceAccountKeyRequest], + Union[iam.ServiceAccountKey, Awaitable[iam.ServiceAccountKey]], + ]: + raise NotImplementedError() + + @property + def create_service_account_key( + self, + ) -> Callable[ + [iam.CreateServiceAccountKeyRequest], + Union[iam.ServiceAccountKey, Awaitable[iam.ServiceAccountKey]], + ]: + raise NotImplementedError() + + @property + def upload_service_account_key( + self, + ) -> Callable[ + [iam.UploadServiceAccountKeyRequest], + Union[iam.ServiceAccountKey, Awaitable[iam.ServiceAccountKey]], + ]: + raise NotImplementedError() + + @property + def delete_service_account_key( + self, + ) -> Callable[ + [iam.DeleteServiceAccountKeyRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def disable_service_account_key( + self, + ) -> Callable[ + [iam.DisableServiceAccountKeyRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def enable_service_account_key( + self, + ) -> Callable[ + [iam.EnableServiceAccountKeyRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def sign_blob( + self, + ) -> Callable[ + [iam.SignBlobRequest], + Union[iam.SignBlobResponse, Awaitable[iam.SignBlobResponse]], + ]: + raise NotImplementedError() + + @property + def sign_jwt( + self, + ) -> Callable[ + [iam.SignJwtRequest], Union[iam.SignJwtResponse, Awaitable[iam.SignJwtResponse]] + ]: + 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 set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def query_grantable_roles( + self, + ) -> Callable[ + [iam.QueryGrantableRolesRequest], + Union[ + iam.QueryGrantableRolesResponse, Awaitable[iam.QueryGrantableRolesResponse] + ], + ]: + raise NotImplementedError() + + @property + def list_roles( + self, + ) -> Callable[ + [iam.ListRolesRequest], + Union[iam.ListRolesResponse, Awaitable[iam.ListRolesResponse]], + ]: + raise NotImplementedError() + + @property + def get_role( + self, + ) -> Callable[[iam.GetRoleRequest], Union[iam.Role, Awaitable[iam.Role]]]: + raise NotImplementedError() + + @property + def create_role( + self, + ) -> Callable[[iam.CreateRoleRequest], Union[iam.Role, Awaitable[iam.Role]]]: + raise NotImplementedError() + + @property + def update_role( + self, + ) -> Callable[[iam.UpdateRoleRequest], Union[iam.Role, Awaitable[iam.Role]]]: + raise NotImplementedError() + + @property + def delete_role( + self, + ) -> Callable[[iam.DeleteRoleRequest], Union[iam.Role, Awaitable[iam.Role]]]: + raise NotImplementedError() + + @property + def undelete_role( + self, + ) -> Callable[[iam.UndeleteRoleRequest], Union[iam.Role, Awaitable[iam.Role]]]: + raise NotImplementedError() + + @property + def query_testable_permissions( + self, + ) -> Callable[ + [iam.QueryTestablePermissionsRequest], + Union[ + iam.QueryTestablePermissionsResponse, + Awaitable[iam.QueryTestablePermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def query_auditable_services( + self, + ) -> Callable[ + [iam.QueryAuditableServicesRequest], + Union[ + iam.QueryAuditableServicesResponse, + Awaitable[iam.QueryAuditableServicesResponse], + ], + ]: + raise NotImplementedError() + + @property + def lint_policy( + self, + ) -> Callable[ + [iam.LintPolicyRequest], + Union[iam.LintPolicyResponse, Awaitable[iam.LintPolicyResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("IAMTransport",) diff --git a/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/transports/grpc.py b/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/transports/grpc.py new file mode 100644 index 000000000000..e9b12b0c2b5d --- /dev/null +++ b/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/transports/grpc.py @@ -0,0 +1,1234 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +import grpc # type: ignore + +from google.cloud.iam_admin_v1.types import iam + +from .base import DEFAULT_CLIENT_INFO, IAMTransport + + +class IAMGrpcTransport(IAMTransport): + """gRPC backend transport for IAM. + + Creates and manages Identity and Access Management (IAM) resources. + + You can use this service to work with all of the following + resources: + + - **Service accounts**, which identify an application or a virtual + machine (VM) instance rather than a person + - **Service account keys**, which service accounts use to + authenticate with Google APIs + - **IAM policies for service accounts**, which specify the roles + that a principal has for the service account + - **IAM custom roles**, which help you limit the number of + permissions that you grant to principals + + In addition, you can use this service to complete the following + tasks, among others: + + - Test whether a service account can use specific permissions + - Check which roles you can grant for a specific resource + - Lint, or validate, condition expressions in an IAM policy + + When you read data from the IAM API, each read is eventually + consistent. In other words, if you write data with the IAM API, then + immediately read that data, the read operation might return an older + version of the data. To deal with this behavior, your application + can retry the request with truncated exponential backoff. + + In contrast, writing data to the IAM API is sequentially consistent. + In other words, write operations are always processed in the order + in which they were received. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def list_service_accounts( + self, + ) -> Callable[[iam.ListServiceAccountsRequest], iam.ListServiceAccountsResponse]: + r"""Return a callable for the list service accounts method over gRPC. + + Lists every [ServiceAccount][google.iam.admin.v1.ServiceAccount] + that belongs to a specific project. + + Returns: + Callable[[~.ListServiceAccountsRequest], + ~.ListServiceAccountsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_service_accounts" not in self._stubs: + self._stubs["list_service_accounts"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/ListServiceAccounts", + request_serializer=iam.ListServiceAccountsRequest.serialize, + response_deserializer=iam.ListServiceAccountsResponse.deserialize, + ) + return self._stubs["list_service_accounts"] + + @property + def get_service_account( + self, + ) -> Callable[[iam.GetServiceAccountRequest], iam.ServiceAccount]: + r"""Return a callable for the get service account method over gRPC. + + Gets a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.GetServiceAccountRequest], + ~.ServiceAccount]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_service_account" not in self._stubs: + self._stubs["get_service_account"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/GetServiceAccount", + request_serializer=iam.GetServiceAccountRequest.serialize, + response_deserializer=iam.ServiceAccount.deserialize, + ) + return self._stubs["get_service_account"] + + @property + def create_service_account( + self, + ) -> Callable[[iam.CreateServiceAccountRequest], iam.ServiceAccount]: + r"""Return a callable for the create service account method over gRPC. + + Creates a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.CreateServiceAccountRequest], + ~.ServiceAccount]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_service_account" not in self._stubs: + self._stubs["create_service_account"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/CreateServiceAccount", + request_serializer=iam.CreateServiceAccountRequest.serialize, + response_deserializer=iam.ServiceAccount.deserialize, + ) + return self._stubs["create_service_account"] + + @property + def update_service_account( + self, + ) -> Callable[[iam.ServiceAccount], iam.ServiceAccount]: + r"""Return a callable for the update service account method over gRPC. + + **Note:** We are in the process of deprecating this method. Use + [PatchServiceAccount][google.iam.admin.v1.IAM.PatchServiceAccount] + instead. + + Updates a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + You can update only the ``display_name`` field. + + Returns: + Callable[[~.ServiceAccount], + ~.ServiceAccount]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_service_account" not in self._stubs: + self._stubs["update_service_account"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/UpdateServiceAccount", + request_serializer=iam.ServiceAccount.serialize, + response_deserializer=iam.ServiceAccount.deserialize, + ) + return self._stubs["update_service_account"] + + @property + def patch_service_account( + self, + ) -> Callable[[iam.PatchServiceAccountRequest], iam.ServiceAccount]: + r"""Return a callable for the patch service account method over gRPC. + + Patches a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.PatchServiceAccountRequest], + ~.ServiceAccount]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "patch_service_account" not in self._stubs: + self._stubs["patch_service_account"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/PatchServiceAccount", + request_serializer=iam.PatchServiceAccountRequest.serialize, + response_deserializer=iam.ServiceAccount.deserialize, + ) + return self._stubs["patch_service_account"] + + @property + def delete_service_account( + self, + ) -> Callable[[iam.DeleteServiceAccountRequest], empty_pb2.Empty]: + r"""Return a callable for the delete service account method over gRPC. + + Deletes a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + **Warning:** After you delete a service account, you might not + be able to undelete it. If you know that you need to re-enable + the service account in the future, use + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount] + instead. + + If you delete a service account, IAM permanently removes the + service account 30 days later. Google Cloud cannot recover the + service account after it is permanently removed, even if you + file a support request. + + To help avoid unplanned outages, we recommend that you disable + the service account before you delete it. Use + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount] + to disable the service account, then wait at least 24 hours and + watch for unintended consequences. If there are no unintended + consequences, you can delete the service account. + + Returns: + Callable[[~.DeleteServiceAccountRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_service_account" not in self._stubs: + self._stubs["delete_service_account"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/DeleteServiceAccount", + request_serializer=iam.DeleteServiceAccountRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_service_account"] + + @property + def undelete_service_account( + self, + ) -> Callable[ + [iam.UndeleteServiceAccountRequest], iam.UndeleteServiceAccountResponse + ]: + r"""Return a callable for the undelete service account method over gRPC. + + Restores a deleted + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + **Important:** It is not always possible to restore a deleted + service account. Use this method only as a last resort. + + After you delete a service account, IAM permanently removes the + service account 30 days later. There is no way to restore a + deleted service account that has been permanently removed. + + Returns: + Callable[[~.UndeleteServiceAccountRequest], + ~.UndeleteServiceAccountResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_service_account" not in self._stubs: + self._stubs["undelete_service_account"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/UndeleteServiceAccount", + request_serializer=iam.UndeleteServiceAccountRequest.serialize, + response_deserializer=iam.UndeleteServiceAccountResponse.deserialize, + ) + return self._stubs["undelete_service_account"] + + @property + def enable_service_account( + self, + ) -> Callable[[iam.EnableServiceAccountRequest], empty_pb2.Empty]: + r"""Return a callable for the enable service account method over gRPC. + + Enables a [ServiceAccount][google.iam.admin.v1.ServiceAccount] + that was disabled by + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount]. + + If the service account is already enabled, then this method has + no effect. + + If the service account was disabled by other means—for example, + if Google disabled the service account because it was + compromised—you cannot use this method to enable the service + account. + + Returns: + Callable[[~.EnableServiceAccountRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "enable_service_account" not in self._stubs: + self._stubs["enable_service_account"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/EnableServiceAccount", + request_serializer=iam.EnableServiceAccountRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["enable_service_account"] + + @property + def disable_service_account( + self, + ) -> Callable[[iam.DisableServiceAccountRequest], empty_pb2.Empty]: + r"""Return a callable for the disable service account method over gRPC. + + Disables a [ServiceAccount][google.iam.admin.v1.ServiceAccount] + immediately. + + If an application uses the service account to authenticate, that + application can no longer call Google APIs or access Google + Cloud resources. Existing access tokens for the service account + are rejected, and requests for new access tokens will fail. + + To re-enable the service account, use + [EnableServiceAccount][google.iam.admin.v1.IAM.EnableServiceAccount]. + After you re-enable the service account, its existing access + tokens will be accepted, and you can request new access tokens. + + To help avoid unplanned outages, we recommend that you disable + the service account before you delete it. Use this method to + disable the service account, then wait at least 24 hours and + watch for unintended consequences. If there are no unintended + consequences, you can delete the service account with + [DeleteServiceAccount][google.iam.admin.v1.IAM.DeleteServiceAccount]. + + Returns: + Callable[[~.DisableServiceAccountRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "disable_service_account" not in self._stubs: + self._stubs["disable_service_account"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/DisableServiceAccount", + request_serializer=iam.DisableServiceAccountRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["disable_service_account"] + + @property + def list_service_account_keys( + self, + ) -> Callable[ + [iam.ListServiceAccountKeysRequest], iam.ListServiceAccountKeysResponse + ]: + r"""Return a callable for the list service account keys method over gRPC. + + Lists every + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey] for a + service account. + + Returns: + Callable[[~.ListServiceAccountKeysRequest], + ~.ListServiceAccountKeysResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_service_account_keys" not in self._stubs: + self._stubs["list_service_account_keys"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/ListServiceAccountKeys", + request_serializer=iam.ListServiceAccountKeysRequest.serialize, + response_deserializer=iam.ListServiceAccountKeysResponse.deserialize, + ) + return self._stubs["list_service_account_keys"] + + @property + def get_service_account_key( + self, + ) -> Callable[[iam.GetServiceAccountKeyRequest], iam.ServiceAccountKey]: + r"""Return a callable for the get service account key method over gRPC. + + Gets a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + Returns: + Callable[[~.GetServiceAccountKeyRequest], + ~.ServiceAccountKey]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_service_account_key" not in self._stubs: + self._stubs["get_service_account_key"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/GetServiceAccountKey", + request_serializer=iam.GetServiceAccountKeyRequest.serialize, + response_deserializer=iam.ServiceAccountKey.deserialize, + ) + return self._stubs["get_service_account_key"] + + @property + def create_service_account_key( + self, + ) -> Callable[[iam.CreateServiceAccountKeyRequest], iam.ServiceAccountKey]: + r"""Return a callable for the create service account key method over gRPC. + + Creates a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + Returns: + Callable[[~.CreateServiceAccountKeyRequest], + ~.ServiceAccountKey]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_service_account_key" not in self._stubs: + self._stubs["create_service_account_key"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/CreateServiceAccountKey", + request_serializer=iam.CreateServiceAccountKeyRequest.serialize, + response_deserializer=iam.ServiceAccountKey.deserialize, + ) + return self._stubs["create_service_account_key"] + + @property + def upload_service_account_key( + self, + ) -> Callable[[iam.UploadServiceAccountKeyRequest], iam.ServiceAccountKey]: + r"""Return a callable for the upload service account key method over gRPC. + + Uploads the public key portion of a key pair that you manage, + and associates the public key with a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + After you upload the public key, you can use the private key + from the key pair as a service account key. + + Returns: + Callable[[~.UploadServiceAccountKeyRequest], + ~.ServiceAccountKey]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "upload_service_account_key" not in self._stubs: + self._stubs["upload_service_account_key"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/UploadServiceAccountKey", + request_serializer=iam.UploadServiceAccountKeyRequest.serialize, + response_deserializer=iam.ServiceAccountKey.deserialize, + ) + return self._stubs["upload_service_account_key"] + + @property + def delete_service_account_key( + self, + ) -> Callable[[iam.DeleteServiceAccountKeyRequest], empty_pb2.Empty]: + r"""Return a callable for the delete service account key method over gRPC. + + Deletes a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + Deleting a service account key does not revoke short-lived + credentials that have been issued based on the service account + key. + + Returns: + Callable[[~.DeleteServiceAccountKeyRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_service_account_key" not in self._stubs: + self._stubs["delete_service_account_key"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/DeleteServiceAccountKey", + request_serializer=iam.DeleteServiceAccountKeyRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_service_account_key"] + + @property + def disable_service_account_key( + self, + ) -> Callable[[iam.DisableServiceAccountKeyRequest], empty_pb2.Empty]: + r"""Return a callable for the disable service account key method over gRPC. + + Disable a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. A + disabled service account key can be re-enabled with + [EnableServiceAccountKey][google.iam.admin.v1.IAM.EnableServiceAccountKey]. + + Returns: + Callable[[~.DisableServiceAccountKeyRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "disable_service_account_key" not in self._stubs: + self._stubs["disable_service_account_key"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/DisableServiceAccountKey", + request_serializer=iam.DisableServiceAccountKeyRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["disable_service_account_key"] + + @property + def enable_service_account_key( + self, + ) -> Callable[[iam.EnableServiceAccountKeyRequest], empty_pb2.Empty]: + r"""Return a callable for the enable service account key method over gRPC. + + Enable a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + Returns: + Callable[[~.EnableServiceAccountKeyRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "enable_service_account_key" not in self._stubs: + self._stubs["enable_service_account_key"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/EnableServiceAccountKey", + request_serializer=iam.EnableServiceAccountKeyRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["enable_service_account_key"] + + @property + def sign_blob(self) -> Callable[[iam.SignBlobRequest], iam.SignBlobResponse]: + r"""Return a callable for the sign blob method over gRPC. + + **Note:** This method is deprecated. Use the + ```signBlob`` `__ + method in the IAM Service Account Credentials API instead. If + you currently use this method, see the `migration + guide `__ + for instructions. + + Signs a blob using the system-managed private key for a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.SignBlobRequest], + ~.SignBlobResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "sign_blob" not in self._stubs: + self._stubs["sign_blob"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/SignBlob", + request_serializer=iam.SignBlobRequest.serialize, + response_deserializer=iam.SignBlobResponse.deserialize, + ) + return self._stubs["sign_blob"] + + @property + def sign_jwt(self) -> Callable[[iam.SignJwtRequest], iam.SignJwtResponse]: + r"""Return a callable for the sign jwt method over gRPC. + + **Note:** This method is deprecated. Use the + ```signJwt`` `__ + method in the IAM Service Account Credentials API instead. If + you currently use this method, see the `migration + guide `__ + for instructions. + + Signs a JSON Web Token (JWT) using the system-managed private + key for a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.SignJwtRequest], + ~.SignJwtResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "sign_jwt" not in self._stubs: + self._stubs["sign_jwt"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/SignJwt", + request_serializer=iam.SignJwtRequest.serialize, + response_deserializer=iam.SignJwtResponse.deserialize, + ) + return self._stubs["sign_jwt"] + + @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 policy that is attached to a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. This IAM + policy specifies which principals have access to the service + account. + + This method does not tell you whether the service account has + been granted any roles on other resources. To check whether a + service account has role grants on a resource, use the + ``getIamPolicy`` method for that resource. For example, to view + the role grants for a project, call the Resource Manager API's + ```projects.getIamPolicy`` `__ + method. + + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @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 policy that is attached to a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Use this method to grant or revoke access to the service + account. For example, you could grant a principal the ability to + impersonate the service account. + + This method does not enable the service account to access other + resources. To grant roles to a service account on a resource, + follow these steps: + + 1. Call the resource's ``getIamPolicy`` method to get its + current IAM policy. + 2. Edit the policy so that it binds the service account to an + IAM role for the resource. + 3. Call the resource's ``setIamPolicy`` method to update its IAM + policy. + + For detailed instructions, see `Manage access to project, + folders, and + organizations `__ + or `Manage access to other + resources `__. + + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Tests whether the caller has the specified permissions on a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def query_grantable_roles( + self, + ) -> Callable[[iam.QueryGrantableRolesRequest], iam.QueryGrantableRolesResponse]: + r"""Return a callable for the query grantable roles method over gRPC. + + Lists roles that can be granted on a Google Cloud + resource. A role is grantable if the IAM policy for the + resource can contain bindings to the role. + + Returns: + Callable[[~.QueryGrantableRolesRequest], + ~.QueryGrantableRolesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "query_grantable_roles" not in self._stubs: + self._stubs["query_grantable_roles"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/QueryGrantableRoles", + request_serializer=iam.QueryGrantableRolesRequest.serialize, + response_deserializer=iam.QueryGrantableRolesResponse.deserialize, + ) + return self._stubs["query_grantable_roles"] + + @property + def list_roles(self) -> Callable[[iam.ListRolesRequest], iam.ListRolesResponse]: + r"""Return a callable for the list roles method over gRPC. + + Lists every predefined [Role][google.iam.admin.v1.Role] that IAM + supports, or every custom role that is defined for an + organization or project. + + Returns: + Callable[[~.ListRolesRequest], + ~.ListRolesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_roles" not in self._stubs: + self._stubs["list_roles"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/ListRoles", + request_serializer=iam.ListRolesRequest.serialize, + response_deserializer=iam.ListRolesResponse.deserialize, + ) + return self._stubs["list_roles"] + + @property + def get_role(self) -> Callable[[iam.GetRoleRequest], iam.Role]: + r"""Return a callable for the get role method over gRPC. + + Gets the definition of a [Role][google.iam.admin.v1.Role]. + + Returns: + Callable[[~.GetRoleRequest], + ~.Role]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_role" not in self._stubs: + self._stubs["get_role"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/GetRole", + request_serializer=iam.GetRoleRequest.serialize, + response_deserializer=iam.Role.deserialize, + ) + return self._stubs["get_role"] + + @property + def create_role(self) -> Callable[[iam.CreateRoleRequest], iam.Role]: + r"""Return a callable for the create role method over gRPC. + + Creates a new custom [Role][google.iam.admin.v1.Role]. + + Returns: + Callable[[~.CreateRoleRequest], + ~.Role]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_role" not in self._stubs: + self._stubs["create_role"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/CreateRole", + request_serializer=iam.CreateRoleRequest.serialize, + response_deserializer=iam.Role.deserialize, + ) + return self._stubs["create_role"] + + @property + def update_role(self) -> Callable[[iam.UpdateRoleRequest], iam.Role]: + r"""Return a callable for the update role method over gRPC. + + Updates the definition of a custom + [Role][google.iam.admin.v1.Role]. + + Returns: + Callable[[~.UpdateRoleRequest], + ~.Role]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_role" not in self._stubs: + self._stubs["update_role"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/UpdateRole", + request_serializer=iam.UpdateRoleRequest.serialize, + response_deserializer=iam.Role.deserialize, + ) + return self._stubs["update_role"] + + @property + def delete_role(self) -> Callable[[iam.DeleteRoleRequest], iam.Role]: + r"""Return a callable for the delete role method over gRPC. + + Deletes a custom [Role][google.iam.admin.v1.Role]. + + When you delete a custom role, the following changes occur + immediately: + + - You cannot bind a principal to the custom role in an IAM + [Policy][google.iam.v1.Policy]. + - Existing bindings to the custom role are not changed, but + they have no effect. + - By default, the response from + [ListRoles][google.iam.admin.v1.IAM.ListRoles] does not + include the custom role. + + You have 7 days to undelete the custom role. After 7 days, the + following changes occur: + + - The custom role is permanently deleted and cannot be + recovered. + - If an IAM policy contains a binding to the custom role, the + binding is permanently removed. + + Returns: + Callable[[~.DeleteRoleRequest], + ~.Role]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_role" not in self._stubs: + self._stubs["delete_role"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/DeleteRole", + request_serializer=iam.DeleteRoleRequest.serialize, + response_deserializer=iam.Role.deserialize, + ) + return self._stubs["delete_role"] + + @property + def undelete_role(self) -> Callable[[iam.UndeleteRoleRequest], iam.Role]: + r"""Return a callable for the undelete role method over gRPC. + + Undeletes a custom [Role][google.iam.admin.v1.Role]. + + Returns: + Callable[[~.UndeleteRoleRequest], + ~.Role]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_role" not in self._stubs: + self._stubs["undelete_role"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/UndeleteRole", + request_serializer=iam.UndeleteRoleRequest.serialize, + response_deserializer=iam.Role.deserialize, + ) + return self._stubs["undelete_role"] + + @property + def query_testable_permissions( + self, + ) -> Callable[ + [iam.QueryTestablePermissionsRequest], iam.QueryTestablePermissionsResponse + ]: + r"""Return a callable for the query testable permissions method over gRPC. + + Lists every permission that you can test on a + resource. A permission is testable if you can check + whether a principal has that permission on the resource. + + Returns: + Callable[[~.QueryTestablePermissionsRequest], + ~.QueryTestablePermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "query_testable_permissions" not in self._stubs: + self._stubs["query_testable_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/QueryTestablePermissions", + request_serializer=iam.QueryTestablePermissionsRequest.serialize, + response_deserializer=iam.QueryTestablePermissionsResponse.deserialize, + ) + return self._stubs["query_testable_permissions"] + + @property + def query_auditable_services( + self, + ) -> Callable[ + [iam.QueryAuditableServicesRequest], iam.QueryAuditableServicesResponse + ]: + r"""Return a callable for the query auditable services method over gRPC. + + Returns a list of services that allow you to opt into audit logs + that are not generated by default. + + To learn more about audit logs, see the `Logging + documentation `__. + + Returns: + Callable[[~.QueryAuditableServicesRequest], + ~.QueryAuditableServicesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "query_auditable_services" not in self._stubs: + self._stubs["query_auditable_services"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/QueryAuditableServices", + request_serializer=iam.QueryAuditableServicesRequest.serialize, + response_deserializer=iam.QueryAuditableServicesResponse.deserialize, + ) + return self._stubs["query_auditable_services"] + + @property + def lint_policy(self) -> Callable[[iam.LintPolicyRequest], iam.LintPolicyResponse]: + r"""Return a callable for the lint policy method over gRPC. + + Lints, or validates, an IAM policy. Currently checks the + [google.iam.v1.Binding.condition][google.iam.v1.Binding.condition] + field, which contains a condition expression for a role binding. + + Successful calls to this method always return an HTTP ``200 OK`` + status code, even if the linter detects an issue in the IAM + policy. + + Returns: + Callable[[~.LintPolicyRequest], + ~.LintPolicyResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "lint_policy" not in self._stubs: + self._stubs["lint_policy"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/LintPolicy", + request_serializer=iam.LintPolicyRequest.serialize, + response_deserializer=iam.LintPolicyResponse.deserialize, + ) + return self._stubs["lint_policy"] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("IAMGrpcTransport",) diff --git a/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/transports/grpc_asyncio.py b/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/transports/grpc_asyncio.py new file mode 100644 index 000000000000..e8e10a66b737 --- /dev/null +++ b/packages/google-cloud-iam/google/cloud/iam_admin_v1/services/iam/transports/grpc_asyncio.py @@ -0,0 +1,1253 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers_async +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 +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.iam_admin_v1.types import iam + +from .base import DEFAULT_CLIENT_INFO, IAMTransport +from .grpc import IAMGrpcTransport + + +class IAMGrpcAsyncIOTransport(IAMTransport): + """gRPC AsyncIO backend transport for IAM. + + Creates and manages Identity and Access Management (IAM) resources. + + You can use this service to work with all of the following + resources: + + - **Service accounts**, which identify an application or a virtual + machine (VM) instance rather than a person + - **Service account keys**, which service accounts use to + authenticate with Google APIs + - **IAM policies for service accounts**, which specify the roles + that a principal has for the service account + - **IAM custom roles**, which help you limit the number of + permissions that you grant to principals + + In addition, you can use this service to complete the following + tasks, among others: + + - Test whether a service account can use specific permissions + - Check which roles you can grant for a specific resource + - Lint, or validate, condition expressions in an IAM policy + + When you read data from the IAM API, each read is eventually + consistent. In other words, if you write data with the IAM API, then + immediately read that data, the read operation might return an older + version of the data. To deal with this behavior, your application + can retry the request with truncated exponential backoff. + + In contrast, writing data to the IAM API is sequentially consistent. + In other words, write operations are always processed in the order + in which they were received. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call 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 = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (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 = "iam.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'iam.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional 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[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_service_accounts( + self, + ) -> Callable[ + [iam.ListServiceAccountsRequest], Awaitable[iam.ListServiceAccountsResponse] + ]: + r"""Return a callable for the list service accounts method over gRPC. + + Lists every [ServiceAccount][google.iam.admin.v1.ServiceAccount] + that belongs to a specific project. + + Returns: + Callable[[~.ListServiceAccountsRequest], + Awaitable[~.ListServiceAccountsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_service_accounts" not in self._stubs: + self._stubs["list_service_accounts"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/ListServiceAccounts", + request_serializer=iam.ListServiceAccountsRequest.serialize, + response_deserializer=iam.ListServiceAccountsResponse.deserialize, + ) + return self._stubs["list_service_accounts"] + + @property + def get_service_account( + self, + ) -> Callable[[iam.GetServiceAccountRequest], Awaitable[iam.ServiceAccount]]: + r"""Return a callable for the get service account method over gRPC. + + Gets a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.GetServiceAccountRequest], + Awaitable[~.ServiceAccount]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_service_account" not in self._stubs: + self._stubs["get_service_account"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/GetServiceAccount", + request_serializer=iam.GetServiceAccountRequest.serialize, + response_deserializer=iam.ServiceAccount.deserialize, + ) + return self._stubs["get_service_account"] + + @property + def create_service_account( + self, + ) -> Callable[[iam.CreateServiceAccountRequest], Awaitable[iam.ServiceAccount]]: + r"""Return a callable for the create service account method over gRPC. + + Creates a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.CreateServiceAccountRequest], + Awaitable[~.ServiceAccount]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_service_account" not in self._stubs: + self._stubs["create_service_account"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/CreateServiceAccount", + request_serializer=iam.CreateServiceAccountRequest.serialize, + response_deserializer=iam.ServiceAccount.deserialize, + ) + return self._stubs["create_service_account"] + + @property + def update_service_account( + self, + ) -> Callable[[iam.ServiceAccount], Awaitable[iam.ServiceAccount]]: + r"""Return a callable for the update service account method over gRPC. + + **Note:** We are in the process of deprecating this method. Use + [PatchServiceAccount][google.iam.admin.v1.IAM.PatchServiceAccount] + instead. + + Updates a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + You can update only the ``display_name`` field. + + Returns: + Callable[[~.ServiceAccount], + Awaitable[~.ServiceAccount]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_service_account" not in self._stubs: + self._stubs["update_service_account"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/UpdateServiceAccount", + request_serializer=iam.ServiceAccount.serialize, + response_deserializer=iam.ServiceAccount.deserialize, + ) + return self._stubs["update_service_account"] + + @property + def patch_service_account( + self, + ) -> Callable[[iam.PatchServiceAccountRequest], Awaitable[iam.ServiceAccount]]: + r"""Return a callable for the patch service account method over gRPC. + + Patches a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.PatchServiceAccountRequest], + Awaitable[~.ServiceAccount]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "patch_service_account" not in self._stubs: + self._stubs["patch_service_account"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/PatchServiceAccount", + request_serializer=iam.PatchServiceAccountRequest.serialize, + response_deserializer=iam.ServiceAccount.deserialize, + ) + return self._stubs["patch_service_account"] + + @property + def delete_service_account( + self, + ) -> Callable[[iam.DeleteServiceAccountRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete service account method over gRPC. + + Deletes a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + **Warning:** After you delete a service account, you might not + be able to undelete it. If you know that you need to re-enable + the service account in the future, use + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount] + instead. + + If you delete a service account, IAM permanently removes the + service account 30 days later. Google Cloud cannot recover the + service account after it is permanently removed, even if you + file a support request. + + To help avoid unplanned outages, we recommend that you disable + the service account before you delete it. Use + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount] + to disable the service account, then wait at least 24 hours and + watch for unintended consequences. If there are no unintended + consequences, you can delete the service account. + + Returns: + Callable[[~.DeleteServiceAccountRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_service_account" not in self._stubs: + self._stubs["delete_service_account"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/DeleteServiceAccount", + request_serializer=iam.DeleteServiceAccountRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_service_account"] + + @property + def undelete_service_account( + self, + ) -> Callable[ + [iam.UndeleteServiceAccountRequest], + Awaitable[iam.UndeleteServiceAccountResponse], + ]: + r"""Return a callable for the undelete service account method over gRPC. + + Restores a deleted + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + **Important:** It is not always possible to restore a deleted + service account. Use this method only as a last resort. + + After you delete a service account, IAM permanently removes the + service account 30 days later. There is no way to restore a + deleted service account that has been permanently removed. + + Returns: + Callable[[~.UndeleteServiceAccountRequest], + Awaitable[~.UndeleteServiceAccountResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_service_account" not in self._stubs: + self._stubs["undelete_service_account"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/UndeleteServiceAccount", + request_serializer=iam.UndeleteServiceAccountRequest.serialize, + response_deserializer=iam.UndeleteServiceAccountResponse.deserialize, + ) + return self._stubs["undelete_service_account"] + + @property + def enable_service_account( + self, + ) -> Callable[[iam.EnableServiceAccountRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the enable service account method over gRPC. + + Enables a [ServiceAccount][google.iam.admin.v1.ServiceAccount] + that was disabled by + [DisableServiceAccount][google.iam.admin.v1.IAM.DisableServiceAccount]. + + If the service account is already enabled, then this method has + no effect. + + If the service account was disabled by other means—for example, + if Google disabled the service account because it was + compromised—you cannot use this method to enable the service + account. + + Returns: + Callable[[~.EnableServiceAccountRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "enable_service_account" not in self._stubs: + self._stubs["enable_service_account"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/EnableServiceAccount", + request_serializer=iam.EnableServiceAccountRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["enable_service_account"] + + @property + def disable_service_account( + self, + ) -> Callable[[iam.DisableServiceAccountRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the disable service account method over gRPC. + + Disables a [ServiceAccount][google.iam.admin.v1.ServiceAccount] + immediately. + + If an application uses the service account to authenticate, that + application can no longer call Google APIs or access Google + Cloud resources. Existing access tokens for the service account + are rejected, and requests for new access tokens will fail. + + To re-enable the service account, use + [EnableServiceAccount][google.iam.admin.v1.IAM.EnableServiceAccount]. + After you re-enable the service account, its existing access + tokens will be accepted, and you can request new access tokens. + + To help avoid unplanned outages, we recommend that you disable + the service account before you delete it. Use this method to + disable the service account, then wait at least 24 hours and + watch for unintended consequences. If there are no unintended + consequences, you can delete the service account with + [DeleteServiceAccount][google.iam.admin.v1.IAM.DeleteServiceAccount]. + + Returns: + Callable[[~.DisableServiceAccountRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "disable_service_account" not in self._stubs: + self._stubs["disable_service_account"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/DisableServiceAccount", + request_serializer=iam.DisableServiceAccountRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["disable_service_account"] + + @property + def list_service_account_keys( + self, + ) -> Callable[ + [iam.ListServiceAccountKeysRequest], + Awaitable[iam.ListServiceAccountKeysResponse], + ]: + r"""Return a callable for the list service account keys method over gRPC. + + Lists every + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey] for a + service account. + + Returns: + Callable[[~.ListServiceAccountKeysRequest], + Awaitable[~.ListServiceAccountKeysResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_service_account_keys" not in self._stubs: + self._stubs["list_service_account_keys"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/ListServiceAccountKeys", + request_serializer=iam.ListServiceAccountKeysRequest.serialize, + response_deserializer=iam.ListServiceAccountKeysResponse.deserialize, + ) + return self._stubs["list_service_account_keys"] + + @property + def get_service_account_key( + self, + ) -> Callable[[iam.GetServiceAccountKeyRequest], Awaitable[iam.ServiceAccountKey]]: + r"""Return a callable for the get service account key method over gRPC. + + Gets a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + Returns: + Callable[[~.GetServiceAccountKeyRequest], + Awaitable[~.ServiceAccountKey]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_service_account_key" not in self._stubs: + self._stubs["get_service_account_key"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/GetServiceAccountKey", + request_serializer=iam.GetServiceAccountKeyRequest.serialize, + response_deserializer=iam.ServiceAccountKey.deserialize, + ) + return self._stubs["get_service_account_key"] + + @property + def create_service_account_key( + self, + ) -> Callable[ + [iam.CreateServiceAccountKeyRequest], Awaitable[iam.ServiceAccountKey] + ]: + r"""Return a callable for the create service account key method over gRPC. + + Creates a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + Returns: + Callable[[~.CreateServiceAccountKeyRequest], + Awaitable[~.ServiceAccountKey]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_service_account_key" not in self._stubs: + self._stubs["create_service_account_key"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/CreateServiceAccountKey", + request_serializer=iam.CreateServiceAccountKeyRequest.serialize, + response_deserializer=iam.ServiceAccountKey.deserialize, + ) + return self._stubs["create_service_account_key"] + + @property + def upload_service_account_key( + self, + ) -> Callable[ + [iam.UploadServiceAccountKeyRequest], Awaitable[iam.ServiceAccountKey] + ]: + r"""Return a callable for the upload service account key method over gRPC. + + Uploads the public key portion of a key pair that you manage, + and associates the public key with a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + After you upload the public key, you can use the private key + from the key pair as a service account key. + + Returns: + Callable[[~.UploadServiceAccountKeyRequest], + Awaitable[~.ServiceAccountKey]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "upload_service_account_key" not in self._stubs: + self._stubs["upload_service_account_key"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/UploadServiceAccountKey", + request_serializer=iam.UploadServiceAccountKeyRequest.serialize, + response_deserializer=iam.ServiceAccountKey.deserialize, + ) + return self._stubs["upload_service_account_key"] + + @property + def delete_service_account_key( + self, + ) -> Callable[[iam.DeleteServiceAccountKeyRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete service account key method over gRPC. + + Deletes a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + Deleting a service account key does not revoke short-lived + credentials that have been issued based on the service account + key. + + Returns: + Callable[[~.DeleteServiceAccountKeyRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_service_account_key" not in self._stubs: + self._stubs["delete_service_account_key"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/DeleteServiceAccountKey", + request_serializer=iam.DeleteServiceAccountKeyRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_service_account_key"] + + @property + def disable_service_account_key( + self, + ) -> Callable[[iam.DisableServiceAccountKeyRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the disable service account key method over gRPC. + + Disable a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. A + disabled service account key can be re-enabled with + [EnableServiceAccountKey][google.iam.admin.v1.IAM.EnableServiceAccountKey]. + + Returns: + Callable[[~.DisableServiceAccountKeyRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "disable_service_account_key" not in self._stubs: + self._stubs["disable_service_account_key"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/DisableServiceAccountKey", + request_serializer=iam.DisableServiceAccountKeyRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["disable_service_account_key"] + + @property + def enable_service_account_key( + self, + ) -> Callable[[iam.EnableServiceAccountKeyRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the enable service account key method over gRPC. + + Enable a + [ServiceAccountKey][google.iam.admin.v1.ServiceAccountKey]. + + Returns: + Callable[[~.EnableServiceAccountKeyRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "enable_service_account_key" not in self._stubs: + self._stubs["enable_service_account_key"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/EnableServiceAccountKey", + request_serializer=iam.EnableServiceAccountKeyRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["enable_service_account_key"] + + @property + def sign_blob( + self, + ) -> Callable[[iam.SignBlobRequest], Awaitable[iam.SignBlobResponse]]: + r"""Return a callable for the sign blob method over gRPC. + + **Note:** This method is deprecated. Use the + ```signBlob`` `__ + method in the IAM Service Account Credentials API instead. If + you currently use this method, see the `migration + guide `__ + for instructions. + + Signs a blob using the system-managed private key for a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.SignBlobRequest], + Awaitable[~.SignBlobResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "sign_blob" not in self._stubs: + self._stubs["sign_blob"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/SignBlob", + request_serializer=iam.SignBlobRequest.serialize, + response_deserializer=iam.SignBlobResponse.deserialize, + ) + return self._stubs["sign_blob"] + + @property + def sign_jwt( + self, + ) -> Callable[[iam.SignJwtRequest], Awaitable[iam.SignJwtResponse]]: + r"""Return a callable for the sign jwt method over gRPC. + + **Note:** This method is deprecated. Use the + ```signJwt`` `__ + method in the IAM Service Account Credentials API instead. If + you currently use this method, see the `migration + guide `__ + for instructions. + + Signs a JSON Web Token (JWT) using the system-managed private + key for a [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.SignJwtRequest], + Awaitable[~.SignJwtResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "sign_jwt" not in self._stubs: + self._stubs["sign_jwt"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/SignJwt", + request_serializer=iam.SignJwtRequest.serialize, + response_deserializer=iam.SignJwtResponse.deserialize, + ) + return self._stubs["sign_jwt"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the IAM policy that is attached to a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. This IAM + policy specifies which principals have access to the service + account. + + This method does not tell you whether the service account has + been granted any roles on other resources. To check whether a + service account has role grants on a resource, use the + ``getIamPolicy`` method for that resource. For example, to view + the role grants for a project, call the Resource Manager API's + ```projects.getIamPolicy`` `__ + method. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the IAM policy that is attached to a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Use this method to grant or revoke access to the service + account. For example, you could grant a principal the ability to + impersonate the service account. + + This method does not enable the service account to access other + resources. To grant roles to a service account on a resource, + follow these steps: + + 1. Call the resource's ``getIamPolicy`` method to get its + current IAM policy. + 2. Edit the policy so that it binds the service account to an + IAM role for the resource. + 3. Call the resource's ``setIamPolicy`` method to update its IAM + policy. + + For detailed instructions, see `Manage access to project, + folders, and + organizations `__ + or `Manage access to other + resources `__. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Tests whether the caller has the specified permissions on a + [ServiceAccount][google.iam.admin.v1.ServiceAccount]. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def query_grantable_roles( + self, + ) -> Callable[ + [iam.QueryGrantableRolesRequest], Awaitable[iam.QueryGrantableRolesResponse] + ]: + r"""Return a callable for the query grantable roles method over gRPC. + + Lists roles that can be granted on a Google Cloud + resource. A role is grantable if the IAM policy for the + resource can contain bindings to the role. + + Returns: + Callable[[~.QueryGrantableRolesRequest], + Awaitable[~.QueryGrantableRolesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "query_grantable_roles" not in self._stubs: + self._stubs["query_grantable_roles"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/QueryGrantableRoles", + request_serializer=iam.QueryGrantableRolesRequest.serialize, + response_deserializer=iam.QueryGrantableRolesResponse.deserialize, + ) + return self._stubs["query_grantable_roles"] + + @property + def list_roles( + self, + ) -> Callable[[iam.ListRolesRequest], Awaitable[iam.ListRolesResponse]]: + r"""Return a callable for the list roles method over gRPC. + + Lists every predefined [Role][google.iam.admin.v1.Role] that IAM + supports, or every custom role that is defined for an + organization or project. + + Returns: + Callable[[~.ListRolesRequest], + Awaitable[~.ListRolesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_roles" not in self._stubs: + self._stubs["list_roles"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/ListRoles", + request_serializer=iam.ListRolesRequest.serialize, + response_deserializer=iam.ListRolesResponse.deserialize, + ) + return self._stubs["list_roles"] + + @property + def get_role(self) -> Callable[[iam.GetRoleRequest], Awaitable[iam.Role]]: + r"""Return a callable for the get role method over gRPC. + + Gets the definition of a [Role][google.iam.admin.v1.Role]. + + Returns: + Callable[[~.GetRoleRequest], + Awaitable[~.Role]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_role" not in self._stubs: + self._stubs["get_role"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/GetRole", + request_serializer=iam.GetRoleRequest.serialize, + response_deserializer=iam.Role.deserialize, + ) + return self._stubs["get_role"] + + @property + def create_role(self) -> Callable[[iam.CreateRoleRequest], Awaitable[iam.Role]]: + r"""Return a callable for the create role method over gRPC. + + Creates a new custom [Role][google.iam.admin.v1.Role]. + + Returns: + Callable[[~.CreateRoleRequest], + Awaitable[~.Role]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_role" not in self._stubs: + self._stubs["create_role"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/CreateRole", + request_serializer=iam.CreateRoleRequest.serialize, + response_deserializer=iam.Role.deserialize, + ) + return self._stubs["create_role"] + + @property + def update_role(self) -> Callable[[iam.UpdateRoleRequest], Awaitable[iam.Role]]: + r"""Return a callable for the update role method over gRPC. + + Updates the definition of a custom + [Role][google.iam.admin.v1.Role]. + + Returns: + Callable[[~.UpdateRoleRequest], + Awaitable[~.Role]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_role" not in self._stubs: + self._stubs["update_role"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/UpdateRole", + request_serializer=iam.UpdateRoleRequest.serialize, + response_deserializer=iam.Role.deserialize, + ) + return self._stubs["update_role"] + + @property + def delete_role(self) -> Callable[[iam.DeleteRoleRequest], Awaitable[iam.Role]]: + r"""Return a callable for the delete role method over gRPC. + + Deletes a custom [Role][google.iam.admin.v1.Role]. + + When you delete a custom role, the following changes occur + immediately: + + - You cannot bind a principal to the custom role in an IAM + [Policy][google.iam.v1.Policy]. + - Existing bindings to the custom role are not changed, but + they have no effect. + - By default, the response from + [ListRoles][google.iam.admin.v1.IAM.ListRoles] does not + include the custom role. + + You have 7 days to undelete the custom role. After 7 days, the + following changes occur: + + - The custom role is permanently deleted and cannot be + recovered. + - If an IAM policy contains a binding to the custom role, the + binding is permanently removed. + + Returns: + Callable[[~.DeleteRoleRequest], + Awaitable[~.Role]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_role" not in self._stubs: + self._stubs["delete_role"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/DeleteRole", + request_serializer=iam.DeleteRoleRequest.serialize, + response_deserializer=iam.Role.deserialize, + ) + return self._stubs["delete_role"] + + @property + def undelete_role(self) -> Callable[[iam.UndeleteRoleRequest], Awaitable[iam.Role]]: + r"""Return a callable for the undelete role method over gRPC. + + Undeletes a custom [Role][google.iam.admin.v1.Role]. + + Returns: + Callable[[~.UndeleteRoleRequest], + Awaitable[~.Role]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_role" not in self._stubs: + self._stubs["undelete_role"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/UndeleteRole", + request_serializer=iam.UndeleteRoleRequest.serialize, + response_deserializer=iam.Role.deserialize, + ) + return self._stubs["undelete_role"] + + @property + def query_testable_permissions( + self, + ) -> Callable[ + [iam.QueryTestablePermissionsRequest], + Awaitable[iam.QueryTestablePermissionsResponse], + ]: + r"""Return a callable for the query testable permissions method over gRPC. + + Lists every permission that you can test on a + resource. A permission is testable if you can check + whether a principal has that permission on the resource. + + Returns: + Callable[[~.QueryTestablePermissionsRequest], + Awaitable[~.QueryTestablePermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "query_testable_permissions" not in self._stubs: + self._stubs["query_testable_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/QueryTestablePermissions", + request_serializer=iam.QueryTestablePermissionsRequest.serialize, + response_deserializer=iam.QueryTestablePermissionsResponse.deserialize, + ) + return self._stubs["query_testable_permissions"] + + @property + def query_auditable_services( + self, + ) -> Callable[ + [iam.QueryAuditableServicesRequest], + Awaitable[iam.QueryAuditableServicesResponse], + ]: + r"""Return a callable for the query auditable services method over gRPC. + + Returns a list of services that allow you to opt into audit logs + that are not generated by default. + + To learn more about audit logs, see the `Logging + documentation `__. + + Returns: + Callable[[~.QueryAuditableServicesRequest], + Awaitable[~.QueryAuditableServicesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "query_auditable_services" not in self._stubs: + self._stubs["query_auditable_services"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/QueryAuditableServices", + request_serializer=iam.QueryAuditableServicesRequest.serialize, + response_deserializer=iam.QueryAuditableServicesResponse.deserialize, + ) + return self._stubs["query_auditable_services"] + + @property + def lint_policy( + self, + ) -> Callable[[iam.LintPolicyRequest], Awaitable[iam.LintPolicyResponse]]: + r"""Return a callable for the lint policy method over gRPC. + + Lints, or validates, an IAM policy. Currently checks the + [google.iam.v1.Binding.condition][google.iam.v1.Binding.condition] + field, which contains a condition expression for a role binding. + + Successful calls to this method always return an HTTP ``200 OK`` + status code, even if the linter detects an issue in the IAM + policy. + + Returns: + Callable[[~.LintPolicyRequest], + Awaitable[~.LintPolicyResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "lint_policy" not in self._stubs: + self._stubs["lint_policy"] = self.grpc_channel.unary_unary( + "/google.iam.admin.v1.IAM/LintPolicy", + request_serializer=iam.LintPolicyRequest.serialize, + response_deserializer=iam.LintPolicyResponse.deserialize, + ) + return self._stubs["lint_policy"] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ("IAMGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-iam/google/cloud/iam_admin_v1/types/__init__.py b/packages/google-cloud-iam/google/cloud/iam_admin_v1/types/__init__.py new file mode 100644 index 000000000000..dcba9708ffa2 --- /dev/null +++ b/packages/google-cloud-iam/google/cloud/iam_admin_v1/types/__init__.py @@ -0,0 +1,116 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .audit_data import AuditData +from .iam import ( + CreateRoleRequest, + CreateServiceAccountKeyRequest, + CreateServiceAccountRequest, + DeleteRoleRequest, + DeleteServiceAccountKeyRequest, + DeleteServiceAccountRequest, + DisableServiceAccountKeyRequest, + DisableServiceAccountRequest, + EnableServiceAccountKeyRequest, + EnableServiceAccountRequest, + GetRoleRequest, + GetServiceAccountKeyRequest, + GetServiceAccountRequest, + LintPolicyRequest, + LintPolicyResponse, + LintResult, + ListRolesRequest, + ListRolesResponse, + ListServiceAccountKeysRequest, + ListServiceAccountKeysResponse, + ListServiceAccountsRequest, + ListServiceAccountsResponse, + PatchServiceAccountRequest, + Permission, + QueryAuditableServicesRequest, + QueryAuditableServicesResponse, + QueryGrantableRolesRequest, + QueryGrantableRolesResponse, + QueryTestablePermissionsRequest, + QueryTestablePermissionsResponse, + Role, + RoleView, + ServiceAccount, + ServiceAccountKey, + ServiceAccountKeyAlgorithm, + ServiceAccountKeyOrigin, + ServiceAccountPrivateKeyType, + ServiceAccountPublicKeyType, + SignBlobRequest, + SignBlobResponse, + SignJwtRequest, + SignJwtResponse, + UndeleteRoleRequest, + UndeleteServiceAccountRequest, + UndeleteServiceAccountResponse, + UpdateRoleRequest, + UploadServiceAccountKeyRequest, +) + +__all__ = ( + "AuditData", + "CreateRoleRequest", + "CreateServiceAccountKeyRequest", + "CreateServiceAccountRequest", + "DeleteRoleRequest", + "DeleteServiceAccountKeyRequest", + "DeleteServiceAccountRequest", + "DisableServiceAccountKeyRequest", + "DisableServiceAccountRequest", + "EnableServiceAccountKeyRequest", + "EnableServiceAccountRequest", + "GetRoleRequest", + "GetServiceAccountKeyRequest", + "GetServiceAccountRequest", + "LintPolicyRequest", + "LintPolicyResponse", + "LintResult", + "ListRolesRequest", + "ListRolesResponse", + "ListServiceAccountKeysRequest", + "ListServiceAccountKeysResponse", + "ListServiceAccountsRequest", + "ListServiceAccountsResponse", + "PatchServiceAccountRequest", + "Permission", + "QueryAuditableServicesRequest", + "QueryAuditableServicesResponse", + "QueryGrantableRolesRequest", + "QueryGrantableRolesResponse", + "QueryTestablePermissionsRequest", + "QueryTestablePermissionsResponse", + "Role", + "ServiceAccount", + "ServiceAccountKey", + "SignBlobRequest", + "SignBlobResponse", + "SignJwtRequest", + "SignJwtResponse", + "UndeleteRoleRequest", + "UndeleteServiceAccountRequest", + "UndeleteServiceAccountResponse", + "UpdateRoleRequest", + "UploadServiceAccountKeyRequest", + "RoleView", + "ServiceAccountKeyAlgorithm", + "ServiceAccountKeyOrigin", + "ServiceAccountPrivateKeyType", + "ServiceAccountPublicKeyType", +) diff --git a/packages/google-cloud-iam/google/cloud/iam_admin_v1/types/audit_data.py b/packages/google-cloud-iam/google/cloud/iam_admin_v1/types/audit_data.py new file mode 100644 index 000000000000..96c4a278f7f0 --- /dev/null +++ b/packages/google-cloud-iam/google/cloud/iam_admin_v1/types/audit_data.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.iam.admin.v1", + manifest={ + "AuditData", + }, +) + + +class AuditData(proto.Message): + r"""Audit log information specific to Cloud IAM admin APIs. This message + is serialized as an ``Any`` type in the ``ServiceData`` message of + an ``AuditLog`` message. + + Attributes: + permission_delta (google.cloud.iam_admin_v1.types.AuditData.PermissionDelta): + The permission_delta when when creating or updating a Role. + """ + + class PermissionDelta(proto.Message): + r"""A PermissionDelta message to record the added_permissions and + removed_permissions inside a role. + + Attributes: + added_permissions (MutableSequence[str]): + Added permissions. + removed_permissions (MutableSequence[str]): + Removed permissions. + """ + + added_permissions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + removed_permissions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + permission_delta: PermissionDelta = proto.Field( + proto.MESSAGE, + number=1, + message=PermissionDelta, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-iam/google/cloud/iam_admin_v1/types/iam.py b/packages/google-cloud-iam/google/cloud/iam_admin_v1/types/iam.py new file mode 100644 index 000000000000..a0a255926696 --- /dev/null +++ b/packages/google-cloud-iam/google/cloud/iam_admin_v1/types/iam.py @@ -0,0 +1,1891 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.iam.admin.v1", + manifest={ + "ServiceAccountKeyAlgorithm", + "ServiceAccountPrivateKeyType", + "ServiceAccountPublicKeyType", + "ServiceAccountKeyOrigin", + "RoleView", + "ServiceAccount", + "CreateServiceAccountRequest", + "ListServiceAccountsRequest", + "ListServiceAccountsResponse", + "GetServiceAccountRequest", + "DeleteServiceAccountRequest", + "PatchServiceAccountRequest", + "UndeleteServiceAccountRequest", + "UndeleteServiceAccountResponse", + "EnableServiceAccountRequest", + "DisableServiceAccountRequest", + "ListServiceAccountKeysRequest", + "ListServiceAccountKeysResponse", + "GetServiceAccountKeyRequest", + "ServiceAccountKey", + "CreateServiceAccountKeyRequest", + "UploadServiceAccountKeyRequest", + "DeleteServiceAccountKeyRequest", + "DisableServiceAccountKeyRequest", + "EnableServiceAccountKeyRequest", + "SignBlobRequest", + "SignBlobResponse", + "SignJwtRequest", + "SignJwtResponse", + "Role", + "QueryGrantableRolesRequest", + "QueryGrantableRolesResponse", + "ListRolesRequest", + "ListRolesResponse", + "GetRoleRequest", + "CreateRoleRequest", + "UpdateRoleRequest", + "DeleteRoleRequest", + "UndeleteRoleRequest", + "Permission", + "QueryTestablePermissionsRequest", + "QueryTestablePermissionsResponse", + "QueryAuditableServicesRequest", + "QueryAuditableServicesResponse", + "LintPolicyRequest", + "LintResult", + "LintPolicyResponse", + }, +) + + +class ServiceAccountKeyAlgorithm(proto.Enum): + r"""Supported key algorithms. + + Values: + KEY_ALG_UNSPECIFIED (0): + An unspecified key algorithm. + KEY_ALG_RSA_1024 (1): + 1k RSA Key. + KEY_ALG_RSA_2048 (2): + 2k RSA Key. + """ + KEY_ALG_UNSPECIFIED = 0 + KEY_ALG_RSA_1024 = 1 + KEY_ALG_RSA_2048 = 2 + + +class ServiceAccountPrivateKeyType(proto.Enum): + r"""Supported private key output formats. + + Values: + TYPE_UNSPECIFIED (0): + Unspecified. Equivalent to ``TYPE_GOOGLE_CREDENTIALS_FILE``. + TYPE_PKCS12_FILE (1): + PKCS12 format. The password for the PKCS12 file is + ``notasecret``. For more information, see + https://tools.ietf.org/html/rfc7292. + TYPE_GOOGLE_CREDENTIALS_FILE (2): + Google Credentials File format. + """ + TYPE_UNSPECIFIED = 0 + TYPE_PKCS12_FILE = 1 + TYPE_GOOGLE_CREDENTIALS_FILE = 2 + + +class ServiceAccountPublicKeyType(proto.Enum): + r"""Supported public key output formats. + + Values: + TYPE_NONE (0): + Do not return the public key. + TYPE_X509_PEM_FILE (1): + X509 PEM format. + TYPE_RAW_PUBLIC_KEY (2): + Raw public key. + """ + TYPE_NONE = 0 + TYPE_X509_PEM_FILE = 1 + TYPE_RAW_PUBLIC_KEY = 2 + + +class ServiceAccountKeyOrigin(proto.Enum): + r"""Service Account Key Origin. + + Values: + ORIGIN_UNSPECIFIED (0): + Unspecified key origin. + USER_PROVIDED (1): + Key is provided by user. + GOOGLE_PROVIDED (2): + Key is provided by Google. + """ + ORIGIN_UNSPECIFIED = 0 + USER_PROVIDED = 1 + GOOGLE_PROVIDED = 2 + + +class RoleView(proto.Enum): + r"""A view for Role objects. + + Values: + BASIC (0): + Omits the ``included_permissions`` field. This is the + default value. + FULL (1): + Returns all fields. + """ + BASIC = 0 + FULL = 1 + + +class ServiceAccount(proto.Message): + r"""An IAM service account. + + A service account is an account for an application or a virtual + machine (VM) instance, not a person. You can use a service account + to call Google APIs. To learn more, read the `overview of service + accounts `__. + + When you create a service account, you specify the project ID that + owns the service account, as well as a name that must be unique + within the project. IAM uses these values to create an email address + that identifies the service account. + + Attributes: + name (str): + The resource name of the service account. + + Use one of the following formats: + + - ``projects/{PROJECT_ID}/serviceAccounts/{EMAIL_ADDRESS}`` + - ``projects/{PROJECT_ID}/serviceAccounts/{UNIQUE_ID}`` + + As an alternative, you can use the ``-`` wildcard character + instead of the project ID: + + - ``projects/-/serviceAccounts/{EMAIL_ADDRESS}`` + - ``projects/-/serviceAccounts/{UNIQUE_ID}`` + + When possible, avoid using the ``-`` wildcard character, + because it can cause response messages to contain misleading + error codes. For example, if you try to get the service + account ``projects/-/serviceAccounts/fake@example.com``, + which does not exist, the response contains an HTTP + ``403 Forbidden`` error instead of a ``404 Not Found`` + error. + project_id (str): + Output only. The ID of the project that owns + the service account. + unique_id (str): + Output only. The unique, stable numeric ID + for the service account. + Each service account retains its unique ID even + if you delete the service account. For example, + if you delete a service account, then create a + new service account with the same name, the new + service account has a different unique ID than + the deleted service account. + email (str): + Output only. The email address of the service + account. + display_name (str): + Optional. A user-specified, human-readable + name for the service account. The maximum length + is 100 UTF-8 bytes. + etag (bytes): + Deprecated. Do not use. + description (str): + Optional. A user-specified, human-readable + description of the service account. The maximum + length is 256 UTF-8 bytes. + oauth2_client_id (str): + Output only. The OAuth 2.0 client ID for the + service account. + disabled (bool): + Output only. Whether the service account is + disabled. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + project_id: str = proto.Field( + proto.STRING, + number=2, + ) + unique_id: str = proto.Field( + proto.STRING, + number=4, + ) + email: str = proto.Field( + proto.STRING, + number=5, + ) + display_name: str = proto.Field( + proto.STRING, + number=6, + ) + etag: bytes = proto.Field( + proto.BYTES, + number=7, + ) + description: str = proto.Field( + proto.STRING, + number=8, + ) + oauth2_client_id: str = proto.Field( + proto.STRING, + number=9, + ) + disabled: bool = proto.Field( + proto.BOOL, + number=11, + ) + + +class CreateServiceAccountRequest(proto.Message): + r"""The service account create request. + + Attributes: + name (str): + Required. The resource name of the project associated with + the service accounts, such as ``projects/my-project-123``. + account_id (str): + Required. The account id that is used to generate the + service account email address and a stable unique id. It is + unique within a project, must be 6-30 characters long, and + match the regular expression ``[a-z]([-a-z0-9]*[a-z0-9])`` + to comply with RFC1035. + service_account (google.cloud.iam_admin_v1.types.ServiceAccount): + The [ServiceAccount][google.iam.admin.v1.ServiceAccount] + resource to create. Currently, only the following values are + user assignable: ``display_name`` and ``description``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + account_id: str = proto.Field( + proto.STRING, + number=2, + ) + service_account: "ServiceAccount" = proto.Field( + proto.MESSAGE, + number=3, + message="ServiceAccount", + ) + + +class ListServiceAccountsRequest(proto.Message): + r"""The service account list request. + + Attributes: + name (str): + Required. The resource name of the project associated with + the service accounts, such as ``projects/my-project-123``. + page_size (int): + Optional limit on the number of service accounts to include + in the response. Further accounts can subsequently be + obtained by including the + [ListServiceAccountsResponse.next_page_token][google.iam.admin.v1.ListServiceAccountsResponse.next_page_token] + in a subsequent request. + + The default is 20, and the maximum is 100. + page_token (str): + Optional pagination token returned in an earlier + [ListServiceAccountsResponse.next_page_token][google.iam.admin.v1.ListServiceAccountsResponse.next_page_token]. + """ + + name: 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 ListServiceAccountsResponse(proto.Message): + r"""The service account list response. + + Attributes: + accounts (MutableSequence[google.cloud.iam_admin_v1.types.ServiceAccount]): + The list of matching service accounts. + next_page_token (str): + To retrieve the next page of results, set + [ListServiceAccountsRequest.page_token][google.iam.admin.v1.ListServiceAccountsRequest.page_token] + to this value. + """ + + @property + def raw_page(self): + return self + + accounts: MutableSequence["ServiceAccount"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ServiceAccount", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetServiceAccountRequest(proto.Message): + r"""The service account get request. + + Attributes: + name (str): + Required. The resource name of the service account in the + following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. Using + ``-`` as a wildcard for the ``PROJECT_ID`` will infer the + project from the account. The ``ACCOUNT`` value can be the + ``email`` address or the ``unique_id`` of the service + account. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteServiceAccountRequest(proto.Message): + r"""The service account delete request. + + Attributes: + name (str): + Required. The resource name of the service account in the + following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. Using + ``-`` as a wildcard for the ``PROJECT_ID`` will infer the + project from the account. The ``ACCOUNT`` value can be the + ``email`` address or the ``unique_id`` of the service + account. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class PatchServiceAccountRequest(proto.Message): + r"""The service account patch request. + + You can patch only the ``display_name`` and ``description`` fields. + You must use the ``update_mask`` field to specify which of these + fields you want to patch. + + Only the fields specified in the request are guaranteed to be + returned in the response. Other fields may be empty in the response. + + Attributes: + service_account (google.cloud.iam_admin_v1.types.ServiceAccount): + + update_mask (google.protobuf.field_mask_pb2.FieldMask): + + """ + + service_account: "ServiceAccount" = proto.Field( + proto.MESSAGE, + number=1, + message="ServiceAccount", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UndeleteServiceAccountRequest(proto.Message): + r"""The service account undelete request. + + Attributes: + name (str): + The resource name of the service account in the following + format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT_UNIQUE_ID}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will infer + the project from the account. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UndeleteServiceAccountResponse(proto.Message): + r""" + + Attributes: + restored_account (google.cloud.iam_admin_v1.types.ServiceAccount): + Metadata for the restored service account. + """ + + restored_account: "ServiceAccount" = proto.Field( + proto.MESSAGE, + number=1, + message="ServiceAccount", + ) + + +class EnableServiceAccountRequest(proto.Message): + r"""The service account enable request. + + Attributes: + name (str): + The resource name of the service account in the following + format: ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will infer + the project from the account. The ``ACCOUNT`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DisableServiceAccountRequest(proto.Message): + r"""The service account disable request. + + Attributes: + name (str): + The resource name of the service account in the following + format: ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will infer + the project from the account. The ``ACCOUNT`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListServiceAccountKeysRequest(proto.Message): + r"""The service account keys list request. + + Attributes: + name (str): + Required. The resource name of the service account in the + following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID``, will infer + the project from the account. The ``ACCOUNT`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + key_types (MutableSequence[google.cloud.iam_admin_v1.types.ListServiceAccountKeysRequest.KeyType]): + Filters the types of keys the user wants to + include in the list response. Duplicate key + types are not allowed. If no key type is + provided, all keys are returned. + """ + + class KeyType(proto.Enum): + r"""``KeyType`` filters to selectively retrieve certain varieties of + keys. + + Values: + KEY_TYPE_UNSPECIFIED (0): + Unspecified key type. The presence of this in + the message will immediately result in an error. + USER_MANAGED (1): + User-managed keys (managed and rotated by the + user). + SYSTEM_MANAGED (2): + System-managed keys (managed and rotated by + Google). + """ + KEY_TYPE_UNSPECIFIED = 0 + USER_MANAGED = 1 + SYSTEM_MANAGED = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + key_types: MutableSequence[KeyType] = proto.RepeatedField( + proto.ENUM, + number=2, + enum=KeyType, + ) + + +class ListServiceAccountKeysResponse(proto.Message): + r"""The service account keys list response. + + Attributes: + keys (MutableSequence[google.cloud.iam_admin_v1.types.ServiceAccountKey]): + The public keys for the service account. + """ + + keys: MutableSequence["ServiceAccountKey"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ServiceAccountKey", + ) + + +class GetServiceAccountKeyRequest(proto.Message): + r"""The service account key get by id request. + + Attributes: + name (str): + Required. The resource name of the service account key in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID`` will infer + the project from the account. The ``ACCOUNT`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + public_key_type (google.cloud.iam_admin_v1.types.ServiceAccountPublicKeyType): + Optional. The output format of the public key. The default + is ``TYPE_NONE``, which means that the public key is not + returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + public_key_type: "ServiceAccountPublicKeyType" = proto.Field( + proto.ENUM, + number=2, + enum="ServiceAccountPublicKeyType", + ) + + +class ServiceAccountKey(proto.Message): + r"""Represents a service account key. + + A service account has two sets of key-pairs: user-managed, and + system-managed. + + User-managed key-pairs can be created and deleted by users. + Users are responsible for rotating these keys periodically to + ensure security of their service accounts. Users retain the + private key of these key-pairs, and Google retains ONLY the + public key. + + System-managed keys are automatically rotated by Google, and are + used for signing for a maximum of two weeks. The rotation + process is probabilistic, and usage of the new key will + gradually ramp up and down over the key's lifetime. + + If you cache the public key set for a service account, we + recommend that you update the cache every 15 minutes. + User-managed keys can be added and removed at any time, so it is + important to update the cache frequently. For Google-managed + keys, Google will publish a key at least 6 hours before it is + first used for signing and will keep publishing it for at least + 6 hours after it was last used for signing. + + Public keys for all service accounts are also published at the + OAuth2 Service Account API. + + Attributes: + name (str): + The resource name of the service account key in the + following format + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + private_key_type (google.cloud.iam_admin_v1.types.ServiceAccountPrivateKeyType): + The output format for the private key. Only provided in + ``CreateServiceAccountKey`` responses, not in + ``GetServiceAccountKey`` or ``ListServiceAccountKey`` + responses. + + Google never exposes system-managed private keys, and never + retains user-managed private keys. + key_algorithm (google.cloud.iam_admin_v1.types.ServiceAccountKeyAlgorithm): + Specifies the algorithm (and possibly key + size) for the key. + private_key_data (bytes): + The private key data. Only provided in + ``CreateServiceAccountKey`` responses. Make sure to keep the + private key data secure because it allows for the assertion + of the service account identity. When base64 decoded, the + private key data can be used to authenticate with Google API + client libraries and with gcloud auth + activate-service-account. + public_key_data (bytes): + The public key data. Only provided in + ``GetServiceAccountKey`` responses. + valid_after_time (google.protobuf.timestamp_pb2.Timestamp): + The key can be used after this timestamp. + valid_before_time (google.protobuf.timestamp_pb2.Timestamp): + The key can be used before this timestamp. + For system-managed key pairs, this timestamp is + the end time for the private key signing + operation. The public key could still be used + for verification for a few hours after this + time. + key_origin (google.cloud.iam_admin_v1.types.ServiceAccountKeyOrigin): + The key origin. + key_type (google.cloud.iam_admin_v1.types.ListServiceAccountKeysRequest.KeyType): + The key type. + disabled (bool): + The key status. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + private_key_type: "ServiceAccountPrivateKeyType" = proto.Field( + proto.ENUM, + number=2, + enum="ServiceAccountPrivateKeyType", + ) + key_algorithm: "ServiceAccountKeyAlgorithm" = proto.Field( + proto.ENUM, + number=8, + enum="ServiceAccountKeyAlgorithm", + ) + private_key_data: bytes = proto.Field( + proto.BYTES, + number=3, + ) + public_key_data: bytes = proto.Field( + proto.BYTES, + number=7, + ) + valid_after_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + valid_before_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + key_origin: "ServiceAccountKeyOrigin" = proto.Field( + proto.ENUM, + number=9, + enum="ServiceAccountKeyOrigin", + ) + key_type: "ListServiceAccountKeysRequest.KeyType" = proto.Field( + proto.ENUM, + number=10, + enum="ListServiceAccountKeysRequest.KeyType", + ) + disabled: bool = proto.Field( + proto.BOOL, + number=11, + ) + + +class CreateServiceAccountKeyRequest(proto.Message): + r"""The service account key create request. + + Attributes: + name (str): + Required. The resource name of the service account in the + following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. Using + ``-`` as a wildcard for the ``PROJECT_ID`` will infer the + project from the account. The ``ACCOUNT`` value can be the + ``email`` address or the ``unique_id`` of the service + account. + private_key_type (google.cloud.iam_admin_v1.types.ServiceAccountPrivateKeyType): + The output format of the private key. The default value is + ``TYPE_GOOGLE_CREDENTIALS_FILE``, which is the Google + Credentials File format. + key_algorithm (google.cloud.iam_admin_v1.types.ServiceAccountKeyAlgorithm): + Which type of key and algorithm to use for + the key. The default is currently a 2K RSA key. + However this may change in the future. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + private_key_type: "ServiceAccountPrivateKeyType" = proto.Field( + proto.ENUM, + number=2, + enum="ServiceAccountPrivateKeyType", + ) + key_algorithm: "ServiceAccountKeyAlgorithm" = proto.Field( + proto.ENUM, + number=3, + enum="ServiceAccountKeyAlgorithm", + ) + + +class UploadServiceAccountKeyRequest(proto.Message): + r"""The service account key upload request. + + Attributes: + name (str): + The resource name of the service account in the following + format: ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will infer + the project from the account. The ``ACCOUNT`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + public_key_data (bytes): + The public key to associate with the service account. Must + be an RSA public key that is wrapped in an X.509 v3 + certificate. Include the first line, + ``-----BEGIN CERTIFICATE-----``, and the last line, + ``-----END CERTIFICATE-----``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + public_key_data: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +class DeleteServiceAccountKeyRequest(proto.Message): + r"""The service account key delete request. + + Attributes: + name (str): + Required. The resource name of the service account key in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will infer + the project from the account. The ``ACCOUNT`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DisableServiceAccountKeyRequest(proto.Message): + r"""The service account key disable request. + + Attributes: + name (str): + Required. The resource name of the service account key in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID`` will infer + the project from the account. The ``ACCOUNT`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class EnableServiceAccountKeyRequest(proto.Message): + r"""The service account key enable request. + + Attributes: + name (str): + Required. The resource name of the service account key in + the following format: + ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}``. + + Using ``-`` as a wildcard for the ``PROJECT_ID`` will infer + the project from the account. The ``ACCOUNT`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class SignBlobRequest(proto.Message): + r"""Deprecated. `Migrate to Service Account Credentials + API `__. + + The service account sign blob request. + + Attributes: + name (str): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The resource name of the service account in the following + format: ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will infer + the project from the account. The ``ACCOUNT`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + bytes_to_sign (bytes): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The bytes to sign. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + bytes_to_sign: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +class SignBlobResponse(proto.Message): + r"""Deprecated. `Migrate to Service Account Credentials + API `__. + + The service account sign blob response. + + Attributes: + key_id (str): + Deprecated. `Migrate to Service Account Credentials + API `__. + + The id of the key used to sign the blob. + signature (bytes): + Deprecated. `Migrate to Service Account Credentials + API `__. + + The signed blob. + """ + + key_id: str = proto.Field( + proto.STRING, + number=1, + ) + signature: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +class SignJwtRequest(proto.Message): + r"""Deprecated. `Migrate to Service Account Credentials + API `__. + + The service account sign JWT request. + + Attributes: + name (str): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The resource name of the service account in the following + format: ``projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}``. + Using ``-`` as a wildcard for the ``PROJECT_ID`` will infer + the project from the account. The ``ACCOUNT`` value can be + the ``email`` address or the ``unique_id`` of the service + account. + payload (str): + Required. Deprecated. `Migrate to Service Account + Credentials + API `__. + + The JWT payload to sign. Must be a serialized JSON object + that contains a JWT Claims Set. For example: + ``{"sub": "user@example.com", "iat": 313435}`` + + If the JWT Claims Set contains an expiration time (``exp``) + claim, it must be an integer timestamp that is not in the + past and no more than 12 hours in the future. + + If the JWT Claims Set does not contain an expiration time + (``exp``) claim, this claim is added automatically, with a + timestamp that is 1 hour in the future. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + payload: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SignJwtResponse(proto.Message): + r"""Deprecated. `Migrate to Service Account Credentials + API `__. + + The service account sign JWT response. + + Attributes: + key_id (str): + Deprecated. `Migrate to Service Account Credentials + API `__. + + The id of the key used to sign the JWT. + signed_jwt (str): + Deprecated. `Migrate to Service Account Credentials + API `__. + + The signed JWT. + """ + + key_id: str = proto.Field( + proto.STRING, + number=1, + ) + signed_jwt: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Role(proto.Message): + r"""A role in the Identity and Access Management API. + + Attributes: + name (str): + The name of the role. + + When Role is used in CreateRole, the role name must not be + set. + + When Role is used in output and other input such as + UpdateRole, the role name is the complete path, e.g., + roles/logging.viewer for predefined roles and + organizations/{ORGANIZATION_ID}/roles/logging.viewer for + custom roles. + title (str): + Optional. A human-readable title for the + role. Typically this is limited to 100 UTF-8 + bytes. + description (str): + Optional. A human-readable description for + the role. + included_permissions (MutableSequence[str]): + The names of the permissions this role grants + when bound in an IAM policy. + stage (google.cloud.iam_admin_v1.types.Role.RoleLaunchStage): + The current launch stage of the role. If the ``ALPHA`` + launch stage has been selected for a role, the ``stage`` + field will not be included in the returned definition for + the role. + etag (bytes): + Used to perform a consistent + read-modify-write. + deleted (bool): + The current deleted state of the role. This + field is read only. It will be ignored in calls + to CreateRole and UpdateRole. + """ + + class RoleLaunchStage(proto.Enum): + r"""A stage representing a role's lifecycle phase. + + Values: + ALPHA (0): + The user has indicated this role is currently in an Alpha + phase. If this launch stage is selected, the ``stage`` field + will not be included when requesting the definition for a + given role. + BETA (1): + The user has indicated this role is currently + in a Beta phase. + GA (2): + The user has indicated this role is generally + available. + DEPRECATED (4): + The user has indicated this role is being + deprecated. + DISABLED (5): + This role is disabled and will not contribute + permissions to any principals it is granted to + in policies. + EAP (6): + The user has indicated this role is currently + in an EAP phase. + """ + ALPHA = 0 + BETA = 1 + GA = 2 + DEPRECATED = 4 + DISABLED = 5 + EAP = 6 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + title: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + included_permissions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + stage: RoleLaunchStage = proto.Field( + proto.ENUM, + number=8, + enum=RoleLaunchStage, + ) + etag: bytes = proto.Field( + proto.BYTES, + number=9, + ) + deleted: bool = proto.Field( + proto.BOOL, + number=11, + ) + + +class QueryGrantableRolesRequest(proto.Message): + r"""The grantable role query request. + + Attributes: + full_resource_name (str): + Required. The full resource name to query from the list of + grantable roles. + + The name follows the Google Cloud Platform resource format. + For example, a Cloud Platform project with id ``my-project`` + will be named + ``//cloudresourcemanager.googleapis.com/projects/my-project``. + view (google.cloud.iam_admin_v1.types.RoleView): + + page_size (int): + Optional limit on the number of roles to + include in the response. + The default is 300, and the maximum is 1,000. + page_token (str): + Optional pagination token returned in an + earlier QueryGrantableRolesResponse. + """ + + full_resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + view: "RoleView" = proto.Field( + proto.ENUM, + number=2, + enum="RoleView", + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class QueryGrantableRolesResponse(proto.Message): + r"""The grantable role query response. + + Attributes: + roles (MutableSequence[google.cloud.iam_admin_v1.types.Role]): + The list of matching roles. + next_page_token (str): + To retrieve the next page of results, set + ``QueryGrantableRolesRequest.page_token`` to this value. + """ + + @property + def raw_page(self): + return self + + roles: MutableSequence["Role"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Role", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListRolesRequest(proto.Message): + r"""The request to get all roles defined under a resource. + + Attributes: + parent (str): + The ``parent`` parameter's value depends on the target + resource for the request, namely + ```roles`` `__, + ```projects`` `__, + or + ```organizations`` `__. + Each resource type's ``parent`` value format is described + below: + + - ```roles.list()`` `__: + An empty string. This method doesn't require a resource; + it simply returns all `predefined + roles `__ + in Cloud IAM. Example request URL: + ``https://iam.googleapis.com/v1/roles`` + + - ```projects.roles.list()`` `__: + ``projects/{PROJECT_ID}``. This method lists all + project-level `custom + roles `__. + Example request URL: + ``https://iam.googleapis.com/v1/projects/{PROJECT_ID}/roles`` + + - ```organizations.roles.list()`` `__: + ``organizations/{ORGANIZATION_ID}``. This method lists + all organization-level `custom + roles `__. + Example request URL: + ``https://iam.googleapis.com/v1/organizations/{ORGANIZATION_ID}/roles`` + + Note: Wildcard (*) values are invalid; you must specify a + complete project ID or organization ID. + page_size (int): + Optional limit on the number of roles to + include in the response. + The default is 300, and the maximum is 1,000. + page_token (str): + Optional pagination token returned in an + earlier ListRolesResponse. + view (google.cloud.iam_admin_v1.types.RoleView): + Optional view for the returned Role objects. When ``FULL`` + is specified, the ``includedPermissions`` field is returned, + which includes a list of all permissions in the role. The + default value is ``BASIC``, which does not return the + ``includedPermissions`` field. + show_deleted (bool): + Include Roles that have been deleted. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + view: "RoleView" = proto.Field( + proto.ENUM, + number=4, + enum="RoleView", + ) + show_deleted: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class ListRolesResponse(proto.Message): + r"""The response containing the roles defined under a resource. + + Attributes: + roles (MutableSequence[google.cloud.iam_admin_v1.types.Role]): + The Roles defined on this resource. + next_page_token (str): + To retrieve the next page of results, set + ``ListRolesRequest.page_token`` to this value. + """ + + @property + def raw_page(self): + return self + + roles: MutableSequence["Role"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Role", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetRoleRequest(proto.Message): + r"""The request to get the definition of an existing role. + + Attributes: + name (str): + The ``name`` parameter's value depends on the target + resource for the request, namely + ```roles`` `__, + ```projects`` `__, + or + ```organizations`` `__. + Each resource type's ``name`` value format is described + below: + + - ```roles.get()`` `__: + ``roles/{ROLE_NAME}``. This method returns results from + all `predefined + roles `__ + in Cloud IAM. Example request URL: + ``https://iam.googleapis.com/v1/roles/{ROLE_NAME}`` + + - ```projects.roles.get()`` `__: + ``projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}``. This + method returns only `custom + roles `__ + that have been created at the project level. Example + request URL: + ``https://iam.googleapis.com/v1/projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}`` + + - ```organizations.roles.get()`` `__: + ``organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}``. + This method returns only `custom + roles `__ + that have been created at the organization level. Example + request URL: + ``https://iam.googleapis.com/v1/organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}`` + + Note: Wildcard (*) values are invalid; you must specify a + complete project ID or organization ID. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateRoleRequest(proto.Message): + r"""The request to create a new role. + + Attributes: + parent (str): + The ``parent`` parameter's value depends on the target + resource for the request, namely + ```projects`` `__ + or + ```organizations`` `__. + Each resource type's ``parent`` value format is described + below: + + - ```projects.roles.create()`` `__: + ``projects/{PROJECT_ID}``. This method creates + project-level `custom + roles `__. + Example request URL: + ``https://iam.googleapis.com/v1/projects/{PROJECT_ID}/roles`` + + - ```organizations.roles.create()`` `__: + ``organizations/{ORGANIZATION_ID}``. This method creates + organization-level `custom + roles `__. + Example request URL: + ``https://iam.googleapis.com/v1/organizations/{ORGANIZATION_ID}/roles`` + + Note: Wildcard (*) values are invalid; you must specify a + complete project ID or organization ID. + role_id (str): + The role ID to use for this role. + + A role ID may contain alphanumeric characters, underscores + (``_``), and periods (``.``). It must contain a minimum of 3 + characters and a maximum of 64 characters. + role (google.cloud.iam_admin_v1.types.Role): + The Role resource to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + role_id: str = proto.Field( + proto.STRING, + number=2, + ) + role: "Role" = proto.Field( + proto.MESSAGE, + number=3, + message="Role", + ) + + +class UpdateRoleRequest(proto.Message): + r"""The request to update a role. + + Attributes: + name (str): + The ``name`` parameter's value depends on the target + resource for the request, namely + ```projects`` `__ + or + ```organizations`` `__. + Each resource type's ``name`` value format is described + below: + + - ```projects.roles.patch()`` `__: + ``projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}``. This + method updates only `custom + roles `__ + that have been created at the project level. Example + request URL: + ``https://iam.googleapis.com/v1/projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}`` + + - ```organizations.roles.patch()`` `__: + ``organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}``. + This method updates only `custom + roles `__ + that have been created at the organization level. Example + request URL: + ``https://iam.googleapis.com/v1/organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}`` + + Note: Wildcard (*) values are invalid; you must specify a + complete project ID or organization ID. + role (google.cloud.iam_admin_v1.types.Role): + The updated role. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + A mask describing which fields in the Role + have changed. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + role: "Role" = proto.Field( + proto.MESSAGE, + number=2, + message="Role", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=3, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteRoleRequest(proto.Message): + r"""The request to delete an existing role. + + Attributes: + name (str): + The ``name`` parameter's value depends on the target + resource for the request, namely + ```projects`` `__ + or + ```organizations`` `__. + Each resource type's ``name`` value format is described + below: + + - ```projects.roles.delete()`` `__: + ``projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}``. This + method deletes only `custom + roles `__ + that have been created at the project level. Example + request URL: + ``https://iam.googleapis.com/v1/projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}`` + + - ```organizations.roles.delete()`` `__: + ``organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}``. + This method deletes only `custom + roles `__ + that have been created at the organization level. Example + request URL: + ``https://iam.googleapis.com/v1/organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}`` + + Note: Wildcard (*) values are invalid; you must specify a + complete project ID or organization ID. + etag (bytes): + Used to perform a consistent + read-modify-write. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +class UndeleteRoleRequest(proto.Message): + r"""The request to undelete an existing role. + + Attributes: + name (str): + The ``name`` parameter's value depends on the target + resource for the request, namely + ```projects`` `__ + or + ```organizations`` `__. + Each resource type's ``name`` value format is described + below: + + - ```projects.roles.undelete()`` `__: + ``projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}``. This + method undeletes only `custom + roles `__ + that have been created at the project level. Example + request URL: + ``https://iam.googleapis.com/v1/projects/{PROJECT_ID}/roles/{CUSTOM_ROLE_ID}`` + + - ```organizations.roles.undelete()`` `__: + ``organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}``. + This method undeletes only `custom + roles `__ + that have been created at the organization level. Example + request URL: + ``https://iam.googleapis.com/v1/organizations/{ORGANIZATION_ID}/roles/{CUSTOM_ROLE_ID}`` + + Note: Wildcard (*) values are invalid; you must specify a + complete project ID or organization ID. + etag (bytes): + Used to perform a consistent + read-modify-write. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +class Permission(proto.Message): + r"""A permission which can be included by a role. + + Attributes: + name (str): + The name of this Permission. + title (str): + The title of this Permission. + description (str): + A brief description of what this Permission + is used for. This permission can ONLY be used in + predefined roles. + only_in_predefined_roles (bool): + + stage (google.cloud.iam_admin_v1.types.Permission.PermissionLaunchStage): + The current launch stage of the permission. + custom_roles_support_level (google.cloud.iam_admin_v1.types.Permission.CustomRolesSupportLevel): + The current custom role support level. + api_disabled (bool): + The service API associated with the + permission is not enabled. + primary_permission (str): + The preferred name for this permission. If present, then + this permission is an alias of, and equivalent to, the + listed primary_permission. + """ + + class PermissionLaunchStage(proto.Enum): + r"""A stage representing a permission's lifecycle phase. + + Values: + ALPHA (0): + The permission is currently in an alpha + phase. + BETA (1): + The permission is currently in a beta phase. + GA (2): + The permission is generally available. + DEPRECATED (3): + The permission is being deprecated. + """ + ALPHA = 0 + BETA = 1 + GA = 2 + DEPRECATED = 3 + + class CustomRolesSupportLevel(proto.Enum): + r"""The state of the permission with regards to custom roles. + + Values: + SUPPORTED (0): + Default state. Permission is fully supported + for custom role use. + TESTING (1): + Permission is being tested to check custom + role compatibility. + NOT_SUPPORTED (2): + Permission is not supported for custom role + use. + """ + SUPPORTED = 0 + TESTING = 1 + NOT_SUPPORTED = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + title: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + only_in_predefined_roles: bool = proto.Field( + proto.BOOL, + number=4, + ) + stage: PermissionLaunchStage = proto.Field( + proto.ENUM, + number=5, + enum=PermissionLaunchStage, + ) + custom_roles_support_level: CustomRolesSupportLevel = proto.Field( + proto.ENUM, + number=6, + enum=CustomRolesSupportLevel, + ) + api_disabled: bool = proto.Field( + proto.BOOL, + number=7, + ) + primary_permission: str = proto.Field( + proto.STRING, + number=8, + ) + + +class QueryTestablePermissionsRequest(proto.Message): + r"""A request to get permissions which can be tested on a + resource. + + Attributes: + full_resource_name (str): + Required. The full resource name to query from the list of + testable permissions. + + The name follows the Google Cloud Platform resource format. + For example, a Cloud Platform project with id ``my-project`` + will be named + ``//cloudresourcemanager.googleapis.com/projects/my-project``. + page_size (int): + Optional limit on the number of permissions + to include in the response. + The default is 100, and the maximum is 1,000. + page_token (str): + Optional pagination token returned in an + earlier QueryTestablePermissionsRequest. + """ + + full_resource_name: 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 QueryTestablePermissionsResponse(proto.Message): + r"""The response containing permissions which can be tested on a + resource. + + Attributes: + permissions (MutableSequence[google.cloud.iam_admin_v1.types.Permission]): + The Permissions testable on the requested + resource. + next_page_token (str): + To retrieve the next page of results, set + ``QueryTestableRolesRequest.page_token`` to this value. + """ + + @property + def raw_page(self): + return self + + permissions: MutableSequence["Permission"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Permission", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class QueryAuditableServicesRequest(proto.Message): + r"""A request to get the list of auditable services for a + resource. + + Attributes: + full_resource_name (str): + Required. The full resource name to query from the list of + auditable services. + + The name follows the Google Cloud Platform resource format. + For example, a Cloud Platform project with id ``my-project`` + will be named + ``//cloudresourcemanager.googleapis.com/projects/my-project``. + """ + + full_resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class QueryAuditableServicesResponse(proto.Message): + r"""A response containing a list of auditable services for a + resource. + + Attributes: + services (MutableSequence[google.cloud.iam_admin_v1.types.QueryAuditableServicesResponse.AuditableService]): + The auditable services for a resource. + """ + + class AuditableService(proto.Message): + r"""Contains information about an auditable service. + + Attributes: + name (str): + Public name of the service. + For example, the service name for Cloud IAM is + 'iam.googleapis.com'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + services: MutableSequence[AuditableService] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=AuditableService, + ) + + +class LintPolicyRequest(proto.Message): + r"""The request to lint a Cloud IAM policy object. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + full_resource_name (str): + The full resource name of the policy this lint request is + about. + + The name follows the Google Cloud Platform (GCP) resource + format. For example, a GCP project with ID ``my-project`` + will be named + ``//cloudresourcemanager.googleapis.com/projects/my-project``. + + The resource name is not used to read the policy instance + from the Cloud IAM database. The candidate policy for lint + has to be provided in the same request object. + condition (google.type.expr_pb2.Expr): + [google.iam.v1.Binding.condition] + [google.iam.v1.Binding.condition] object to be linted. + + This field is a member of `oneof`_ ``lint_object``. + """ + + full_resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + condition: expr_pb2.Expr = proto.Field( + proto.MESSAGE, + number=5, + oneof="lint_object", + message=expr_pb2.Expr, + ) + + +class LintResult(proto.Message): + r"""Structured response of a single validation unit. + + Attributes: + level (google.cloud.iam_admin_v1.types.LintResult.Level): + The validation unit level. + validation_unit_name (str): + The validation unit name, for instance + "lintValidationUnits/ConditionComplexityCheck". + severity (google.cloud.iam_admin_v1.types.LintResult.Severity): + The validation unit severity. + field_name (str): + The name of the field for which this lint result is about. + + For nested messages ``field_name`` consists of names of the + embedded fields separated by period character. The top-level + qualifier is the input object to lint in the request. For + example, the ``field_name`` value ``condition.expression`` + identifies a lint result for the ``expression`` field of the + provided condition. + location_offset (int): + 0-based character position of problematic construct within + the object identified by ``field_name``. Currently, this is + populated only for condition expression. + debug_message (str): + Human readable debug message associated with + the issue. + """ + + class Level(proto.Enum): + r"""Possible Level values of a validation unit corresponding to + its domain of discourse. + + Values: + LEVEL_UNSPECIFIED (0): + Level is unspecified. + CONDITION (3): + A validation unit which operates on an + individual condition within a binding. + """ + LEVEL_UNSPECIFIED = 0 + CONDITION = 3 + + class Severity(proto.Enum): + r"""Possible Severity values of an issued result. + + Values: + SEVERITY_UNSPECIFIED (0): + Severity is unspecified. + ERROR (1): + A validation unit returns an error only for critical issues. + If an attempt is made to set the problematic policy without + rectifying the critical issue, it causes the ``setPolicy`` + operation to fail. + WARNING (2): + Any issue which is severe enough but does not cause an + error. For example, suspicious constructs in the input + object will not necessarily fail ``setPolicy``, but there is + a high likelihood that they won't behave as expected during + policy evaluation in ``checkPolicy``. This includes the + following common scenarios: + + - Unsatisfiable condition: Expired timestamp in date/time + condition. + - Ineffective condition: Condition on a + pair which is granted unconditionally in another binding + of the same policy. + NOTICE (3): + Reserved for the issues that are not severe as + ``ERROR``/``WARNING``, but need special handling. For + instance, messages about skipped validation units are issued + as ``NOTICE``. + INFO (4): + Any informative statement which is not severe enough to + raise ``ERROR``/``WARNING``/``NOTICE``, like auto-correction + recommendations on the input content. Note that current + version of the linter does not utilize ``INFO``. + DEPRECATED (5): + Deprecated severity level. + """ + SEVERITY_UNSPECIFIED = 0 + ERROR = 1 + WARNING = 2 + NOTICE = 3 + INFO = 4 + DEPRECATED = 5 + + level: Level = proto.Field( + proto.ENUM, + number=1, + enum=Level, + ) + validation_unit_name: str = proto.Field( + proto.STRING, + number=2, + ) + severity: Severity = proto.Field( + proto.ENUM, + number=3, + enum=Severity, + ) + field_name: str = proto.Field( + proto.STRING, + number=5, + ) + location_offset: int = proto.Field( + proto.INT32, + number=6, + ) + debug_message: str = proto.Field( + proto.STRING, + number=7, + ) + + +class LintPolicyResponse(proto.Message): + r"""The response of a lint operation. An empty response indicates + the operation was able to fully execute and no lint issue was + found. + + Attributes: + lint_results (MutableSequence[google.cloud.iam_admin_v1.types.LintResult]): + List of lint results sorted by ``severity`` in descending + order. + """ + + lint_results: MutableSequence["LintResult"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="LintResult", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_create_role_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_create_role_async.py new file mode 100644 index 000000000000..ed6fccb389a5 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_create_role_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateRole +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_CreateRole_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_create_role(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.CreateRoleRequest( + ) + + # Make the request + response = await client.create_role(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_CreateRole_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_create_role_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_create_role_sync.py new file mode 100644 index 000000000000..15088404dca7 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_create_role_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateRole +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_CreateRole_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_create_role(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.CreateRoleRequest( + ) + + # Make the request + response = client.create_role(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_CreateRole_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_create_service_account_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_create_service_account_async.py new file mode 100644 index 000000000000..206fa64054e9 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_create_service_account_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServiceAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_CreateServiceAccount_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_create_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.CreateServiceAccountRequest( + name="name_value", + account_id="account_id_value", + ) + + # Make the request + response = await client.create_service_account(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_CreateServiceAccount_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_create_service_account_key_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_create_service_account_key_async.py new file mode 100644 index 000000000000..d28ddbfaf0fe --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_create_service_account_key_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServiceAccountKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_CreateServiceAccountKey_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_create_service_account_key(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.CreateServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + response = await client.create_service_account_key(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_CreateServiceAccountKey_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_create_service_account_key_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_create_service_account_key_sync.py new file mode 100644 index 000000000000..007951d7b83c --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_create_service_account_key_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServiceAccountKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_CreateServiceAccountKey_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_create_service_account_key(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.CreateServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + response = client.create_service_account_key(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_CreateServiceAccountKey_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_create_service_account_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_create_service_account_sync.py new file mode 100644 index 000000000000..8be99027c4c3 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_create_service_account_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateServiceAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_CreateServiceAccount_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_create_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.CreateServiceAccountRequest( + name="name_value", + account_id="account_id_value", + ) + + # Make the request + response = client.create_service_account(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_CreateServiceAccount_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_delete_role_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_delete_role_async.py new file mode 100644 index 000000000000..7d1e9f539574 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_delete_role_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteRole +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_DeleteRole_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_delete_role(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.DeleteRoleRequest( + ) + + # Make the request + response = await client.delete_role(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_DeleteRole_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_delete_role_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_delete_role_sync.py new file mode 100644 index 000000000000..cb57949b3eb6 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_delete_role_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteRole +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_DeleteRole_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_delete_role(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.DeleteRoleRequest( + ) + + # Make the request + response = client.delete_role(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_DeleteRole_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_delete_service_account_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_delete_service_account_async.py new file mode 100644 index 000000000000..f6dd96090b0c --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_delete_service_account_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServiceAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_DeleteServiceAccount_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_delete_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.DeleteServiceAccountRequest( + name="name_value", + ) + + # Make the request + await client.delete_service_account(request=request) + + +# [END iam_v1_generated_IAM_DeleteServiceAccount_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_delete_service_account_key_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_delete_service_account_key_async.py new file mode 100644 index 000000000000..6d18bb4620c1 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_delete_service_account_key_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServiceAccountKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_DeleteServiceAccountKey_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_delete_service_account_key(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.DeleteServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + await client.delete_service_account_key(request=request) + + +# [END iam_v1_generated_IAM_DeleteServiceAccountKey_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_delete_service_account_key_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_delete_service_account_key_sync.py new file mode 100644 index 000000000000..81c14fcd2263 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_delete_service_account_key_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServiceAccountKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_DeleteServiceAccountKey_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_delete_service_account_key(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.DeleteServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + client.delete_service_account_key(request=request) + + +# [END iam_v1_generated_IAM_DeleteServiceAccountKey_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_delete_service_account_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_delete_service_account_sync.py new file mode 100644 index 000000000000..1d94e8aa3b7d --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_delete_service_account_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteServiceAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_DeleteServiceAccount_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_delete_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.DeleteServiceAccountRequest( + name="name_value", + ) + + # Make the request + client.delete_service_account(request=request) + + +# [END iam_v1_generated_IAM_DeleteServiceAccount_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_disable_service_account_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_disable_service_account_async.py new file mode 100644 index 000000000000..af7d8115b2c7 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_disable_service_account_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DisableServiceAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_DisableServiceAccount_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_disable_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.DisableServiceAccountRequest( + ) + + # Make the request + await client.disable_service_account(request=request) + + +# [END iam_v1_generated_IAM_DisableServiceAccount_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_disable_service_account_key_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_disable_service_account_key_async.py new file mode 100644 index 000000000000..6110f0a48da7 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_disable_service_account_key_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DisableServiceAccountKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_DisableServiceAccountKey_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_disable_service_account_key(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.DisableServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + await client.disable_service_account_key(request=request) + + +# [END iam_v1_generated_IAM_DisableServiceAccountKey_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_disable_service_account_key_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_disable_service_account_key_sync.py new file mode 100644 index 000000000000..1ae8d5797cd6 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_disable_service_account_key_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DisableServiceAccountKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_DisableServiceAccountKey_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_disable_service_account_key(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.DisableServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + client.disable_service_account_key(request=request) + + +# [END iam_v1_generated_IAM_DisableServiceAccountKey_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_disable_service_account_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_disable_service_account_sync.py new file mode 100644 index 000000000000..892c050cb78a --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_disable_service_account_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DisableServiceAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_DisableServiceAccount_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_disable_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.DisableServiceAccountRequest( + ) + + # Make the request + client.disable_service_account(request=request) + + +# [END iam_v1_generated_IAM_DisableServiceAccount_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_enable_service_account_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_enable_service_account_async.py new file mode 100644 index 000000000000..b0106f9d92bf --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_enable_service_account_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for EnableServiceAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_EnableServiceAccount_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_enable_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.EnableServiceAccountRequest( + ) + + # Make the request + await client.enable_service_account(request=request) + + +# [END iam_v1_generated_IAM_EnableServiceAccount_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_enable_service_account_key_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_enable_service_account_key_async.py new file mode 100644 index 000000000000..9917323286e1 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_enable_service_account_key_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for EnableServiceAccountKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_EnableServiceAccountKey_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_enable_service_account_key(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.EnableServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + await client.enable_service_account_key(request=request) + + +# [END iam_v1_generated_IAM_EnableServiceAccountKey_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_enable_service_account_key_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_enable_service_account_key_sync.py new file mode 100644 index 000000000000..339e7b5a1c75 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_enable_service_account_key_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for EnableServiceAccountKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_EnableServiceAccountKey_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_enable_service_account_key(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.EnableServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + client.enable_service_account_key(request=request) + + +# [END iam_v1_generated_IAM_EnableServiceAccountKey_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_enable_service_account_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_enable_service_account_sync.py new file mode 100644 index 000000000000..77eec32fff91 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_enable_service_account_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for EnableServiceAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_EnableServiceAccount_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_enable_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.EnableServiceAccountRequest( + ) + + # Make the request + client.enable_service_account(request=request) + + +# [END iam_v1_generated_IAM_EnableServiceAccount_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_iam_policy_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_iam_policy_async.py new file mode 100644 index 000000000000..8e087356be34 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_iam_policy_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_GetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_get_iam_policy(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_GetIamPolicy_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_iam_policy_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_iam_policy_sync.py new file mode 100644 index 000000000000..2508e2ed9a10 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_iam_policy_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_GetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_get_iam_policy(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.get_iam_policy(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_GetIamPolicy_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_role_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_role_async.py new file mode 100644 index 000000000000..a3abd1595c05 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_role_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetRole +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_GetRole_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_get_role(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.GetRoleRequest( + ) + + # Make the request + response = await client.get_role(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_GetRole_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_role_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_role_sync.py new file mode 100644 index 000000000000..ad554e08880d --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_role_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetRole +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_GetRole_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_get_role(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.GetRoleRequest( + ) + + # Make the request + response = client.get_role(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_GetRole_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_service_account_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_service_account_async.py new file mode 100644 index 000000000000..759bddeb4861 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_service_account_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServiceAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_GetServiceAccount_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_get_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.GetServiceAccountRequest( + name="name_value", + ) + + # Make the request + response = await client.get_service_account(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_GetServiceAccount_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_service_account_key_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_service_account_key_async.py new file mode 100644 index 000000000000..ef250788c842 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_service_account_key_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServiceAccountKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_GetServiceAccountKey_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_get_service_account_key(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.GetServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_service_account_key(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_GetServiceAccountKey_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_service_account_key_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_service_account_key_sync.py new file mode 100644 index 000000000000..7821b3fbd859 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_service_account_key_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServiceAccountKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_GetServiceAccountKey_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_get_service_account_key(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.GetServiceAccountKeyRequest( + name="name_value", + ) + + # Make the request + response = client.get_service_account_key(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_GetServiceAccountKey_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_service_account_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_service_account_sync.py new file mode 100644 index 000000000000..d9422d6c880d --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_get_service_account_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetServiceAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_GetServiceAccount_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_get_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.GetServiceAccountRequest( + name="name_value", + ) + + # Make the request + response = client.get_service_account(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_GetServiceAccount_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_lint_policy_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_lint_policy_async.py new file mode 100644 index 000000000000..1e919765ef96 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_lint_policy_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for LintPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_LintPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_lint_policy(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.LintPolicyRequest( + ) + + # Make the request + response = await client.lint_policy(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_LintPolicy_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_lint_policy_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_lint_policy_sync.py new file mode 100644 index 000000000000..a4dcc1c41027 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_lint_policy_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for LintPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_LintPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_lint_policy(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.LintPolicyRequest( + ) + + # Make the request + response = client.lint_policy(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_LintPolicy_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_list_roles_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_list_roles_async.py new file mode 100644 index 000000000000..c5e4b87d8fe0 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_list_roles_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListRoles +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_ListRoles_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_list_roles(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.ListRolesRequest( + ) + + # Make the request + page_result = client.list_roles(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END iam_v1_generated_IAM_ListRoles_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_list_roles_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_list_roles_sync.py new file mode 100644 index 000000000000..50ced048bb61 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_list_roles_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListRoles +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_ListRoles_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_list_roles(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.ListRolesRequest( + ) + + # Make the request + page_result = client.list_roles(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END iam_v1_generated_IAM_ListRoles_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_list_service_account_keys_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_list_service_account_keys_async.py new file mode 100644 index 000000000000..3babbeca2bc8 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_list_service_account_keys_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServiceAccountKeys +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_ListServiceAccountKeys_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_list_service_account_keys(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.ListServiceAccountKeysRequest( + name="name_value", + ) + + # Make the request + response = await client.list_service_account_keys(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_ListServiceAccountKeys_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_list_service_account_keys_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_list_service_account_keys_sync.py new file mode 100644 index 000000000000..4cac7b21e8c4 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_list_service_account_keys_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServiceAccountKeys +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_ListServiceAccountKeys_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_list_service_account_keys(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.ListServiceAccountKeysRequest( + name="name_value", + ) + + # Make the request + response = client.list_service_account_keys(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_ListServiceAccountKeys_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_list_service_accounts_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_list_service_accounts_async.py new file mode 100644 index 000000000000..a5caea1afbc7 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_list_service_accounts_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServiceAccounts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_ListServiceAccounts_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_list_service_accounts(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.ListServiceAccountsRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_service_accounts(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END iam_v1_generated_IAM_ListServiceAccounts_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_list_service_accounts_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_list_service_accounts_sync.py new file mode 100644 index 000000000000..cf0acda1a615 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_list_service_accounts_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListServiceAccounts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_ListServiceAccounts_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_list_service_accounts(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.ListServiceAccountsRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_service_accounts(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END iam_v1_generated_IAM_ListServiceAccounts_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_patch_service_account_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_patch_service_account_async.py new file mode 100644 index 000000000000..ebd9cf4cd0c3 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_patch_service_account_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PatchServiceAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_PatchServiceAccount_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_patch_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.PatchServiceAccountRequest( + ) + + # Make the request + response = await client.patch_service_account(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_PatchServiceAccount_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_patch_service_account_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_patch_service_account_sync.py new file mode 100644 index 000000000000..eb75048e58a4 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_patch_service_account_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PatchServiceAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_PatchServiceAccount_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_patch_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.PatchServiceAccountRequest( + ) + + # Make the request + response = client.patch_service_account(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_PatchServiceAccount_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_query_auditable_services_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_query_auditable_services_async.py new file mode 100644 index 000000000000..18b83c6d8771 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_query_auditable_services_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for QueryAuditableServices +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_QueryAuditableServices_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_query_auditable_services(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.QueryAuditableServicesRequest( + ) + + # Make the request + response = await client.query_auditable_services(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_QueryAuditableServices_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_query_auditable_services_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_query_auditable_services_sync.py new file mode 100644 index 000000000000..a35ea8e90b31 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_query_auditable_services_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for QueryAuditableServices +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_QueryAuditableServices_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_query_auditable_services(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.QueryAuditableServicesRequest( + ) + + # Make the request + response = client.query_auditable_services(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_QueryAuditableServices_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_query_grantable_roles_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_query_grantable_roles_async.py new file mode 100644 index 000000000000..a4fc32f88ef2 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_query_grantable_roles_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for QueryGrantableRoles +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_QueryGrantableRoles_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_query_grantable_roles(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.QueryGrantableRolesRequest( + full_resource_name="full_resource_name_value", + ) + + # Make the request + page_result = client.query_grantable_roles(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END iam_v1_generated_IAM_QueryGrantableRoles_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_query_grantable_roles_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_query_grantable_roles_sync.py new file mode 100644 index 000000000000..5b080bf40c1a --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_query_grantable_roles_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for QueryGrantableRoles +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_QueryGrantableRoles_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_query_grantable_roles(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.QueryGrantableRolesRequest( + full_resource_name="full_resource_name_value", + ) + + # Make the request + page_result = client.query_grantable_roles(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END iam_v1_generated_IAM_QueryGrantableRoles_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_query_testable_permissions_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_query_testable_permissions_async.py new file mode 100644 index 000000000000..51236c8d0726 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_query_testable_permissions_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for QueryTestablePermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_QueryTestablePermissions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_query_testable_permissions(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.QueryTestablePermissionsRequest( + ) + + # Make the request + page_result = client.query_testable_permissions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END iam_v1_generated_IAM_QueryTestablePermissions_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_query_testable_permissions_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_query_testable_permissions_sync.py new file mode 100644 index 000000000000..cc69e89f4516 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_query_testable_permissions_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for QueryTestablePermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_QueryTestablePermissions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_query_testable_permissions(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.QueryTestablePermissionsRequest( + ) + + # Make the request + page_result = client.query_testable_permissions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END iam_v1_generated_IAM_QueryTestablePermissions_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_set_iam_policy_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_set_iam_policy_async.py new file mode 100644 index 000000000000..522cd50af93b --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_set_iam_policy_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_SetIamPolicy_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_set_iam_policy(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = await client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_SetIamPolicy_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_set_iam_policy_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_set_iam_policy_sync.py new file mode 100644 index 000000000000..88edc7c7f47a --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_set_iam_policy_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SetIamPolicy +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_SetIamPolicy_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_set_iam_policy(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Make the request + response = client.set_iam_policy(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_SetIamPolicy_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_sign_blob_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_sign_blob_async.py new file mode 100644 index 000000000000..27de06306bfd --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_sign_blob_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SignBlob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_SignBlob_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_sign_blob(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.SignBlobRequest( + name="name_value", + bytes_to_sign=b'bytes_to_sign_blob', + ) + + # Make the request + response = await client.sign_blob(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_SignBlob_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_sign_blob_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_sign_blob_sync.py new file mode 100644 index 000000000000..329db1478626 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_sign_blob_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SignBlob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_SignBlob_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_sign_blob(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.SignBlobRequest( + name="name_value", + bytes_to_sign=b'bytes_to_sign_blob', + ) + + # Make the request + response = client.sign_blob(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_SignBlob_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_sign_jwt_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_sign_jwt_async.py new file mode 100644 index 000000000000..d6453dfadc08 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_sign_jwt_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SignJwt +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_SignJwt_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_sign_jwt(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.SignJwtRequest( + name="name_value", + payload="payload_value", + ) + + # Make the request + response = await client.sign_jwt(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_SignJwt_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_sign_jwt_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_sign_jwt_sync.py new file mode 100644 index 000000000000..a35e6a88d415 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_sign_jwt_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SignJwt +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_SignJwt_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_sign_jwt(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.SignJwtRequest( + name="name_value", + payload="payload_value", + ) + + # Make the request + response = client.sign_jwt(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_SignJwt_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_test_iam_permissions_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_test_iam_permissions_async.py new file mode 100644 index 000000000000..67225e76cccd --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_test_iam_permissions_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_TestIamPermissions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +async def sample_test_iam_permissions(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = await client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_TestIamPermissions_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_test_iam_permissions_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_test_iam_permissions_sync.py new file mode 100644 index 000000000000..62f3747ea0da --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_test_iam_permissions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TestIamPermissions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_TestIamPermissions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore + + +def sample_test_iam_permissions(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + permissions=['permissions_value1', 'permissions_value2'], + ) + + # Make the request + response = client.test_iam_permissions(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_TestIamPermissions_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_undelete_role_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_undelete_role_async.py new file mode 100644 index 000000000000..432594ad2890 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_undelete_role_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UndeleteRole +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_UndeleteRole_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_undelete_role(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.UndeleteRoleRequest( + ) + + # Make the request + response = await client.undelete_role(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_UndeleteRole_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_undelete_role_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_undelete_role_sync.py new file mode 100644 index 000000000000..f7f910fbf5f9 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_undelete_role_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UndeleteRole +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_UndeleteRole_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_undelete_role(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.UndeleteRoleRequest( + ) + + # Make the request + response = client.undelete_role(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_UndeleteRole_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_undelete_service_account_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_undelete_service_account_async.py new file mode 100644 index 000000000000..2f9eecf8367a --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_undelete_service_account_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UndeleteServiceAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_UndeleteServiceAccount_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_undelete_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.UndeleteServiceAccountRequest( + ) + + # Make the request + response = await client.undelete_service_account(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_UndeleteServiceAccount_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_undelete_service_account_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_undelete_service_account_sync.py new file mode 100644 index 000000000000..523be3d4d766 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_undelete_service_account_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UndeleteServiceAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_UndeleteServiceAccount_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_undelete_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.UndeleteServiceAccountRequest( + ) + + # Make the request + response = client.undelete_service_account(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_UndeleteServiceAccount_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_update_role_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_update_role_async.py new file mode 100644 index 000000000000..5c52c05c319a --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_update_role_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateRole +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_UpdateRole_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_update_role(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.UpdateRoleRequest( + ) + + # Make the request + response = await client.update_role(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_UpdateRole_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_update_role_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_update_role_sync.py new file mode 100644 index 000000000000..f13ce735aa11 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_update_role_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateRole +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_UpdateRole_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_update_role(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.UpdateRoleRequest( + ) + + # Make the request + response = client.update_role(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_UpdateRole_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_update_service_account_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_update_service_account_async.py new file mode 100644 index 000000000000..ef6f5980864f --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_update_service_account_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateServiceAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_UpdateServiceAccount_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_update_service_account(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.ServiceAccount( + ) + + # Make the request + response = await client.update_service_account(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_UpdateServiceAccount_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_update_service_account_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_update_service_account_sync.py new file mode 100644 index 000000000000..1715240f6b55 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_update_service_account_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateServiceAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_UpdateServiceAccount_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_update_service_account(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.ServiceAccount( + ) + + # Make the request + response = client.update_service_account(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_UpdateServiceAccount_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_upload_service_account_key_async.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_upload_service_account_key_async.py new file mode 100644 index 000000000000..3c12d555d32d --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_upload_service_account_key_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UploadServiceAccountKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_UploadServiceAccountKey_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +async def sample_upload_service_account_key(): + # Create a client + client = iam_admin_v1.IAMAsyncClient() + + # Initialize request argument(s) + request = iam_admin_v1.UploadServiceAccountKeyRequest( + ) + + # Make the request + response = await client.upload_service_account_key(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_UploadServiceAccountKey_async] diff --git a/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_upload_service_account_key_sync.py b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_upload_service_account_key_sync.py new file mode 100644 index 000000000000..e7442facbbf1 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/iam_v1_generated_iam_upload_service_account_key_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UploadServiceAccountKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-iam + + +# [START iam_v1_generated_IAM_UploadServiceAccountKey_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import iam_admin_v1 + + +def sample_upload_service_account_key(): + # Create a client + client = iam_admin_v1.IAMClient() + + # Initialize request argument(s) + request = iam_admin_v1.UploadServiceAccountKeyRequest( + ) + + # Make the request + response = client.upload_service_account_key(request=request) + + # Handle the response + print(response) + +# [END iam_v1_generated_IAM_UploadServiceAccountKey_sync] diff --git a/packages/google-cloud-iam/samples/generated_samples/snippet_metadata_google.iam.admin.v1.json b/packages/google-cloud-iam/samples/generated_samples/snippet_metadata_google.iam.admin.v1.json new file mode 100644 index 000000000000..13547dc8e5e6 --- /dev/null +++ b/packages/google-cloud-iam/samples/generated_samples/snippet_metadata_google.iam.admin.v1.json @@ -0,0 +1,4922 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.iam.admin.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-iam", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.create_role", + "method": { + "fullName": "google.iam.admin.v1.IAM.CreateRole", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "CreateRole" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.CreateRoleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.Role", + "shortName": "create_role" + }, + "description": "Sample for CreateRole", + "file": "iam_v1_generated_iam_create_role_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_CreateRole_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": "iam_v1_generated_iam_create_role_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.create_role", + "method": { + "fullName": "google.iam.admin.v1.IAM.CreateRole", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "CreateRole" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.CreateRoleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.Role", + "shortName": "create_role" + }, + "description": "Sample for CreateRole", + "file": "iam_v1_generated_iam_create_role_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_CreateRole_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": "iam_v1_generated_iam_create_role_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.create_service_account_key", + "method": { + "fullName": "google.iam.admin.v1.IAM.CreateServiceAccountKey", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "CreateServiceAccountKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.CreateServiceAccountKeyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "private_key_type", + "type": "google.cloud.iam_admin_v1.types.ServiceAccountPrivateKeyType" + }, + { + "name": "key_algorithm", + "type": "google.cloud.iam_admin_v1.types.ServiceAccountKeyAlgorithm" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.ServiceAccountKey", + "shortName": "create_service_account_key" + }, + "description": "Sample for CreateServiceAccountKey", + "file": "iam_v1_generated_iam_create_service_account_key_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_CreateServiceAccountKey_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_create_service_account_key_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.create_service_account_key", + "method": { + "fullName": "google.iam.admin.v1.IAM.CreateServiceAccountKey", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "CreateServiceAccountKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.CreateServiceAccountKeyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "private_key_type", + "type": "google.cloud.iam_admin_v1.types.ServiceAccountPrivateKeyType" + }, + { + "name": "key_algorithm", + "type": "google.cloud.iam_admin_v1.types.ServiceAccountKeyAlgorithm" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.ServiceAccountKey", + "shortName": "create_service_account_key" + }, + "description": "Sample for CreateServiceAccountKey", + "file": "iam_v1_generated_iam_create_service_account_key_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_CreateServiceAccountKey_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_create_service_account_key_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.create_service_account", + "method": { + "fullName": "google.iam.admin.v1.IAM.CreateServiceAccount", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "CreateServiceAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.CreateServiceAccountRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "account_id", + "type": "str" + }, + { + "name": "service_account", + "type": "google.cloud.iam_admin_v1.types.ServiceAccount" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.ServiceAccount", + "shortName": "create_service_account" + }, + "description": "Sample for CreateServiceAccount", + "file": "iam_v1_generated_iam_create_service_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_CreateServiceAccount_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_create_service_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.create_service_account", + "method": { + "fullName": "google.iam.admin.v1.IAM.CreateServiceAccount", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "CreateServiceAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.CreateServiceAccountRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "account_id", + "type": "str" + }, + { + "name": "service_account", + "type": "google.cloud.iam_admin_v1.types.ServiceAccount" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.ServiceAccount", + "shortName": "create_service_account" + }, + "description": "Sample for CreateServiceAccount", + "file": "iam_v1_generated_iam_create_service_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_CreateServiceAccount_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_create_service_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.delete_role", + "method": { + "fullName": "google.iam.admin.v1.IAM.DeleteRole", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "DeleteRole" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.DeleteRoleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.Role", + "shortName": "delete_role" + }, + "description": "Sample for DeleteRole", + "file": "iam_v1_generated_iam_delete_role_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_DeleteRole_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": "iam_v1_generated_iam_delete_role_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.delete_role", + "method": { + "fullName": "google.iam.admin.v1.IAM.DeleteRole", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "DeleteRole" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.DeleteRoleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.Role", + "shortName": "delete_role" + }, + "description": "Sample for DeleteRole", + "file": "iam_v1_generated_iam_delete_role_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_DeleteRole_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": "iam_v1_generated_iam_delete_role_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.delete_service_account_key", + "method": { + "fullName": "google.iam.admin.v1.IAM.DeleteServiceAccountKey", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "DeleteServiceAccountKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.DeleteServiceAccountKeyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_service_account_key" + }, + "description": "Sample for DeleteServiceAccountKey", + "file": "iam_v1_generated_iam_delete_service_account_key_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_DeleteServiceAccountKey_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_delete_service_account_key_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.delete_service_account_key", + "method": { + "fullName": "google.iam.admin.v1.IAM.DeleteServiceAccountKey", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "DeleteServiceAccountKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.DeleteServiceAccountKeyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_service_account_key" + }, + "description": "Sample for DeleteServiceAccountKey", + "file": "iam_v1_generated_iam_delete_service_account_key_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_DeleteServiceAccountKey_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_delete_service_account_key_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.delete_service_account", + "method": { + "fullName": "google.iam.admin.v1.IAM.DeleteServiceAccount", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "DeleteServiceAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.DeleteServiceAccountRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_service_account" + }, + "description": "Sample for DeleteServiceAccount", + "file": "iam_v1_generated_iam_delete_service_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_DeleteServiceAccount_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_delete_service_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.delete_service_account", + "method": { + "fullName": "google.iam.admin.v1.IAM.DeleteServiceAccount", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "DeleteServiceAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.DeleteServiceAccountRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_service_account" + }, + "description": "Sample for DeleteServiceAccount", + "file": "iam_v1_generated_iam_delete_service_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_DeleteServiceAccount_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_delete_service_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.disable_service_account_key", + "method": { + "fullName": "google.iam.admin.v1.IAM.DisableServiceAccountKey", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "DisableServiceAccountKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.DisableServiceAccountKeyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "disable_service_account_key" + }, + "description": "Sample for DisableServiceAccountKey", + "file": "iam_v1_generated_iam_disable_service_account_key_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_DisableServiceAccountKey_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_disable_service_account_key_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.disable_service_account_key", + "method": { + "fullName": "google.iam.admin.v1.IAM.DisableServiceAccountKey", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "DisableServiceAccountKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.DisableServiceAccountKeyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "disable_service_account_key" + }, + "description": "Sample for DisableServiceAccountKey", + "file": "iam_v1_generated_iam_disable_service_account_key_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_DisableServiceAccountKey_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_disable_service_account_key_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.disable_service_account", + "method": { + "fullName": "google.iam.admin.v1.IAM.DisableServiceAccount", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "DisableServiceAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.DisableServiceAccountRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "disable_service_account" + }, + "description": "Sample for DisableServiceAccount", + "file": "iam_v1_generated_iam_disable_service_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_DisableServiceAccount_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_disable_service_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.disable_service_account", + "method": { + "fullName": "google.iam.admin.v1.IAM.DisableServiceAccount", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "DisableServiceAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.DisableServiceAccountRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "disable_service_account" + }, + "description": "Sample for DisableServiceAccount", + "file": "iam_v1_generated_iam_disable_service_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_DisableServiceAccount_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_disable_service_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.enable_service_account_key", + "method": { + "fullName": "google.iam.admin.v1.IAM.EnableServiceAccountKey", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "EnableServiceAccountKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.EnableServiceAccountKeyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "enable_service_account_key" + }, + "description": "Sample for EnableServiceAccountKey", + "file": "iam_v1_generated_iam_enable_service_account_key_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_EnableServiceAccountKey_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_enable_service_account_key_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.enable_service_account_key", + "method": { + "fullName": "google.iam.admin.v1.IAM.EnableServiceAccountKey", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "EnableServiceAccountKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.EnableServiceAccountKeyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "enable_service_account_key" + }, + "description": "Sample for EnableServiceAccountKey", + "file": "iam_v1_generated_iam_enable_service_account_key_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_EnableServiceAccountKey_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_enable_service_account_key_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.enable_service_account", + "method": { + "fullName": "google.iam.admin.v1.IAM.EnableServiceAccount", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "EnableServiceAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.EnableServiceAccountRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "enable_service_account" + }, + "description": "Sample for EnableServiceAccount", + "file": "iam_v1_generated_iam_enable_service_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_EnableServiceAccount_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_enable_service_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.enable_service_account", + "method": { + "fullName": "google.iam.admin.v1.IAM.EnableServiceAccount", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "EnableServiceAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.EnableServiceAccountRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "enable_service_account" + }, + "description": "Sample for EnableServiceAccount", + "file": "iam_v1_generated_iam_enable_service_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_EnableServiceAccount_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_enable_service_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.get_iam_policy", + "method": { + "fullName": "google.iam.admin.v1.IAM.GetIamPolicy", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "iam_v1_generated_iam_get_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_GetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_get_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.get_iam_policy", + "method": { + "fullName": "google.iam.admin.v1.IAM.GetIamPolicy", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "GetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "get_iam_policy" + }, + "description": "Sample for GetIamPolicy", + "file": "iam_v1_generated_iam_get_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.get_role", + "method": { + "fullName": "google.iam.admin.v1.IAM.GetRole", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "GetRole" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.GetRoleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.Role", + "shortName": "get_role" + }, + "description": "Sample for GetRole", + "file": "iam_v1_generated_iam_get_role_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_GetRole_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": "iam_v1_generated_iam_get_role_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.get_role", + "method": { + "fullName": "google.iam.admin.v1.IAM.GetRole", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "GetRole" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.GetRoleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.Role", + "shortName": "get_role" + }, + "description": "Sample for GetRole", + "file": "iam_v1_generated_iam_get_role_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_GetRole_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": "iam_v1_generated_iam_get_role_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.get_service_account_key", + "method": { + "fullName": "google.iam.admin.v1.IAM.GetServiceAccountKey", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "GetServiceAccountKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.GetServiceAccountKeyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "public_key_type", + "type": "google.cloud.iam_admin_v1.types.ServiceAccountPublicKeyType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.ServiceAccountKey", + "shortName": "get_service_account_key" + }, + "description": "Sample for GetServiceAccountKey", + "file": "iam_v1_generated_iam_get_service_account_key_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_GetServiceAccountKey_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_get_service_account_key_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.get_service_account_key", + "method": { + "fullName": "google.iam.admin.v1.IAM.GetServiceAccountKey", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "GetServiceAccountKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.GetServiceAccountKeyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "public_key_type", + "type": "google.cloud.iam_admin_v1.types.ServiceAccountPublicKeyType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.ServiceAccountKey", + "shortName": "get_service_account_key" + }, + "description": "Sample for GetServiceAccountKey", + "file": "iam_v1_generated_iam_get_service_account_key_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_GetServiceAccountKey_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_get_service_account_key_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.get_service_account", + "method": { + "fullName": "google.iam.admin.v1.IAM.GetServiceAccount", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "GetServiceAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.GetServiceAccountRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.ServiceAccount", + "shortName": "get_service_account" + }, + "description": "Sample for GetServiceAccount", + "file": "iam_v1_generated_iam_get_service_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_GetServiceAccount_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_get_service_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.get_service_account", + "method": { + "fullName": "google.iam.admin.v1.IAM.GetServiceAccount", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "GetServiceAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.GetServiceAccountRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.ServiceAccount", + "shortName": "get_service_account" + }, + "description": "Sample for GetServiceAccount", + "file": "iam_v1_generated_iam_get_service_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_GetServiceAccount_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_get_service_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.lint_policy", + "method": { + "fullName": "google.iam.admin.v1.IAM.LintPolicy", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "LintPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.LintPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.LintPolicyResponse", + "shortName": "lint_policy" + }, + "description": "Sample for LintPolicy", + "file": "iam_v1_generated_iam_lint_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_LintPolicy_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": "iam_v1_generated_iam_lint_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.lint_policy", + "method": { + "fullName": "google.iam.admin.v1.IAM.LintPolicy", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "LintPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.LintPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.LintPolicyResponse", + "shortName": "lint_policy" + }, + "description": "Sample for LintPolicy", + "file": "iam_v1_generated_iam_lint_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_LintPolicy_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": "iam_v1_generated_iam_lint_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.list_roles", + "method": { + "fullName": "google.iam.admin.v1.IAM.ListRoles", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "ListRoles" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.ListRolesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.services.iam.pagers.ListRolesAsyncPager", + "shortName": "list_roles" + }, + "description": "Sample for ListRoles", + "file": "iam_v1_generated_iam_list_roles_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_ListRoles_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_list_roles_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.list_roles", + "method": { + "fullName": "google.iam.admin.v1.IAM.ListRoles", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "ListRoles" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.ListRolesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.services.iam.pagers.ListRolesPager", + "shortName": "list_roles" + }, + "description": "Sample for ListRoles", + "file": "iam_v1_generated_iam_list_roles_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_ListRoles_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_list_roles_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.list_service_account_keys", + "method": { + "fullName": "google.iam.admin.v1.IAM.ListServiceAccountKeys", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "ListServiceAccountKeys" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.ListServiceAccountKeysRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "key_types", + "type": "MutableSequence[google.cloud.iam_admin_v1.types.ListServiceAccountKeysRequest.KeyType]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.ListServiceAccountKeysResponse", + "shortName": "list_service_account_keys" + }, + "description": "Sample for ListServiceAccountKeys", + "file": "iam_v1_generated_iam_list_service_account_keys_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_ListServiceAccountKeys_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_list_service_account_keys_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.list_service_account_keys", + "method": { + "fullName": "google.iam.admin.v1.IAM.ListServiceAccountKeys", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "ListServiceAccountKeys" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.ListServiceAccountKeysRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "key_types", + "type": "MutableSequence[google.cloud.iam_admin_v1.types.ListServiceAccountKeysRequest.KeyType]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.ListServiceAccountKeysResponse", + "shortName": "list_service_account_keys" + }, + "description": "Sample for ListServiceAccountKeys", + "file": "iam_v1_generated_iam_list_service_account_keys_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_ListServiceAccountKeys_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_list_service_account_keys_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.list_service_accounts", + "method": { + "fullName": "google.iam.admin.v1.IAM.ListServiceAccounts", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "ListServiceAccounts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.ListServiceAccountsRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.services.iam.pagers.ListServiceAccountsAsyncPager", + "shortName": "list_service_accounts" + }, + "description": "Sample for ListServiceAccounts", + "file": "iam_v1_generated_iam_list_service_accounts_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_ListServiceAccounts_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_list_service_accounts_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.list_service_accounts", + "method": { + "fullName": "google.iam.admin.v1.IAM.ListServiceAccounts", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "ListServiceAccounts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.ListServiceAccountsRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.services.iam.pagers.ListServiceAccountsPager", + "shortName": "list_service_accounts" + }, + "description": "Sample for ListServiceAccounts", + "file": "iam_v1_generated_iam_list_service_accounts_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_ListServiceAccounts_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_list_service_accounts_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.patch_service_account", + "method": { + "fullName": "google.iam.admin.v1.IAM.PatchServiceAccount", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "PatchServiceAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.PatchServiceAccountRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.ServiceAccount", + "shortName": "patch_service_account" + }, + "description": "Sample for PatchServiceAccount", + "file": "iam_v1_generated_iam_patch_service_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_PatchServiceAccount_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": "iam_v1_generated_iam_patch_service_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.patch_service_account", + "method": { + "fullName": "google.iam.admin.v1.IAM.PatchServiceAccount", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "PatchServiceAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.PatchServiceAccountRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.ServiceAccount", + "shortName": "patch_service_account" + }, + "description": "Sample for PatchServiceAccount", + "file": "iam_v1_generated_iam_patch_service_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_PatchServiceAccount_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": "iam_v1_generated_iam_patch_service_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.query_auditable_services", + "method": { + "fullName": "google.iam.admin.v1.IAM.QueryAuditableServices", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "QueryAuditableServices" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.QueryAuditableServicesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.QueryAuditableServicesResponse", + "shortName": "query_auditable_services" + }, + "description": "Sample for QueryAuditableServices", + "file": "iam_v1_generated_iam_query_auditable_services_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_QueryAuditableServices_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": "iam_v1_generated_iam_query_auditable_services_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.query_auditable_services", + "method": { + "fullName": "google.iam.admin.v1.IAM.QueryAuditableServices", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "QueryAuditableServices" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.QueryAuditableServicesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.QueryAuditableServicesResponse", + "shortName": "query_auditable_services" + }, + "description": "Sample for QueryAuditableServices", + "file": "iam_v1_generated_iam_query_auditable_services_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_QueryAuditableServices_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": "iam_v1_generated_iam_query_auditable_services_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.query_grantable_roles", + "method": { + "fullName": "google.iam.admin.v1.IAM.QueryGrantableRoles", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "QueryGrantableRoles" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.QueryGrantableRolesRequest" + }, + { + "name": "full_resource_name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.services.iam.pagers.QueryGrantableRolesAsyncPager", + "shortName": "query_grantable_roles" + }, + "description": "Sample for QueryGrantableRoles", + "file": "iam_v1_generated_iam_query_grantable_roles_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_QueryGrantableRoles_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_query_grantable_roles_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.query_grantable_roles", + "method": { + "fullName": "google.iam.admin.v1.IAM.QueryGrantableRoles", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "QueryGrantableRoles" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.QueryGrantableRolesRequest" + }, + { + "name": "full_resource_name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.services.iam.pagers.QueryGrantableRolesPager", + "shortName": "query_grantable_roles" + }, + "description": "Sample for QueryGrantableRoles", + "file": "iam_v1_generated_iam_query_grantable_roles_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_QueryGrantableRoles_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_query_grantable_roles_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.query_testable_permissions", + "method": { + "fullName": "google.iam.admin.v1.IAM.QueryTestablePermissions", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "QueryTestablePermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.QueryTestablePermissionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.services.iam.pagers.QueryTestablePermissionsAsyncPager", + "shortName": "query_testable_permissions" + }, + "description": "Sample for QueryTestablePermissions", + "file": "iam_v1_generated_iam_query_testable_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_QueryTestablePermissions_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_query_testable_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.query_testable_permissions", + "method": { + "fullName": "google.iam.admin.v1.IAM.QueryTestablePermissions", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "QueryTestablePermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.QueryTestablePermissionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.services.iam.pagers.QueryTestablePermissionsPager", + "shortName": "query_testable_permissions" + }, + "description": "Sample for QueryTestablePermissions", + "file": "iam_v1_generated_iam_query_testable_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_QueryTestablePermissions_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_query_testable_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.set_iam_policy", + "method": { + "fullName": "google.iam.admin.v1.IAM.SetIamPolicy", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "iam_v1_generated_iam_set_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_SetIamPolicy_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_set_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.set_iam_policy", + "method": { + "fullName": "google.iam.admin.v1.IAM.SetIamPolicy", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "SetIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.policy_pb2.Policy", + "shortName": "set_iam_policy" + }, + "description": "Sample for SetIamPolicy", + "file": "iam_v1_generated_iam_set_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_SetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_set_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.sign_blob", + "method": { + "fullName": "google.iam.admin.v1.IAM.SignBlob", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "SignBlob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.SignBlobRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "bytes_to_sign", + "type": "bytes" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.SignBlobResponse", + "shortName": "sign_blob" + }, + "description": "Sample for SignBlob", + "file": "iam_v1_generated_iam_sign_blob_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_SignBlob_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_sign_blob_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.sign_blob", + "method": { + "fullName": "google.iam.admin.v1.IAM.SignBlob", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "SignBlob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.SignBlobRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "bytes_to_sign", + "type": "bytes" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.SignBlobResponse", + "shortName": "sign_blob" + }, + "description": "Sample for SignBlob", + "file": "iam_v1_generated_iam_sign_blob_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_SignBlob_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_sign_blob_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.sign_jwt", + "method": { + "fullName": "google.iam.admin.v1.IAM.SignJwt", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "SignJwt" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.SignJwtRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "payload", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.SignJwtResponse", + "shortName": "sign_jwt" + }, + "description": "Sample for SignJwt", + "file": "iam_v1_generated_iam_sign_jwt_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_SignJwt_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_sign_jwt_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.sign_jwt", + "method": { + "fullName": "google.iam.admin.v1.IAM.SignJwt", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "SignJwt" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.SignJwtRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "payload", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.SignJwtResponse", + "shortName": "sign_jwt" + }, + "description": "Sample for SignJwt", + "file": "iam_v1_generated_iam_sign_jwt_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_SignJwt_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_sign_jwt_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.test_iam_permissions", + "method": { + "fullName": "google.iam.admin.v1.IAM.TestIamPermissions", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "iam_v1_generated_iam_test_iam_permissions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_TestIamPermissions_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_test_iam_permissions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.test_iam_permissions", + "method": { + "fullName": "google.iam.admin.v1.IAM.TestIamPermissions", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "permissions", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "iam_v1_generated_iam_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_TestIamPermissions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 41, + "start": 39, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 42, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "iam_v1_generated_iam_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.undelete_role", + "method": { + "fullName": "google.iam.admin.v1.IAM.UndeleteRole", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "UndeleteRole" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.UndeleteRoleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.Role", + "shortName": "undelete_role" + }, + "description": "Sample for UndeleteRole", + "file": "iam_v1_generated_iam_undelete_role_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_UndeleteRole_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": "iam_v1_generated_iam_undelete_role_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.undelete_role", + "method": { + "fullName": "google.iam.admin.v1.IAM.UndeleteRole", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "UndeleteRole" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.UndeleteRoleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.Role", + "shortName": "undelete_role" + }, + "description": "Sample for UndeleteRole", + "file": "iam_v1_generated_iam_undelete_role_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_UndeleteRole_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": "iam_v1_generated_iam_undelete_role_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.undelete_service_account", + "method": { + "fullName": "google.iam.admin.v1.IAM.UndeleteServiceAccount", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "UndeleteServiceAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.UndeleteServiceAccountRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.UndeleteServiceAccountResponse", + "shortName": "undelete_service_account" + }, + "description": "Sample for UndeleteServiceAccount", + "file": "iam_v1_generated_iam_undelete_service_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_UndeleteServiceAccount_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": "iam_v1_generated_iam_undelete_service_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.undelete_service_account", + "method": { + "fullName": "google.iam.admin.v1.IAM.UndeleteServiceAccount", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "UndeleteServiceAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.UndeleteServiceAccountRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.UndeleteServiceAccountResponse", + "shortName": "undelete_service_account" + }, + "description": "Sample for UndeleteServiceAccount", + "file": "iam_v1_generated_iam_undelete_service_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_UndeleteServiceAccount_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": "iam_v1_generated_iam_undelete_service_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.update_role", + "method": { + "fullName": "google.iam.admin.v1.IAM.UpdateRole", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "UpdateRole" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.UpdateRoleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.Role", + "shortName": "update_role" + }, + "description": "Sample for UpdateRole", + "file": "iam_v1_generated_iam_update_role_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_UpdateRole_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": "iam_v1_generated_iam_update_role_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.update_role", + "method": { + "fullName": "google.iam.admin.v1.IAM.UpdateRole", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "UpdateRole" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.UpdateRoleRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.Role", + "shortName": "update_role" + }, + "description": "Sample for UpdateRole", + "file": "iam_v1_generated_iam_update_role_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_UpdateRole_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": "iam_v1_generated_iam_update_role_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.update_service_account", + "method": { + "fullName": "google.iam.admin.v1.IAM.UpdateServiceAccount", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "UpdateServiceAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.ServiceAccount" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.ServiceAccount", + "shortName": "update_service_account" + }, + "description": "Sample for UpdateServiceAccount", + "file": "iam_v1_generated_iam_update_service_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_UpdateServiceAccount_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": "iam_v1_generated_iam_update_service_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.update_service_account", + "method": { + "fullName": "google.iam.admin.v1.IAM.UpdateServiceAccount", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "UpdateServiceAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.ServiceAccount" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.ServiceAccount", + "shortName": "update_service_account" + }, + "description": "Sample for UpdateServiceAccount", + "file": "iam_v1_generated_iam_update_service_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_UpdateServiceAccount_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": "iam_v1_generated_iam_update_service_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient", + "shortName": "IAMAsyncClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMAsyncClient.upload_service_account_key", + "method": { + "fullName": "google.iam.admin.v1.IAM.UploadServiceAccountKey", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "UploadServiceAccountKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.UploadServiceAccountKeyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.ServiceAccountKey", + "shortName": "upload_service_account_key" + }, + "description": "Sample for UploadServiceAccountKey", + "file": "iam_v1_generated_iam_upload_service_account_key_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_UploadServiceAccountKey_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": "iam_v1_generated_iam_upload_service_account_key_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.iam_admin_v1.IAMClient", + "shortName": "IAMClient" + }, + "fullName": "google.cloud.iam_admin_v1.IAMClient.upload_service_account_key", + "method": { + "fullName": "google.iam.admin.v1.IAM.UploadServiceAccountKey", + "service": { + "fullName": "google.iam.admin.v1.IAM", + "shortName": "IAM" + }, + "shortName": "UploadServiceAccountKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.iam_admin_v1.types.UploadServiceAccountKeyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.iam_admin_v1.types.ServiceAccountKey", + "shortName": "upload_service_account_key" + }, + "description": "Sample for UploadServiceAccountKey", + "file": "iam_v1_generated_iam_upload_service_account_key_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "iam_v1_generated_IAM_UploadServiceAccountKey_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": "iam_v1_generated_iam_upload_service_account_key_sync.py" + } + ] +} diff --git a/packages/google-cloud-iam/scripts/fixup_iam_admin_v1_keywords.py b/packages/google-cloud-iam/scripts/fixup_iam_admin_v1_keywords.py new file mode 100644 index 000000000000..0e36eac17726 --- /dev/null +++ b/packages/google-cloud-iam/scripts/fixup_iam_admin_v1_keywords.py @@ -0,0 +1,206 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class iam_adminCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_role': ('parent', 'role_id', 'role', ), + 'create_service_account': ('name', 'account_id', 'service_account', ), + 'create_service_account_key': ('name', 'private_key_type', 'key_algorithm', ), + 'delete_role': ('name', 'etag', ), + 'delete_service_account': ('name', ), + 'delete_service_account_key': ('name', ), + 'disable_service_account': ('name', ), + 'disable_service_account_key': ('name', ), + 'enable_service_account': ('name', ), + 'enable_service_account_key': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'get_role': ('name', ), + 'get_service_account': ('name', ), + 'get_service_account_key': ('name', 'public_key_type', ), + 'lint_policy': ('full_resource_name', 'condition', ), + 'list_roles': ('parent', 'page_size', 'page_token', 'view', 'show_deleted', ), + 'list_service_account_keys': ('name', 'key_types', ), + 'list_service_accounts': ('name', 'page_size', 'page_token', ), + 'patch_service_account': ('service_account', 'update_mask', ), + 'query_auditable_services': ('full_resource_name', ), + 'query_grantable_roles': ('full_resource_name', 'view', 'page_size', 'page_token', ), + 'query_testable_permissions': ('full_resource_name', 'page_size', 'page_token', ), + 'set_iam_policy': ('resource', 'policy', 'update_mask', ), + 'sign_blob': ('name', 'bytes_to_sign', ), + 'sign_jwt': ('name', 'payload', ), + 'test_iam_permissions': ('resource', 'permissions', ), + 'undelete_role': ('name', 'etag', ), + 'undelete_service_account': ('name', ), + 'update_role': ('name', 'role', 'update_mask', ), + 'update_service_account': ('name', 'project_id', 'unique_id', 'email', 'display_name', 'etag', 'description', 'oauth2_client_id', 'disabled', ), + 'upload_service_account_key': ('name', 'public_key_data', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=iam_adminCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the iam_admin client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/packages/google-cloud-iam/setup.py b/packages/google-cloud-iam/setup.py index 9d37a1f76d99..1330538510c3 100644 --- a/packages/google-cloud-iam/setup.py +++ b/packages/google-cloud-iam/setup.py @@ -47,6 +47,7 @@ "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", "proto-plus >= 1.22.3, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", ] url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-iam" diff --git a/packages/google-cloud-iam/testing/constraints-3.7.txt b/packages/google-cloud-iam/testing/constraints-3.7.txt index b8a550c73855..4cd2782277d4 100644 --- a/packages/google-cloud-iam/testing/constraints-3.7.txt +++ b/packages/google-cloud-iam/testing/constraints-3.7.txt @@ -8,3 +8,4 @@ google-api-core==1.34.1 google-auth==2.14.1 proto-plus==1.22.3 protobuf==3.19.5 +grpc-google-iam-v1==0.12.4 diff --git a/packages/google-cloud-iam/tests/unit/gapic/iam_admin_v1/__init__.py b/packages/google-cloud-iam/tests/unit/gapic/iam_admin_v1/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/packages/google-cloud-iam/tests/unit/gapic/iam_admin_v1/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/google-cloud-iam/tests/unit/gapic/iam_admin_v1/test_iam.py b/packages/google-cloud-iam/tests/unit/gapic/iam_admin_v1/test_iam.py new file mode 100644 index 000000000000..874db329d3b1 --- /dev/null +++ b/packages/google-cloud-iam/tests/unit/gapic/iam_admin_v1/test_iam.py @@ -0,0 +1,10504 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import math + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import api_core_version, client_options +from google.api_core import exceptions as core_exceptions +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest + +from google.cloud.iam_admin_v1.services.iam import ( + IAMAsyncClient, + IAMClient, + pagers, + transports, +) +from google.cloud.iam_admin_v1.types import iam + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert IAMClient._get_default_mtls_endpoint(None) is None + assert IAMClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert IAMClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ( + IAMClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + ) + assert ( + IAMClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert IAMClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +def test__read_environment_variables(): + assert IAMClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert IAMClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert IAMClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + IAMClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert IAMClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert IAMClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert IAMClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + IAMClient._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 IAMClient._read_environment_variables() == (False, "auto", "foo.com") + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert IAMClient._get_client_cert_source(None, False) is None + assert IAMClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ( + IAMClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + IAMClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + IAMClient._get_client_cert_source(mock_provided_cert_source, "true") + is mock_provided_cert_source + ) + + +@mock.patch.object( + IAMClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IAMClient) +) +@mock.patch.object( + IAMAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(IAMAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = IAMClient._DEFAULT_UNIVERSE + default_endpoint = IAMClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = IAMClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + IAMClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + IAMClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == IAMClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + IAMClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + IAMClient._get_api_endpoint(None, None, default_universe, "always") + == IAMClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + IAMClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == IAMClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + IAMClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + ) + assert ( + IAMClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + IAMClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + IAMClient._get_universe_domain(client_universe_domain, universe_domain_env) + == client_universe_domain + ) + assert ( + IAMClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + ) + assert IAMClient._get_universe_domain(None, None) == IAMClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + IAMClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (IAMClient, transports.IAMGrpcTransport, "grpc"), + ], +) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel( + "http://localhost/", grpc.local_channel_credentials() + ) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel( + "http://localhost/", grpc.local_channel_credentials() + ) + transport = transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [ + int(part) for part in google.auth.__version__.split(".")[0:2] + ] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class(transport=transport_class(credentials=credentials)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert ( + str(excinfo.value) + == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + ) + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [ + int(part) for part in api_core_version.__version__.split(".")[0:2] + ] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class( + client_options={"universe_domain": "bar.com"}, + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials(), + ), + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert ( + str(excinfo.value) + == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + ) + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (IAMClient, "grpc"), + (IAMAsyncClient, "grpc_asyncio"), + ], +) +def test_iam_client_from_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 == ("iam.googleapis.com:443") + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.IAMGrpcTransport, "grpc"), + (transports.IAMGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_iam_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + 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", + [ + (IAMClient, "grpc"), + (IAMAsyncClient, "grpc_asyncio"), + ], +) +def test_iam_client_from_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 == ("iam.googleapis.com:443") + + +def test_iam_client_get_transport_class(): + transport = IAMClient.get_transport_class() + available_transports = [ + transports.IAMGrpcTransport, + ] + assert transport in available_transports + + transport = IAMClient.get_transport_class("grpc") + assert transport == transports.IAMGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (IAMClient, transports.IAMGrpcTransport, "grpc"), + (IAMAsyncClient, transports.IAMGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +@mock.patch.object( + IAMClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IAMClient) +) +@mock.patch.object( + IAMAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(IAMAsyncClient), +) +def test_iam_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(IAMClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(IAMClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (IAMClient, transports.IAMGrpcTransport, "grpc", "true"), + (IAMAsyncClient, transports.IAMGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (IAMClient, transports.IAMGrpcTransport, "grpc", "false"), + (IAMAsyncClient, transports.IAMGrpcAsyncIOTransport, "grpc_asyncio", "false"), + ], +) +@mock.patch.object( + IAMClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IAMClient) +) +@mock.patch.object( + IAMAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(IAMAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_iam_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_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", [IAMClient, IAMAsyncClient]) +@mock.patch.object(IAMClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IAMClient)) +@mock.patch.object( + IAMAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(IAMAsyncClient) +) +def test_iam_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize("client_class", [IAMClient, IAMAsyncClient]) +@mock.patch.object( + IAMClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(IAMClient) +) +@mock.patch.object( + IAMAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(IAMAsyncClient), +) +def test_iam_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = IAMClient._DEFAULT_UNIVERSE + default_endpoint = IAMClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = IAMClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + 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", + [ + (IAMClient, transports.IAMGrpcTransport, "grpc"), + (IAMAsyncClient, transports.IAMGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_iam_client_client_options_scopes( + client_class, transport_class, 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", + [ + (IAMClient, transports.IAMGrpcTransport, "grpc", grpc_helpers), + ( + IAMAsyncClient, + transports.IAMGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_iam_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_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_iam_client_client_options_from_dict(): + with mock.patch( + "google.cloud.iam_admin_v1.services.iam.transports.IAMGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = IAMClient(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", + [ + (IAMClient, transports.IAMGrpcTransport, "grpc", grpc_helpers), + ( + IAMAsyncClient, + transports.IAMGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_iam_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_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( + "iam.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="iam.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam.ListServiceAccountsRequest, + dict, + ], +) +def test_list_service_accounts(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_accounts), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ListServiceAccountsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_service_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.ListServiceAccountsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServiceAccountsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_service_accounts_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_accounts), "__call__" + ) as call: + client.list_service_accounts() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.ListServiceAccountsRequest() + + +def test_list_service_accounts_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.ListServiceAccountsRequest( + name="name_value", + 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_service_accounts), "__call__" + ) as call: + client.list_service_accounts(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.ListServiceAccountsRequest( + name="name_value", + page_token="page_token_value", + ) + + +@pytest.mark.asyncio +async def test_list_service_accounts_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_accounts), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ListServiceAccountsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_service_accounts() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.ListServiceAccountsRequest() + + +@pytest.mark.asyncio +async def test_list_service_accounts_async( + transport: str = "grpc_asyncio", request_type=iam.ListServiceAccountsRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_accounts), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ListServiceAccountsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_service_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.ListServiceAccountsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServiceAccountsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_service_accounts_async_from_dict(): + await test_list_service_accounts_async(request_type=dict) + + +def test_list_service_accounts_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ListServiceAccountsRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_accounts), "__call__" + ) as call: + call.return_value = iam.ListServiceAccountsResponse() + client.list_service_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_service_accounts_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ListServiceAccountsRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_accounts), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ListServiceAccountsResponse() + ) + await client.list_service_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_list_service_accounts_flattened(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_accounts), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ListServiceAccountsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_service_accounts( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_list_service_accounts_flattened_error(): + client = IAMClient( + credentials=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_service_accounts( + iam.ListServiceAccountsRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_list_service_accounts_flattened_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_accounts), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ListServiceAccountsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ListServiceAccountsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_service_accounts( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_service_accounts_flattened_error_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_service_accounts( + iam.ListServiceAccountsRequest(), + name="name_value", + ) + + +def test_list_service_accounts_pager(transport_name: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_accounts), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + iam.ListServiceAccountsResponse( + accounts=[ + iam.ServiceAccount(), + iam.ServiceAccount(), + iam.ServiceAccount(), + ], + next_page_token="abc", + ), + iam.ListServiceAccountsResponse( + accounts=[], + next_page_token="def", + ), + iam.ListServiceAccountsResponse( + accounts=[ + iam.ServiceAccount(), + ], + next_page_token="ghi", + ), + iam.ListServiceAccountsResponse( + accounts=[ + iam.ServiceAccount(), + iam.ServiceAccount(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", ""),)), + ) + pager = client.list_service_accounts(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, iam.ServiceAccount) for i in results) + + +def test_list_service_accounts_pages(transport_name: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_accounts), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + iam.ListServiceAccountsResponse( + accounts=[ + iam.ServiceAccount(), + iam.ServiceAccount(), + iam.ServiceAccount(), + ], + next_page_token="abc", + ), + iam.ListServiceAccountsResponse( + accounts=[], + next_page_token="def", + ), + iam.ListServiceAccountsResponse( + accounts=[ + iam.ServiceAccount(), + ], + next_page_token="ghi", + ), + iam.ListServiceAccountsResponse( + accounts=[ + iam.ServiceAccount(), + iam.ServiceAccount(), + ], + ), + RuntimeError, + ) + pages = list(client.list_service_accounts(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_service_accounts_async_pager(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_accounts), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + iam.ListServiceAccountsResponse( + accounts=[ + iam.ServiceAccount(), + iam.ServiceAccount(), + iam.ServiceAccount(), + ], + next_page_token="abc", + ), + iam.ListServiceAccountsResponse( + accounts=[], + next_page_token="def", + ), + iam.ListServiceAccountsResponse( + accounts=[ + iam.ServiceAccount(), + ], + next_page_token="ghi", + ), + iam.ListServiceAccountsResponse( + accounts=[ + iam.ServiceAccount(), + iam.ServiceAccount(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_service_accounts( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, iam.ServiceAccount) for i in responses) + + +@pytest.mark.asyncio +async def test_list_service_accounts_async_pages(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_accounts), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + iam.ListServiceAccountsResponse( + accounts=[ + iam.ServiceAccount(), + iam.ServiceAccount(), + iam.ServiceAccount(), + ], + next_page_token="abc", + ), + iam.ListServiceAccountsResponse( + accounts=[], + next_page_token="def", + ), + iam.ListServiceAccountsResponse( + accounts=[ + iam.ServiceAccount(), + ], + next_page_token="ghi", + ), + iam.ListServiceAccountsResponse( + accounts=[ + iam.ServiceAccount(), + iam.ServiceAccount(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_service_accounts(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + iam.GetServiceAccountRequest, + dict, + ], +) +def test_get_service_account(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ServiceAccount( + name="name_value", + project_id="project_id_value", + unique_id="unique_id_value", + email="email_value", + display_name="display_name_value", + etag=b"etag_blob", + description="description_value", + oauth2_client_id="oauth2_client_id_value", + disabled=True, + ) + response = client.get_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.GetServiceAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.ServiceAccount) + assert response.name == "name_value" + assert response.project_id == "project_id_value" + assert response.unique_id == "unique_id_value" + assert response.email == "email_value" + assert response.display_name == "display_name_value" + assert response.etag == b"etag_blob" + assert response.description == "description_value" + assert response.oauth2_client_id == "oauth2_client_id_value" + assert response.disabled is True + + +def test_get_service_account_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_account), "__call__" + ) as call: + client.get_service_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.GetServiceAccountRequest() + + +def test_get_service_account_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.GetServiceAccountRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_account), "__call__" + ) as call: + client.get_service_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.GetServiceAccountRequest( + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_service_account_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ServiceAccount( + name="name_value", + project_id="project_id_value", + unique_id="unique_id_value", + email="email_value", + display_name="display_name_value", + etag=b"etag_blob", + description="description_value", + oauth2_client_id="oauth2_client_id_value", + disabled=True, + ) + ) + response = await client.get_service_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.GetServiceAccountRequest() + + +@pytest.mark.asyncio +async def test_get_service_account_async( + transport: str = "grpc_asyncio", request_type=iam.GetServiceAccountRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ServiceAccount( + name="name_value", + project_id="project_id_value", + unique_id="unique_id_value", + email="email_value", + display_name="display_name_value", + etag=b"etag_blob", + description="description_value", + oauth2_client_id="oauth2_client_id_value", + disabled=True, + ) + ) + response = await client.get_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.GetServiceAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.ServiceAccount) + assert response.name == "name_value" + assert response.project_id == "project_id_value" + assert response.unique_id == "unique_id_value" + assert response.email == "email_value" + assert response.display_name == "display_name_value" + assert response.etag == b"etag_blob" + assert response.description == "description_value" + assert response.oauth2_client_id == "oauth2_client_id_value" + assert response.disabled is True + + +@pytest.mark.asyncio +async def test_get_service_account_async_from_dict(): + await test_get_service_account_async(request_type=dict) + + +def test_get_service_account_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.GetServiceAccountRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_account), "__call__" + ) as call: + call.return_value = iam.ServiceAccount() + client.get_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_service_account_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.GetServiceAccountRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_account), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam.ServiceAccount()) + await client.get_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_service_account_flattened(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ServiceAccount() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_service_account( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_service_account_flattened_error(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_service_account( + iam.GetServiceAccountRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_service_account_flattened_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ServiceAccount() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam.ServiceAccount()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_service_account( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_service_account_flattened_error_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_service_account( + iam.GetServiceAccountRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam.CreateServiceAccountRequest, + dict, + ], +) +def test_create_service_account(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ServiceAccount( + name="name_value", + project_id="project_id_value", + unique_id="unique_id_value", + email="email_value", + display_name="display_name_value", + etag=b"etag_blob", + description="description_value", + oauth2_client_id="oauth2_client_id_value", + disabled=True, + ) + response = client.create_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.CreateServiceAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.ServiceAccount) + assert response.name == "name_value" + assert response.project_id == "project_id_value" + assert response.unique_id == "unique_id_value" + assert response.email == "email_value" + assert response.display_name == "display_name_value" + assert response.etag == b"etag_blob" + assert response.description == "description_value" + assert response.oauth2_client_id == "oauth2_client_id_value" + assert response.disabled is True + + +def test_create_service_account_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_account), "__call__" + ) as call: + client.create_service_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.CreateServiceAccountRequest() + + +def test_create_service_account_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.CreateServiceAccountRequest( + name="name_value", + account_id="account_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_account), "__call__" + ) as call: + client.create_service_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.CreateServiceAccountRequest( + name="name_value", + account_id="account_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_service_account_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ServiceAccount( + name="name_value", + project_id="project_id_value", + unique_id="unique_id_value", + email="email_value", + display_name="display_name_value", + etag=b"etag_blob", + description="description_value", + oauth2_client_id="oauth2_client_id_value", + disabled=True, + ) + ) + response = await client.create_service_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.CreateServiceAccountRequest() + + +@pytest.mark.asyncio +async def test_create_service_account_async( + transport: str = "grpc_asyncio", request_type=iam.CreateServiceAccountRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ServiceAccount( + name="name_value", + project_id="project_id_value", + unique_id="unique_id_value", + email="email_value", + display_name="display_name_value", + etag=b"etag_blob", + description="description_value", + oauth2_client_id="oauth2_client_id_value", + disabled=True, + ) + ) + response = await client.create_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.CreateServiceAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.ServiceAccount) + assert response.name == "name_value" + assert response.project_id == "project_id_value" + assert response.unique_id == "unique_id_value" + assert response.email == "email_value" + assert response.display_name == "display_name_value" + assert response.etag == b"etag_blob" + assert response.description == "description_value" + assert response.oauth2_client_id == "oauth2_client_id_value" + assert response.disabled is True + + +@pytest.mark.asyncio +async def test_create_service_account_async_from_dict(): + await test_create_service_account_async(request_type=dict) + + +def test_create_service_account_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.CreateServiceAccountRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_account), "__call__" + ) as call: + call.return_value = iam.ServiceAccount() + client.create_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_service_account_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.CreateServiceAccountRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_account), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam.ServiceAccount()) + await client.create_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_create_service_account_flattened(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ServiceAccount() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_service_account( + name="name_value", + account_id="account_id_value", + service_account=iam.ServiceAccount(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].account_id + mock_val = "account_id_value" + assert arg == mock_val + arg = args[0].service_account + mock_val = iam.ServiceAccount(name="name_value") + assert arg == mock_val + + +def test_create_service_account_flattened_error(): + client = IAMClient( + credentials=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_service_account( + iam.CreateServiceAccountRequest(), + name="name_value", + account_id="account_id_value", + service_account=iam.ServiceAccount(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_service_account_flattened_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ServiceAccount() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam.ServiceAccount()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_service_account( + name="name_value", + account_id="account_id_value", + service_account=iam.ServiceAccount(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].account_id + mock_val = "account_id_value" + assert arg == mock_val + arg = args[0].service_account + mock_val = iam.ServiceAccount(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_service_account_flattened_error_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_service_account( + iam.CreateServiceAccountRequest(), + name="name_value", + account_id="account_id_value", + service_account=iam.ServiceAccount(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam.ServiceAccount, + dict, + ], +) +def test_update_service_account(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ServiceAccount( + name="name_value", + project_id="project_id_value", + unique_id="unique_id_value", + email="email_value", + display_name="display_name_value", + etag=b"etag_blob", + description="description_value", + oauth2_client_id="oauth2_client_id_value", + disabled=True, + ) + response = client.update_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.ServiceAccount() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.ServiceAccount) + assert response.name == "name_value" + assert response.project_id == "project_id_value" + assert response.unique_id == "unique_id_value" + assert response.email == "email_value" + assert response.display_name == "display_name_value" + assert response.etag == b"etag_blob" + assert response.description == "description_value" + assert response.oauth2_client_id == "oauth2_client_id_value" + assert response.disabled is True + + +def test_update_service_account_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service_account), "__call__" + ) as call: + client.update_service_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.ServiceAccount() + + +def test_update_service_account_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.ServiceAccount( + name="name_value", + project_id="project_id_value", + unique_id="unique_id_value", + email="email_value", + display_name="display_name_value", + description="description_value", + oauth2_client_id="oauth2_client_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service_account), "__call__" + ) as call: + client.update_service_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.ServiceAccount( + name="name_value", + project_id="project_id_value", + unique_id="unique_id_value", + email="email_value", + display_name="display_name_value", + description="description_value", + oauth2_client_id="oauth2_client_id_value", + ) + + +@pytest.mark.asyncio +async def test_update_service_account_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ServiceAccount( + name="name_value", + project_id="project_id_value", + unique_id="unique_id_value", + email="email_value", + display_name="display_name_value", + etag=b"etag_blob", + description="description_value", + oauth2_client_id="oauth2_client_id_value", + disabled=True, + ) + ) + response = await client.update_service_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.ServiceAccount() + + +@pytest.mark.asyncio +async def test_update_service_account_async( + transport: str = "grpc_asyncio", request_type=iam.ServiceAccount +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ServiceAccount( + name="name_value", + project_id="project_id_value", + unique_id="unique_id_value", + email="email_value", + display_name="display_name_value", + etag=b"etag_blob", + description="description_value", + oauth2_client_id="oauth2_client_id_value", + disabled=True, + ) + ) + response = await client.update_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.ServiceAccount() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.ServiceAccount) + assert response.name == "name_value" + assert response.project_id == "project_id_value" + assert response.unique_id == "unique_id_value" + assert response.email == "email_value" + assert response.display_name == "display_name_value" + assert response.etag == b"etag_blob" + assert response.description == "description_value" + assert response.oauth2_client_id == "oauth2_client_id_value" + assert response.disabled is True + + +@pytest.mark.asyncio +async def test_update_service_account_async_from_dict(): + await test_update_service_account_async(request_type=dict) + + +def test_update_service_account_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ServiceAccount() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service_account), "__call__" + ) as call: + call.return_value = iam.ServiceAccount() + client.update_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_service_account_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ServiceAccount() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_service_account), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam.ServiceAccount()) + await client.update_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + iam.PatchServiceAccountRequest, + dict, + ], +) +def test_patch_service_account(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.patch_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ServiceAccount( + name="name_value", + project_id="project_id_value", + unique_id="unique_id_value", + email="email_value", + display_name="display_name_value", + etag=b"etag_blob", + description="description_value", + oauth2_client_id="oauth2_client_id_value", + disabled=True, + ) + response = client.patch_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.PatchServiceAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.ServiceAccount) + assert response.name == "name_value" + assert response.project_id == "project_id_value" + assert response.unique_id == "unique_id_value" + assert response.email == "email_value" + assert response.display_name == "display_name_value" + assert response.etag == b"etag_blob" + assert response.description == "description_value" + assert response.oauth2_client_id == "oauth2_client_id_value" + assert response.disabled is True + + +def test_patch_service_account_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.patch_service_account), "__call__" + ) as call: + client.patch_service_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.PatchServiceAccountRequest() + + +def test_patch_service_account_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.PatchServiceAccountRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.patch_service_account), "__call__" + ) as call: + client.patch_service_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.PatchServiceAccountRequest() + + +@pytest.mark.asyncio +async def test_patch_service_account_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.patch_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ServiceAccount( + name="name_value", + project_id="project_id_value", + unique_id="unique_id_value", + email="email_value", + display_name="display_name_value", + etag=b"etag_blob", + description="description_value", + oauth2_client_id="oauth2_client_id_value", + disabled=True, + ) + ) + response = await client.patch_service_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.PatchServiceAccountRequest() + + +@pytest.mark.asyncio +async def test_patch_service_account_async( + transport: str = "grpc_asyncio", request_type=iam.PatchServiceAccountRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.patch_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ServiceAccount( + name="name_value", + project_id="project_id_value", + unique_id="unique_id_value", + email="email_value", + display_name="display_name_value", + etag=b"etag_blob", + description="description_value", + oauth2_client_id="oauth2_client_id_value", + disabled=True, + ) + ) + response = await client.patch_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.PatchServiceAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.ServiceAccount) + assert response.name == "name_value" + assert response.project_id == "project_id_value" + assert response.unique_id == "unique_id_value" + assert response.email == "email_value" + assert response.display_name == "display_name_value" + assert response.etag == b"etag_blob" + assert response.description == "description_value" + assert response.oauth2_client_id == "oauth2_client_id_value" + assert response.disabled is True + + +@pytest.mark.asyncio +async def test_patch_service_account_async_from_dict(): + await test_patch_service_account_async(request_type=dict) + + +def test_patch_service_account_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.PatchServiceAccountRequest() + + request.service_account.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.patch_service_account), "__call__" + ) as call: + call.return_value = iam.ServiceAccount() + client.patch_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "service_account.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_patch_service_account_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.PatchServiceAccountRequest() + + request.service_account.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.patch_service_account), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam.ServiceAccount()) + await client.patch_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "service_account.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + iam.DeleteServiceAccountRequest, + dict, + ], +) +def test_delete_service_account(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.DeleteServiceAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_service_account_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_account), "__call__" + ) as call: + client.delete_service_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.DeleteServiceAccountRequest() + + +def test_delete_service_account_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.DeleteServiceAccountRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_account), "__call__" + ) as call: + client.delete_service_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.DeleteServiceAccountRequest( + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_service_account_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_service_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.DeleteServiceAccountRequest() + + +@pytest.mark.asyncio +async def test_delete_service_account_async( + transport: str = "grpc_asyncio", request_type=iam.DeleteServiceAccountRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.DeleteServiceAccountRequest() + 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_service_account_async_from_dict(): + await test_delete_service_account_async(request_type=dict) + + +def test_delete_service_account_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.DeleteServiceAccountRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_account), "__call__" + ) as call: + call.return_value = None + client.delete_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_service_account_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.DeleteServiceAccountRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_account), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_service_account_flattened(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_service_account( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_service_account_flattened_error(): + client = IAMClient( + credentials=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_service_account( + iam.DeleteServiceAccountRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_service_account_flattened_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_service_account( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_service_account_flattened_error_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_service_account( + iam.DeleteServiceAccountRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam.UndeleteServiceAccountRequest, + dict, + ], +) +def test_undelete_service_account(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.UndeleteServiceAccountResponse() + response = client.undelete_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.UndeleteServiceAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.UndeleteServiceAccountResponse) + + +def test_undelete_service_account_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_service_account), "__call__" + ) as call: + client.undelete_service_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.UndeleteServiceAccountRequest() + + +def test_undelete_service_account_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.UndeleteServiceAccountRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_service_account), "__call__" + ) as call: + client.undelete_service_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.UndeleteServiceAccountRequest( + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_undelete_service_account_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.UndeleteServiceAccountResponse() + ) + response = await client.undelete_service_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.UndeleteServiceAccountRequest() + + +@pytest.mark.asyncio +async def test_undelete_service_account_async( + transport: str = "grpc_asyncio", request_type=iam.UndeleteServiceAccountRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.UndeleteServiceAccountResponse() + ) + response = await client.undelete_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.UndeleteServiceAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.UndeleteServiceAccountResponse) + + +@pytest.mark.asyncio +async def test_undelete_service_account_async_from_dict(): + await test_undelete_service_account_async(request_type=dict) + + +def test_undelete_service_account_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.UndeleteServiceAccountRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_service_account), "__call__" + ) as call: + call.return_value = iam.UndeleteServiceAccountResponse() + client.undelete_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_undelete_service_account_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.UndeleteServiceAccountRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.undelete_service_account), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.UndeleteServiceAccountResponse() + ) + await client.undelete_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + iam.EnableServiceAccountRequest, + dict, + ], +) +def test_enable_service_account(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.enable_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.EnableServiceAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_enable_service_account_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_service_account), "__call__" + ) as call: + client.enable_service_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.EnableServiceAccountRequest() + + +def test_enable_service_account_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.EnableServiceAccountRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_service_account), "__call__" + ) as call: + client.enable_service_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.EnableServiceAccountRequest( + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_enable_service_account_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.enable_service_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.EnableServiceAccountRequest() + + +@pytest.mark.asyncio +async def test_enable_service_account_async( + transport: str = "grpc_asyncio", request_type=iam.EnableServiceAccountRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.enable_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.EnableServiceAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_enable_service_account_async_from_dict(): + await test_enable_service_account_async(request_type=dict) + + +def test_enable_service_account_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.EnableServiceAccountRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_service_account), "__call__" + ) as call: + call.return_value = None + client.enable_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_enable_service_account_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.EnableServiceAccountRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_service_account), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.enable_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + iam.DisableServiceAccountRequest, + dict, + ], +) +def test_disable_service_account(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.disable_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.DisableServiceAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_disable_service_account_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_service_account), "__call__" + ) as call: + client.disable_service_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.DisableServiceAccountRequest() + + +def test_disable_service_account_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.DisableServiceAccountRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_service_account), "__call__" + ) as call: + client.disable_service_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.DisableServiceAccountRequest( + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_disable_service_account_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.disable_service_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.DisableServiceAccountRequest() + + +@pytest.mark.asyncio +async def test_disable_service_account_async( + transport: str = "grpc_asyncio", request_type=iam.DisableServiceAccountRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_service_account), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.disable_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.DisableServiceAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_disable_service_account_async_from_dict(): + await test_disable_service_account_async(request_type=dict) + + +def test_disable_service_account_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.DisableServiceAccountRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_service_account), "__call__" + ) as call: + call.return_value = None + client.disable_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_disable_service_account_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.DisableServiceAccountRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_service_account), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.disable_service_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + iam.ListServiceAccountKeysRequest, + dict, + ], +) +def test_list_service_account_keys(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_account_keys), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ListServiceAccountKeysResponse() + response = client.list_service_account_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.ListServiceAccountKeysRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.ListServiceAccountKeysResponse) + + +def test_list_service_account_keys_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_account_keys), "__call__" + ) as call: + client.list_service_account_keys() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.ListServiceAccountKeysRequest() + + +def test_list_service_account_keys_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.ListServiceAccountKeysRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_account_keys), "__call__" + ) as call: + client.list_service_account_keys(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.ListServiceAccountKeysRequest( + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_list_service_account_keys_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_account_keys), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ListServiceAccountKeysResponse() + ) + response = await client.list_service_account_keys() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.ListServiceAccountKeysRequest() + + +@pytest.mark.asyncio +async def test_list_service_account_keys_async( + transport: str = "grpc_asyncio", request_type=iam.ListServiceAccountKeysRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_account_keys), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ListServiceAccountKeysResponse() + ) + response = await client.list_service_account_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.ListServiceAccountKeysRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.ListServiceAccountKeysResponse) + + +@pytest.mark.asyncio +async def test_list_service_account_keys_async_from_dict(): + await test_list_service_account_keys_async(request_type=dict) + + +def test_list_service_account_keys_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ListServiceAccountKeysRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_account_keys), "__call__" + ) as call: + call.return_value = iam.ListServiceAccountKeysResponse() + client.list_service_account_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_service_account_keys_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.ListServiceAccountKeysRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_account_keys), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ListServiceAccountKeysResponse() + ) + await client.list_service_account_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_list_service_account_keys_flattened(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_account_keys), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ListServiceAccountKeysResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_service_account_keys( + name="name_value", + key_types=[iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].key_types + mock_val = [iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED] + assert arg == mock_val + + +def test_list_service_account_keys_flattened_error(): + client = IAMClient( + credentials=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_service_account_keys( + iam.ListServiceAccountKeysRequest(), + name="name_value", + key_types=[iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED], + ) + + +@pytest.mark.asyncio +async def test_list_service_account_keys_flattened_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_service_account_keys), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ListServiceAccountKeysResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ListServiceAccountKeysResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_service_account_keys( + name="name_value", + key_types=[iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].key_types + mock_val = [iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED] + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_service_account_keys_flattened_error_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_service_account_keys( + iam.ListServiceAccountKeysRequest(), + name="name_value", + key_types=[iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam.GetServiceAccountKeyRequest, + dict, + ], +) +def test_get_service_account_key(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ServiceAccountKey( + name="name_value", + private_key_type=iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE, + key_algorithm=iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024, + private_key_data=b"private_key_data_blob", + public_key_data=b"public_key_data_blob", + key_origin=iam.ServiceAccountKeyOrigin.USER_PROVIDED, + key_type=iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED, + disabled=True, + ) + response = client.get_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.GetServiceAccountKeyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.ServiceAccountKey) + assert response.name == "name_value" + assert ( + response.private_key_type == iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE + ) + assert response.key_algorithm == iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024 + assert response.private_key_data == b"private_key_data_blob" + assert response.public_key_data == b"public_key_data_blob" + assert response.key_origin == iam.ServiceAccountKeyOrigin.USER_PROVIDED + assert response.key_type == iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED + assert response.disabled is True + + +def test_get_service_account_key_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_account_key), "__call__" + ) as call: + client.get_service_account_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.GetServiceAccountKeyRequest() + + +def test_get_service_account_key_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.GetServiceAccountKeyRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_account_key), "__call__" + ) as call: + client.get_service_account_key(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.GetServiceAccountKeyRequest( + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_service_account_key_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ServiceAccountKey( + name="name_value", + private_key_type=iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE, + key_algorithm=iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024, + private_key_data=b"private_key_data_blob", + public_key_data=b"public_key_data_blob", + key_origin=iam.ServiceAccountKeyOrigin.USER_PROVIDED, + key_type=iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED, + disabled=True, + ) + ) + response = await client.get_service_account_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.GetServiceAccountKeyRequest() + + +@pytest.mark.asyncio +async def test_get_service_account_key_async( + transport: str = "grpc_asyncio", request_type=iam.GetServiceAccountKeyRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ServiceAccountKey( + name="name_value", + private_key_type=iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE, + key_algorithm=iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024, + private_key_data=b"private_key_data_blob", + public_key_data=b"public_key_data_blob", + key_origin=iam.ServiceAccountKeyOrigin.USER_PROVIDED, + key_type=iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED, + disabled=True, + ) + ) + response = await client.get_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.GetServiceAccountKeyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.ServiceAccountKey) + assert response.name == "name_value" + assert ( + response.private_key_type == iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE + ) + assert response.key_algorithm == iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024 + assert response.private_key_data == b"private_key_data_blob" + assert response.public_key_data == b"public_key_data_blob" + assert response.key_origin == iam.ServiceAccountKeyOrigin.USER_PROVIDED + assert response.key_type == iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED + assert response.disabled is True + + +@pytest.mark.asyncio +async def test_get_service_account_key_async_from_dict(): + await test_get_service_account_key_async(request_type=dict) + + +def test_get_service_account_key_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.GetServiceAccountKeyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_account_key), "__call__" + ) as call: + call.return_value = iam.ServiceAccountKey() + client.get_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_service_account_key_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.GetServiceAccountKeyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_account_key), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ServiceAccountKey() + ) + await client.get_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_service_account_key_flattened(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ServiceAccountKey() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_service_account_key( + name="name_value", + public_key_type=iam.ServiceAccountPublicKeyType.TYPE_X509_PEM_FILE, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].public_key_type + mock_val = iam.ServiceAccountPublicKeyType.TYPE_X509_PEM_FILE + assert arg == mock_val + + +def test_get_service_account_key_flattened_error(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_service_account_key( + iam.GetServiceAccountKeyRequest(), + name="name_value", + public_key_type=iam.ServiceAccountPublicKeyType.TYPE_X509_PEM_FILE, + ) + + +@pytest.mark.asyncio +async def test_get_service_account_key_flattened_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ServiceAccountKey() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ServiceAccountKey() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_service_account_key( + name="name_value", + public_key_type=iam.ServiceAccountPublicKeyType.TYPE_X509_PEM_FILE, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].public_key_type + mock_val = iam.ServiceAccountPublicKeyType.TYPE_X509_PEM_FILE + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_service_account_key_flattened_error_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_service_account_key( + iam.GetServiceAccountKeyRequest(), + name="name_value", + public_key_type=iam.ServiceAccountPublicKeyType.TYPE_X509_PEM_FILE, + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam.CreateServiceAccountKeyRequest, + dict, + ], +) +def test_create_service_account_key(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ServiceAccountKey( + name="name_value", + private_key_type=iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE, + key_algorithm=iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024, + private_key_data=b"private_key_data_blob", + public_key_data=b"public_key_data_blob", + key_origin=iam.ServiceAccountKeyOrigin.USER_PROVIDED, + key_type=iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED, + disabled=True, + ) + response = client.create_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.CreateServiceAccountKeyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.ServiceAccountKey) + assert response.name == "name_value" + assert ( + response.private_key_type == iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE + ) + assert response.key_algorithm == iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024 + assert response.private_key_data == b"private_key_data_blob" + assert response.public_key_data == b"public_key_data_blob" + assert response.key_origin == iam.ServiceAccountKeyOrigin.USER_PROVIDED + assert response.key_type == iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED + assert response.disabled is True + + +def test_create_service_account_key_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_account_key), "__call__" + ) as call: + client.create_service_account_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.CreateServiceAccountKeyRequest() + + +def test_create_service_account_key_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.CreateServiceAccountKeyRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_account_key), "__call__" + ) as call: + client.create_service_account_key(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.CreateServiceAccountKeyRequest( + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_create_service_account_key_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ServiceAccountKey( + name="name_value", + private_key_type=iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE, + key_algorithm=iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024, + private_key_data=b"private_key_data_blob", + public_key_data=b"public_key_data_blob", + key_origin=iam.ServiceAccountKeyOrigin.USER_PROVIDED, + key_type=iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED, + disabled=True, + ) + ) + response = await client.create_service_account_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.CreateServiceAccountKeyRequest() + + +@pytest.mark.asyncio +async def test_create_service_account_key_async( + transport: str = "grpc_asyncio", request_type=iam.CreateServiceAccountKeyRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ServiceAccountKey( + name="name_value", + private_key_type=iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE, + key_algorithm=iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024, + private_key_data=b"private_key_data_blob", + public_key_data=b"public_key_data_blob", + key_origin=iam.ServiceAccountKeyOrigin.USER_PROVIDED, + key_type=iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED, + disabled=True, + ) + ) + response = await client.create_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.CreateServiceAccountKeyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.ServiceAccountKey) + assert response.name == "name_value" + assert ( + response.private_key_type == iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE + ) + assert response.key_algorithm == iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024 + assert response.private_key_data == b"private_key_data_blob" + assert response.public_key_data == b"public_key_data_blob" + assert response.key_origin == iam.ServiceAccountKeyOrigin.USER_PROVIDED + assert response.key_type == iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED + assert response.disabled is True + + +@pytest.mark.asyncio +async def test_create_service_account_key_async_from_dict(): + await test_create_service_account_key_async(request_type=dict) + + +def test_create_service_account_key_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.CreateServiceAccountKeyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_account_key), "__call__" + ) as call: + call.return_value = iam.ServiceAccountKey() + client.create_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_service_account_key_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.CreateServiceAccountKeyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_account_key), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ServiceAccountKey() + ) + await client.create_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_service_account_key_flattened(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ServiceAccountKey() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_service_account_key( + name="name_value", + private_key_type=iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE, + key_algorithm=iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].private_key_type + mock_val = iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE + assert arg == mock_val + arg = args[0].key_algorithm + mock_val = iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024 + assert arg == mock_val + + +def test_create_service_account_key_flattened_error(): + client = IAMClient( + credentials=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_service_account_key( + iam.CreateServiceAccountKeyRequest(), + name="name_value", + private_key_type=iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE, + key_algorithm=iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024, + ) + + +@pytest.mark.asyncio +async def test_create_service_account_key_flattened_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ServiceAccountKey() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ServiceAccountKey() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_service_account_key( + name="name_value", + private_key_type=iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE, + key_algorithm=iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].private_key_type + mock_val = iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE + assert arg == mock_val + arg = args[0].key_algorithm + mock_val = iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024 + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_service_account_key_flattened_error_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_service_account_key( + iam.CreateServiceAccountKeyRequest(), + name="name_value", + private_key_type=iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE, + key_algorithm=iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024, + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam.UploadServiceAccountKeyRequest, + dict, + ], +) +def test_upload_service_account_key(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ServiceAccountKey( + name="name_value", + private_key_type=iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE, + key_algorithm=iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024, + private_key_data=b"private_key_data_blob", + public_key_data=b"public_key_data_blob", + key_origin=iam.ServiceAccountKeyOrigin.USER_PROVIDED, + key_type=iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED, + disabled=True, + ) + response = client.upload_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.UploadServiceAccountKeyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.ServiceAccountKey) + assert response.name == "name_value" + assert ( + response.private_key_type == iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE + ) + assert response.key_algorithm == iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024 + assert response.private_key_data == b"private_key_data_blob" + assert response.public_key_data == b"public_key_data_blob" + assert response.key_origin == iam.ServiceAccountKeyOrigin.USER_PROVIDED + assert response.key_type == iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED + assert response.disabled is True + + +def test_upload_service_account_key_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_service_account_key), "__call__" + ) as call: + client.upload_service_account_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.UploadServiceAccountKeyRequest() + + +def test_upload_service_account_key_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.UploadServiceAccountKeyRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_service_account_key), "__call__" + ) as call: + client.upload_service_account_key(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.UploadServiceAccountKeyRequest( + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_upload_service_account_key_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ServiceAccountKey( + name="name_value", + private_key_type=iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE, + key_algorithm=iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024, + private_key_data=b"private_key_data_blob", + public_key_data=b"public_key_data_blob", + key_origin=iam.ServiceAccountKeyOrigin.USER_PROVIDED, + key_type=iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED, + disabled=True, + ) + ) + response = await client.upload_service_account_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.UploadServiceAccountKeyRequest() + + +@pytest.mark.asyncio +async def test_upload_service_account_key_async( + transport: str = "grpc_asyncio", request_type=iam.UploadServiceAccountKeyRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ServiceAccountKey( + name="name_value", + private_key_type=iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE, + key_algorithm=iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024, + private_key_data=b"private_key_data_blob", + public_key_data=b"public_key_data_blob", + key_origin=iam.ServiceAccountKeyOrigin.USER_PROVIDED, + key_type=iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED, + disabled=True, + ) + ) + response = await client.upload_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.UploadServiceAccountKeyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.ServiceAccountKey) + assert response.name == "name_value" + assert ( + response.private_key_type == iam.ServiceAccountPrivateKeyType.TYPE_PKCS12_FILE + ) + assert response.key_algorithm == iam.ServiceAccountKeyAlgorithm.KEY_ALG_RSA_1024 + assert response.private_key_data == b"private_key_data_blob" + assert response.public_key_data == b"public_key_data_blob" + assert response.key_origin == iam.ServiceAccountKeyOrigin.USER_PROVIDED + assert response.key_type == iam.ListServiceAccountKeysRequest.KeyType.USER_MANAGED + assert response.disabled is True + + +@pytest.mark.asyncio +async def test_upload_service_account_key_async_from_dict(): + await test_upload_service_account_key_async(request_type=dict) + + +def test_upload_service_account_key_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.UploadServiceAccountKeyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_service_account_key), "__call__" + ) as call: + call.return_value = iam.ServiceAccountKey() + client.upload_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_upload_service_account_key_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.UploadServiceAccountKeyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_service_account_key), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ServiceAccountKey() + ) + await client.upload_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + iam.DeleteServiceAccountKeyRequest, + dict, + ], +) +def test_delete_service_account_key(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.DeleteServiceAccountKeyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_service_account_key_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_account_key), "__call__" + ) as call: + client.delete_service_account_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.DeleteServiceAccountKeyRequest() + + +def test_delete_service_account_key_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.DeleteServiceAccountKeyRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_account_key), "__call__" + ) as call: + client.delete_service_account_key(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.DeleteServiceAccountKeyRequest( + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_service_account_key_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_service_account_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.DeleteServiceAccountKeyRequest() + + +@pytest.mark.asyncio +async def test_delete_service_account_key_async( + transport: str = "grpc_asyncio", request_type=iam.DeleteServiceAccountKeyRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.DeleteServiceAccountKeyRequest() + 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_service_account_key_async_from_dict(): + await test_delete_service_account_key_async(request_type=dict) + + +def test_delete_service_account_key_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.DeleteServiceAccountKeyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_account_key), "__call__" + ) as call: + call.return_value = None + client.delete_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_service_account_key_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.DeleteServiceAccountKeyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_account_key), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_service_account_key_flattened(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_service_account_key( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_service_account_key_flattened_error(): + client = IAMClient( + credentials=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_service_account_key( + iam.DeleteServiceAccountKeyRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_service_account_key_flattened_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_service_account_key( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_service_account_key_flattened_error_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_service_account_key( + iam.DeleteServiceAccountKeyRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam.DisableServiceAccountKeyRequest, + dict, + ], +) +def test_disable_service_account_key(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.disable_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.DisableServiceAccountKeyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_disable_service_account_key_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_service_account_key), "__call__" + ) as call: + client.disable_service_account_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.DisableServiceAccountKeyRequest() + + +def test_disable_service_account_key_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.DisableServiceAccountKeyRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_service_account_key), "__call__" + ) as call: + client.disable_service_account_key(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.DisableServiceAccountKeyRequest( + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_disable_service_account_key_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.disable_service_account_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.DisableServiceAccountKeyRequest() + + +@pytest.mark.asyncio +async def test_disable_service_account_key_async( + transport: str = "grpc_asyncio", request_type=iam.DisableServiceAccountKeyRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.disable_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.DisableServiceAccountKeyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_disable_service_account_key_async_from_dict(): + await test_disable_service_account_key_async(request_type=dict) + + +def test_disable_service_account_key_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.DisableServiceAccountKeyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_service_account_key), "__call__" + ) as call: + call.return_value = None + client.disable_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_disable_service_account_key_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.DisableServiceAccountKeyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_service_account_key), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.disable_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_disable_service_account_key_flattened(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.disable_service_account_key( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_disable_service_account_key_flattened_error(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.disable_service_account_key( + iam.DisableServiceAccountKeyRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_disable_service_account_key_flattened_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.disable_service_account_key( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_disable_service_account_key_flattened_error_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.disable_service_account_key( + iam.DisableServiceAccountKeyRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam.EnableServiceAccountKeyRequest, + dict, + ], +) +def test_enable_service_account_key(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.enable_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.EnableServiceAccountKeyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_enable_service_account_key_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_service_account_key), "__call__" + ) as call: + client.enable_service_account_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.EnableServiceAccountKeyRequest() + + +def test_enable_service_account_key_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.EnableServiceAccountKeyRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_service_account_key), "__call__" + ) as call: + client.enable_service_account_key(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.EnableServiceAccountKeyRequest( + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_enable_service_account_key_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.enable_service_account_key() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.EnableServiceAccountKeyRequest() + + +@pytest.mark.asyncio +async def test_enable_service_account_key_async( + transport: str = "grpc_asyncio", request_type=iam.EnableServiceAccountKeyRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.enable_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.EnableServiceAccountKeyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_enable_service_account_key_async_from_dict(): + await test_enable_service_account_key_async(request_type=dict) + + +def test_enable_service_account_key_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.EnableServiceAccountKeyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_service_account_key), "__call__" + ) as call: + call.return_value = None + client.enable_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_enable_service_account_key_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.EnableServiceAccountKeyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_service_account_key), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.enable_service_account_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_enable_service_account_key_flattened(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.enable_service_account_key( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_enable_service_account_key_flattened_error(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.enable_service_account_key( + iam.EnableServiceAccountKeyRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_enable_service_account_key_flattened_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_service_account_key), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.enable_service_account_key( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_enable_service_account_key_flattened_error_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.enable_service_account_key( + iam.EnableServiceAccountKeyRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam.SignBlobRequest, + dict, + ], +) +def test_sign_blob(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = iam.SignBlobResponse( + key_id="key_id_value", + signature=b"signature_blob", + ) + response = client.sign_blob(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.SignBlobRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.SignBlobResponse) + assert response.key_id == "key_id_value" + assert response.signature == b"signature_blob" + + +def test_sign_blob_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: + client.sign_blob() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.SignBlobRequest() + + +def test_sign_blob_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.SignBlobRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: + client.sign_blob(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.SignBlobRequest( + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_sign_blob_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.SignBlobResponse( + key_id="key_id_value", + signature=b"signature_blob", + ) + ) + response = await client.sign_blob() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.SignBlobRequest() + + +@pytest.mark.asyncio +async def test_sign_blob_async( + transport: str = "grpc_asyncio", request_type=iam.SignBlobRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.SignBlobResponse( + key_id="key_id_value", + signature=b"signature_blob", + ) + ) + response = await client.sign_blob(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.SignBlobRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.SignBlobResponse) + assert response.key_id == "key_id_value" + assert response.signature == b"signature_blob" + + +@pytest.mark.asyncio +async def test_sign_blob_async_from_dict(): + await test_sign_blob_async(request_type=dict) + + +def test_sign_blob_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.SignBlobRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: + call.return_value = iam.SignBlobResponse() + client.sign_blob(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_sign_blob_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.SignBlobRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.SignBlobResponse() + ) + await client.sign_blob(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_sign_blob_flattened(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = iam.SignBlobResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.sign_blob( + name="name_value", + bytes_to_sign=b"bytes_to_sign_blob", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].bytes_to_sign + mock_val = b"bytes_to_sign_blob" + assert arg == mock_val + + +def test_sign_blob_flattened_error(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.sign_blob( + iam.SignBlobRequest(), + name="name_value", + bytes_to_sign=b"bytes_to_sign_blob", + ) + + +@pytest.mark.asyncio +async def test_sign_blob_flattened_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.sign_blob), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = iam.SignBlobResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.SignBlobResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.sign_blob( + name="name_value", + bytes_to_sign=b"bytes_to_sign_blob", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].bytes_to_sign + mock_val = b"bytes_to_sign_blob" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_sign_blob_flattened_error_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.sign_blob( + iam.SignBlobRequest(), + name="name_value", + bytes_to_sign=b"bytes_to_sign_blob", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam.SignJwtRequest, + dict, + ], +) +def test_sign_jwt(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = iam.SignJwtResponse( + key_id="key_id_value", + signed_jwt="signed_jwt_value", + ) + response = client.sign_jwt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.SignJwtRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.SignJwtResponse) + assert response.key_id == "key_id_value" + assert response.signed_jwt == "signed_jwt_value" + + +def test_sign_jwt_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: + client.sign_jwt() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.SignJwtRequest() + + +def test_sign_jwt_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.SignJwtRequest( + name="name_value", + payload="payload_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: + client.sign_jwt(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.SignJwtRequest( + name="name_value", + payload="payload_value", + ) + + +@pytest.mark.asyncio +async def test_sign_jwt_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.SignJwtResponse( + key_id="key_id_value", + signed_jwt="signed_jwt_value", + ) + ) + response = await client.sign_jwt() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.SignJwtRequest() + + +@pytest.mark.asyncio +async def test_sign_jwt_async( + transport: str = "grpc_asyncio", request_type=iam.SignJwtRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.SignJwtResponse( + key_id="key_id_value", + signed_jwt="signed_jwt_value", + ) + ) + response = await client.sign_jwt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.SignJwtRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.SignJwtResponse) + assert response.key_id == "key_id_value" + assert response.signed_jwt == "signed_jwt_value" + + +@pytest.mark.asyncio +async def test_sign_jwt_async_from_dict(): + await test_sign_jwt_async(request_type=dict) + + +def test_sign_jwt_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.SignJwtRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: + call.return_value = iam.SignJwtResponse() + client.sign_jwt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_sign_jwt_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.SignJwtRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam.SignJwtResponse()) + await client.sign_jwt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_sign_jwt_flattened(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = iam.SignJwtResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.sign_jwt( + name="name_value", + payload="payload_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].payload + mock_val = "payload_value" + assert arg == mock_val + + +def test_sign_jwt_flattened_error(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.sign_jwt( + iam.SignJwtRequest(), + name="name_value", + payload="payload_value", + ) + + +@pytest.mark.asyncio +async def test_sign_jwt_flattened_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.sign_jwt), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = iam.SignJwtResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam.SignJwtResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.sign_jwt( + name="name_value", + payload="payload_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].payload + mock_val = "payload_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_sign_jwt_flattened_error_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.sign_jwt( + iam.SignJwtRequest(), + name="name_value", + payload="payload_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam_policy_pb2.GetIamPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +def test_get_iam_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + client.get_iam_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest( + resource="resource_value", + ) + + +@pytest.mark.asyncio +async def test_get_iam_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.get_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_get_iam_policy_async( + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.GetIamPolicyRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam_policy_pb2.GetIamPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + + request.resource = "resource_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource_value", + ) in kw["metadata"] + + +def test_get_iam_policy_from_dict_foreign(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_get_iam_policy_flattened(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_iam_policy( + resource="resource_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = "resource_value" + assert arg == mock_val + + +def test_get_iam_policy_flattened_error(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource="resource_value", + ) + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_iam_policy( + resource="resource_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = "resource_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_iam_policy_flattened_error_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource="resource_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + response = client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam_policy_pb2.SetIamPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +def test_set_iam_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + client.set_iam_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest( + resource="resource_value", + ) + + +@pytest.mark.asyncio +async def test_set_iam_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.set_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() + + +@pytest.mark.asyncio +async def test_set_iam_policy_async( + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.SetIamPolicyRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + ) + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam_policy_pb2.SetIamPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + + request.resource = "resource_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource_value", + ) in kw["metadata"] + + +def test_set_iam_policy_from_dict_foreign(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + "update_mask": field_mask_pb2.FieldMask(paths=["paths_value"]), + } + ) + call.assert_called() + + +def test_set_iam_policy_flattened(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.set_iam_policy( + resource="resource_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = "resource_value" + assert arg == mock_val + + +def test_set_iam_policy_flattened_error(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource="resource_value", + ) + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.set_iam_policy( + resource="resource_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = "resource_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_set_iam_policy_flattened_error_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource="resource_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam_policy_pb2.TestIamPermissionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +def test_test_iam_permissions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + client.test_iam_permissions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest( + resource="resource_value", + ) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + response = await client.test_iam_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async( + transport: str = "grpc_asyncio", + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + ) + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam_policy_pb2.TestIamPermissionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + + request.resource = "resource_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "resource=resource_value", + ) in kw["metadata"] + + +def test_test_iam_permissions_from_dict_foreign(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_test_iam_permissions_flattened(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_iam_permissions( + resource="resource_value", + permissions=["permissions_value"], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = "resource_value" + assert arg == mock_val + arg = args[0].permissions + mock_val = ["permissions_value"] + assert arg == mock_val + + +def test_test_iam_permissions_flattened_error(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource="resource_value", + permissions=["permissions_value"], + ) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_iam_permissions( + resource="resource_value", + permissions=["permissions_value"], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].resource + mock_val = "resource_value" + assert arg == mock_val + arg = args[0].permissions + mock_val = ["permissions_value"] + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_test_iam_permissions_flattened_error_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource="resource_value", + permissions=["permissions_value"], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam.QueryGrantableRolesRequest, + dict, + ], +) +def test_query_grantable_roles(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_grantable_roles), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.QueryGrantableRolesResponse( + next_page_token="next_page_token_value", + ) + response = client.query_grantable_roles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.QueryGrantableRolesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.QueryGrantableRolesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_query_grantable_roles_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_grantable_roles), "__call__" + ) as call: + client.query_grantable_roles() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.QueryGrantableRolesRequest() + + +def test_query_grantable_roles_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.QueryGrantableRolesRequest( + full_resource_name="full_resource_name_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_grantable_roles), "__call__" + ) as call: + client.query_grantable_roles(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.QueryGrantableRolesRequest( + full_resource_name="full_resource_name_value", + page_token="page_token_value", + ) + + +@pytest.mark.asyncio +async def test_query_grantable_roles_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_grantable_roles), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.QueryGrantableRolesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.query_grantable_roles() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.QueryGrantableRolesRequest() + + +@pytest.mark.asyncio +async def test_query_grantable_roles_async( + transport: str = "grpc_asyncio", request_type=iam.QueryGrantableRolesRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_grantable_roles), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.QueryGrantableRolesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.query_grantable_roles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.QueryGrantableRolesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.QueryGrantableRolesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_query_grantable_roles_async_from_dict(): + await test_query_grantable_roles_async(request_type=dict) + + +def test_query_grantable_roles_flattened(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_grantable_roles), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.QueryGrantableRolesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.query_grantable_roles( + full_resource_name="full_resource_name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].full_resource_name + mock_val = "full_resource_name_value" + assert arg == mock_val + + +def test_query_grantable_roles_flattened_error(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.query_grantable_roles( + iam.QueryGrantableRolesRequest(), + full_resource_name="full_resource_name_value", + ) + + +@pytest.mark.asyncio +async def test_query_grantable_roles_flattened_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_grantable_roles), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.QueryGrantableRolesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.QueryGrantableRolesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.query_grantable_roles( + full_resource_name="full_resource_name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].full_resource_name + mock_val = "full_resource_name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_query_grantable_roles_flattened_error_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.query_grantable_roles( + iam.QueryGrantableRolesRequest(), + full_resource_name="full_resource_name_value", + ) + + +def test_query_grantable_roles_pager(transport_name: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_grantable_roles), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + iam.QueryGrantableRolesResponse( + roles=[ + iam.Role(), + iam.Role(), + iam.Role(), + ], + next_page_token="abc", + ), + iam.QueryGrantableRolesResponse( + roles=[], + next_page_token="def", + ), + iam.QueryGrantableRolesResponse( + roles=[ + iam.Role(), + ], + next_page_token="ghi", + ), + iam.QueryGrantableRolesResponse( + roles=[ + iam.Role(), + iam.Role(), + ], + ), + RuntimeError, + ) + + metadata = () + pager = client.query_grantable_roles(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, iam.Role) for i in results) + + +def test_query_grantable_roles_pages(transport_name: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_grantable_roles), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + iam.QueryGrantableRolesResponse( + roles=[ + iam.Role(), + iam.Role(), + iam.Role(), + ], + next_page_token="abc", + ), + iam.QueryGrantableRolesResponse( + roles=[], + next_page_token="def", + ), + iam.QueryGrantableRolesResponse( + roles=[ + iam.Role(), + ], + next_page_token="ghi", + ), + iam.QueryGrantableRolesResponse( + roles=[ + iam.Role(), + iam.Role(), + ], + ), + RuntimeError, + ) + pages = list(client.query_grantable_roles(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_query_grantable_roles_async_pager(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_grantable_roles), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + iam.QueryGrantableRolesResponse( + roles=[ + iam.Role(), + iam.Role(), + iam.Role(), + ], + next_page_token="abc", + ), + iam.QueryGrantableRolesResponse( + roles=[], + next_page_token="def", + ), + iam.QueryGrantableRolesResponse( + roles=[ + iam.Role(), + ], + next_page_token="ghi", + ), + iam.QueryGrantableRolesResponse( + roles=[ + iam.Role(), + iam.Role(), + ], + ), + RuntimeError, + ) + async_pager = await client.query_grantable_roles( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, iam.Role) for i in responses) + + +@pytest.mark.asyncio +async def test_query_grantable_roles_async_pages(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_grantable_roles), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + iam.QueryGrantableRolesResponse( + roles=[ + iam.Role(), + iam.Role(), + iam.Role(), + ], + next_page_token="abc", + ), + iam.QueryGrantableRolesResponse( + roles=[], + next_page_token="def", + ), + iam.QueryGrantableRolesResponse( + roles=[ + iam.Role(), + ], + next_page_token="ghi", + ), + iam.QueryGrantableRolesResponse( + roles=[ + iam.Role(), + iam.Role(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.query_grantable_roles(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + iam.ListRolesRequest, + dict, + ], +) +def test_list_roles(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_roles), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = iam.ListRolesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_roles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.ListRolesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRolesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_roles_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_roles), "__call__") as call: + client.list_roles() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.ListRolesRequest() + + +def test_list_roles_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.ListRolesRequest( + 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_roles), "__call__") as call: + client.list_roles(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.ListRolesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +@pytest.mark.asyncio +async def test_list_roles_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_roles), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ListRolesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_roles() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.ListRolesRequest() + + +@pytest.mark.asyncio +async def test_list_roles_async( + transport: str = "grpc_asyncio", request_type=iam.ListRolesRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_roles), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.ListRolesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_roles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.ListRolesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRolesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_roles_async_from_dict(): + await test_list_roles_async(request_type=dict) + + +def test_list_roles_pager(transport_name: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_roles), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + iam.ListRolesResponse( + roles=[ + iam.Role(), + iam.Role(), + iam.Role(), + ], + next_page_token="abc", + ), + iam.ListRolesResponse( + roles=[], + next_page_token="def", + ), + iam.ListRolesResponse( + roles=[ + iam.Role(), + ], + next_page_token="ghi", + ), + iam.ListRolesResponse( + roles=[ + iam.Role(), + iam.Role(), + ], + ), + RuntimeError, + ) + + metadata = () + pager = client.list_roles(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, iam.Role) for i in results) + + +def test_list_roles_pages(transport_name: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_roles), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + iam.ListRolesResponse( + roles=[ + iam.Role(), + iam.Role(), + iam.Role(), + ], + next_page_token="abc", + ), + iam.ListRolesResponse( + roles=[], + next_page_token="def", + ), + iam.ListRolesResponse( + roles=[ + iam.Role(), + ], + next_page_token="ghi", + ), + iam.ListRolesResponse( + roles=[ + iam.Role(), + iam.Role(), + ], + ), + RuntimeError, + ) + pages = list(client.list_roles(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_roles_async_pager(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_roles), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + iam.ListRolesResponse( + roles=[ + iam.Role(), + iam.Role(), + iam.Role(), + ], + next_page_token="abc", + ), + iam.ListRolesResponse( + roles=[], + next_page_token="def", + ), + iam.ListRolesResponse( + roles=[ + iam.Role(), + ], + next_page_token="ghi", + ), + iam.ListRolesResponse( + roles=[ + iam.Role(), + iam.Role(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_roles( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, iam.Role) for i in responses) + + +@pytest.mark.asyncio +async def test_list_roles_async_pages(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_roles), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + iam.ListRolesResponse( + roles=[ + iam.Role(), + iam.Role(), + iam.Role(), + ], + next_page_token="abc", + ), + iam.ListRolesResponse( + roles=[], + next_page_token="def", + ), + iam.ListRolesResponse( + roles=[ + iam.Role(), + ], + next_page_token="ghi", + ), + iam.ListRolesResponse( + roles=[ + iam.Role(), + iam.Role(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_roles(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + iam.GetRoleRequest, + dict, + ], +) +def test_get_role(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_role), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = iam.Role( + name="name_value", + title="title_value", + description="description_value", + included_permissions=["included_permissions_value"], + stage=iam.Role.RoleLaunchStage.BETA, + etag=b"etag_blob", + deleted=True, + ) + response = client.get_role(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.GetRoleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.Role) + assert response.name == "name_value" + assert response.title == "title_value" + assert response.description == "description_value" + assert response.included_permissions == ["included_permissions_value"] + assert response.stage == iam.Role.RoleLaunchStage.BETA + assert response.etag == b"etag_blob" + assert response.deleted is True + + +def test_get_role_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_role), "__call__") as call: + client.get_role() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.GetRoleRequest() + + +def test_get_role_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.GetRoleRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_role), "__call__") as call: + client.get_role(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.GetRoleRequest( + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_role_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_role), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.Role( + name="name_value", + title="title_value", + description="description_value", + included_permissions=["included_permissions_value"], + stage=iam.Role.RoleLaunchStage.BETA, + etag=b"etag_blob", + deleted=True, + ) + ) + response = await client.get_role() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.GetRoleRequest() + + +@pytest.mark.asyncio +async def test_get_role_async( + transport: str = "grpc_asyncio", request_type=iam.GetRoleRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_role), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.Role( + name="name_value", + title="title_value", + description="description_value", + included_permissions=["included_permissions_value"], + stage=iam.Role.RoleLaunchStage.BETA, + etag=b"etag_blob", + deleted=True, + ) + ) + response = await client.get_role(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.GetRoleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.Role) + assert response.name == "name_value" + assert response.title == "title_value" + assert response.description == "description_value" + assert response.included_permissions == ["included_permissions_value"] + assert response.stage == iam.Role.RoleLaunchStage.BETA + assert response.etag == b"etag_blob" + assert response.deleted is True + + +@pytest.mark.asyncio +async def test_get_role_async_from_dict(): + await test_get_role_async(request_type=dict) + + +def test_get_role_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.GetRoleRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_role), "__call__") as call: + call.return_value = iam.Role() + client.get_role(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_role_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.GetRoleRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_role), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam.Role()) + await client.get_role(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + iam.CreateRoleRequest, + dict, + ], +) +def test_create_role(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_role), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = iam.Role( + name="name_value", + title="title_value", + description="description_value", + included_permissions=["included_permissions_value"], + stage=iam.Role.RoleLaunchStage.BETA, + etag=b"etag_blob", + deleted=True, + ) + response = client.create_role(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.CreateRoleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.Role) + assert response.name == "name_value" + assert response.title == "title_value" + assert response.description == "description_value" + assert response.included_permissions == ["included_permissions_value"] + assert response.stage == iam.Role.RoleLaunchStage.BETA + assert response.etag == b"etag_blob" + assert response.deleted is True + + +def test_create_role_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_role), "__call__") as call: + client.create_role() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.CreateRoleRequest() + + +def test_create_role_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.CreateRoleRequest( + parent="parent_value", + role_id="role_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_role), "__call__") as call: + client.create_role(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.CreateRoleRequest( + parent="parent_value", + role_id="role_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_role_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_role), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.Role( + name="name_value", + title="title_value", + description="description_value", + included_permissions=["included_permissions_value"], + stage=iam.Role.RoleLaunchStage.BETA, + etag=b"etag_blob", + deleted=True, + ) + ) + response = await client.create_role() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.CreateRoleRequest() + + +@pytest.mark.asyncio +async def test_create_role_async( + transport: str = "grpc_asyncio", request_type=iam.CreateRoleRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_role), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.Role( + name="name_value", + title="title_value", + description="description_value", + included_permissions=["included_permissions_value"], + stage=iam.Role.RoleLaunchStage.BETA, + etag=b"etag_blob", + deleted=True, + ) + ) + response = await client.create_role(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.CreateRoleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.Role) + assert response.name == "name_value" + assert response.title == "title_value" + assert response.description == "description_value" + assert response.included_permissions == ["included_permissions_value"] + assert response.stage == iam.Role.RoleLaunchStage.BETA + assert response.etag == b"etag_blob" + assert response.deleted is True + + +@pytest.mark.asyncio +async def test_create_role_async_from_dict(): + await test_create_role_async(request_type=dict) + + +def test_create_role_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.CreateRoleRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_role), "__call__") as call: + call.return_value = iam.Role() + client.create_role(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_role_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.CreateRoleRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_role), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam.Role()) + await client.create_role(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + iam.UpdateRoleRequest, + dict, + ], +) +def test_update_role(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_role), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = iam.Role( + name="name_value", + title="title_value", + description="description_value", + included_permissions=["included_permissions_value"], + stage=iam.Role.RoleLaunchStage.BETA, + etag=b"etag_blob", + deleted=True, + ) + response = client.update_role(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.UpdateRoleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.Role) + assert response.name == "name_value" + assert response.title == "title_value" + assert response.description == "description_value" + assert response.included_permissions == ["included_permissions_value"] + assert response.stage == iam.Role.RoleLaunchStage.BETA + assert response.etag == b"etag_blob" + assert response.deleted is True + + +def test_update_role_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_role), "__call__") as call: + client.update_role() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.UpdateRoleRequest() + + +def test_update_role_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.UpdateRoleRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_role), "__call__") as call: + client.update_role(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.UpdateRoleRequest( + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_update_role_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_role), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.Role( + name="name_value", + title="title_value", + description="description_value", + included_permissions=["included_permissions_value"], + stage=iam.Role.RoleLaunchStage.BETA, + etag=b"etag_blob", + deleted=True, + ) + ) + response = await client.update_role() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.UpdateRoleRequest() + + +@pytest.mark.asyncio +async def test_update_role_async( + transport: str = "grpc_asyncio", request_type=iam.UpdateRoleRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_role), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.Role( + name="name_value", + title="title_value", + description="description_value", + included_permissions=["included_permissions_value"], + stage=iam.Role.RoleLaunchStage.BETA, + etag=b"etag_blob", + deleted=True, + ) + ) + response = await client.update_role(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.UpdateRoleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.Role) + assert response.name == "name_value" + assert response.title == "title_value" + assert response.description == "description_value" + assert response.included_permissions == ["included_permissions_value"] + assert response.stage == iam.Role.RoleLaunchStage.BETA + assert response.etag == b"etag_blob" + assert response.deleted is True + + +@pytest.mark.asyncio +async def test_update_role_async_from_dict(): + await test_update_role_async(request_type=dict) + + +def test_update_role_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.UpdateRoleRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_role), "__call__") as call: + call.return_value = iam.Role() + client.update_role(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_role_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.UpdateRoleRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_role), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam.Role()) + await client.update_role(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + iam.DeleteRoleRequest, + dict, + ], +) +def test_delete_role(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_role), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = iam.Role( + name="name_value", + title="title_value", + description="description_value", + included_permissions=["included_permissions_value"], + stage=iam.Role.RoleLaunchStage.BETA, + etag=b"etag_blob", + deleted=True, + ) + response = client.delete_role(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.DeleteRoleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.Role) + assert response.name == "name_value" + assert response.title == "title_value" + assert response.description == "description_value" + assert response.included_permissions == ["included_permissions_value"] + assert response.stage == iam.Role.RoleLaunchStage.BETA + assert response.etag == b"etag_blob" + assert response.deleted is True + + +def test_delete_role_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_role), "__call__") as call: + client.delete_role() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.DeleteRoleRequest() + + +def test_delete_role_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.DeleteRoleRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_role), "__call__") as call: + client.delete_role(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.DeleteRoleRequest( + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_role_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_role), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.Role( + name="name_value", + title="title_value", + description="description_value", + included_permissions=["included_permissions_value"], + stage=iam.Role.RoleLaunchStage.BETA, + etag=b"etag_blob", + deleted=True, + ) + ) + response = await client.delete_role() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.DeleteRoleRequest() + + +@pytest.mark.asyncio +async def test_delete_role_async( + transport: str = "grpc_asyncio", request_type=iam.DeleteRoleRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_role), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.Role( + name="name_value", + title="title_value", + description="description_value", + included_permissions=["included_permissions_value"], + stage=iam.Role.RoleLaunchStage.BETA, + etag=b"etag_blob", + deleted=True, + ) + ) + response = await client.delete_role(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.DeleteRoleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.Role) + assert response.name == "name_value" + assert response.title == "title_value" + assert response.description == "description_value" + assert response.included_permissions == ["included_permissions_value"] + assert response.stage == iam.Role.RoleLaunchStage.BETA + assert response.etag == b"etag_blob" + assert response.deleted is True + + +@pytest.mark.asyncio +async def test_delete_role_async_from_dict(): + await test_delete_role_async(request_type=dict) + + +def test_delete_role_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.DeleteRoleRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_role), "__call__") as call: + call.return_value = iam.Role() + client.delete_role(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_role_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.DeleteRoleRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_role), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam.Role()) + await client.delete_role(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + iam.UndeleteRoleRequest, + dict, + ], +) +def test_undelete_role(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_role), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = iam.Role( + name="name_value", + title="title_value", + description="description_value", + included_permissions=["included_permissions_value"], + stage=iam.Role.RoleLaunchStage.BETA, + etag=b"etag_blob", + deleted=True, + ) + response = client.undelete_role(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.UndeleteRoleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.Role) + assert response.name == "name_value" + assert response.title == "title_value" + assert response.description == "description_value" + assert response.included_permissions == ["included_permissions_value"] + assert response.stage == iam.Role.RoleLaunchStage.BETA + assert response.etag == b"etag_blob" + assert response.deleted is True + + +def test_undelete_role_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.undelete_role), "__call__") as call: + client.undelete_role() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.UndeleteRoleRequest() + + +def test_undelete_role_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.UndeleteRoleRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.undelete_role), "__call__") as call: + client.undelete_role(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.UndeleteRoleRequest( + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_undelete_role_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.undelete_role), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.Role( + name="name_value", + title="title_value", + description="description_value", + included_permissions=["included_permissions_value"], + stage=iam.Role.RoleLaunchStage.BETA, + etag=b"etag_blob", + deleted=True, + ) + ) + response = await client.undelete_role() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.UndeleteRoleRequest() + + +@pytest.mark.asyncio +async def test_undelete_role_async( + transport: str = "grpc_asyncio", request_type=iam.UndeleteRoleRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_role), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.Role( + name="name_value", + title="title_value", + description="description_value", + included_permissions=["included_permissions_value"], + stage=iam.Role.RoleLaunchStage.BETA, + etag=b"etag_blob", + deleted=True, + ) + ) + response = await client.undelete_role(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.UndeleteRoleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.Role) + assert response.name == "name_value" + assert response.title == "title_value" + assert response.description == "description_value" + assert response.included_permissions == ["included_permissions_value"] + assert response.stage == iam.Role.RoleLaunchStage.BETA + assert response.etag == b"etag_blob" + assert response.deleted is True + + +@pytest.mark.asyncio +async def test_undelete_role_async_from_dict(): + await test_undelete_role_async(request_type=dict) + + +def test_undelete_role_field_headers(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.UndeleteRoleRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.undelete_role), "__call__") as call: + call.return_value = iam.Role() + client.undelete_role(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_role_field_headers_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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.UndeleteRoleRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.undelete_role), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(iam.Role()) + await client.undelete_role(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + iam.QueryTestablePermissionsRequest, + dict, + ], +) +def test_query_testable_permissions(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_testable_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.QueryTestablePermissionsResponse( + next_page_token="next_page_token_value", + ) + response = client.query_testable_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.QueryTestablePermissionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.QueryTestablePermissionsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_query_testable_permissions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_testable_permissions), "__call__" + ) as call: + client.query_testable_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.QueryTestablePermissionsRequest() + + +def test_query_testable_permissions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.QueryTestablePermissionsRequest( + full_resource_name="full_resource_name_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_testable_permissions), "__call__" + ) as call: + client.query_testable_permissions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.QueryTestablePermissionsRequest( + full_resource_name="full_resource_name_value", + page_token="page_token_value", + ) + + +@pytest.mark.asyncio +async def test_query_testable_permissions_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_testable_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.QueryTestablePermissionsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.query_testable_permissions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.QueryTestablePermissionsRequest() + + +@pytest.mark.asyncio +async def test_query_testable_permissions_async( + transport: str = "grpc_asyncio", request_type=iam.QueryTestablePermissionsRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_testable_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.QueryTestablePermissionsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.query_testable_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.QueryTestablePermissionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.QueryTestablePermissionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_query_testable_permissions_async_from_dict(): + await test_query_testable_permissions_async(request_type=dict) + + +def test_query_testable_permissions_pager(transport_name: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_testable_permissions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + iam.QueryTestablePermissionsResponse( + permissions=[ + iam.Permission(), + iam.Permission(), + iam.Permission(), + ], + next_page_token="abc", + ), + iam.QueryTestablePermissionsResponse( + permissions=[], + next_page_token="def", + ), + iam.QueryTestablePermissionsResponse( + permissions=[ + iam.Permission(), + ], + next_page_token="ghi", + ), + iam.QueryTestablePermissionsResponse( + permissions=[ + iam.Permission(), + iam.Permission(), + ], + ), + RuntimeError, + ) + + metadata = () + pager = client.query_testable_permissions(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, iam.Permission) for i in results) + + +def test_query_testable_permissions_pages(transport_name: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_testable_permissions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + iam.QueryTestablePermissionsResponse( + permissions=[ + iam.Permission(), + iam.Permission(), + iam.Permission(), + ], + next_page_token="abc", + ), + iam.QueryTestablePermissionsResponse( + permissions=[], + next_page_token="def", + ), + iam.QueryTestablePermissionsResponse( + permissions=[ + iam.Permission(), + ], + next_page_token="ghi", + ), + iam.QueryTestablePermissionsResponse( + permissions=[ + iam.Permission(), + iam.Permission(), + ], + ), + RuntimeError, + ) + pages = list(client.query_testable_permissions(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_query_testable_permissions_async_pager(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_testable_permissions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + iam.QueryTestablePermissionsResponse( + permissions=[ + iam.Permission(), + iam.Permission(), + iam.Permission(), + ], + next_page_token="abc", + ), + iam.QueryTestablePermissionsResponse( + permissions=[], + next_page_token="def", + ), + iam.QueryTestablePermissionsResponse( + permissions=[ + iam.Permission(), + ], + next_page_token="ghi", + ), + iam.QueryTestablePermissionsResponse( + permissions=[ + iam.Permission(), + iam.Permission(), + ], + ), + RuntimeError, + ) + async_pager = await client.query_testable_permissions( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, iam.Permission) for i in responses) + + +@pytest.mark.asyncio +async def test_query_testable_permissions_async_pages(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_testable_permissions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + iam.QueryTestablePermissionsResponse( + permissions=[ + iam.Permission(), + iam.Permission(), + iam.Permission(), + ], + next_page_token="abc", + ), + iam.QueryTestablePermissionsResponse( + permissions=[], + next_page_token="def", + ), + iam.QueryTestablePermissionsResponse( + permissions=[ + iam.Permission(), + ], + next_page_token="ghi", + ), + iam.QueryTestablePermissionsResponse( + permissions=[ + iam.Permission(), + iam.Permission(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.query_testable_permissions(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + iam.QueryAuditableServicesRequest, + dict, + ], +) +def test_query_auditable_services(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_auditable_services), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam.QueryAuditableServicesResponse() + response = client.query_auditable_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.QueryAuditableServicesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.QueryAuditableServicesResponse) + + +def test_query_auditable_services_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_auditable_services), "__call__" + ) as call: + client.query_auditable_services() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.QueryAuditableServicesRequest() + + +def test_query_auditable_services_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.QueryAuditableServicesRequest( + full_resource_name="full_resource_name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_auditable_services), "__call__" + ) as call: + client.query_auditable_services(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.QueryAuditableServicesRequest( + full_resource_name="full_resource_name_value", + ) + + +@pytest.mark.asyncio +async def test_query_auditable_services_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_auditable_services), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.QueryAuditableServicesResponse() + ) + response = await client.query_auditable_services() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.QueryAuditableServicesRequest() + + +@pytest.mark.asyncio +async def test_query_auditable_services_async( + transport: str = "grpc_asyncio", request_type=iam.QueryAuditableServicesRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_auditable_services), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.QueryAuditableServicesResponse() + ) + response = await client.query_auditable_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.QueryAuditableServicesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.QueryAuditableServicesResponse) + + +@pytest.mark.asyncio +async def test_query_auditable_services_async_from_dict(): + await test_query_auditable_services_async(request_type=dict) + + +@pytest.mark.parametrize( + "request_type", + [ + iam.LintPolicyRequest, + dict, + ], +) +def test_lint_policy(request_type, transport: str = "grpc"): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.lint_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = iam.LintPolicyResponse() + response = client.lint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = iam.LintPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.LintPolicyResponse) + + +def test_lint_policy_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.lint_policy), "__call__") as call: + client.lint_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.LintPolicyRequest() + + +def test_lint_policy_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = iam.LintPolicyRequest( + full_resource_name="full_resource_name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.lint_policy), "__call__") as call: + client.lint_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.LintPolicyRequest( + full_resource_name="full_resource_name_value", + ) + + +@pytest.mark.asyncio +async def test_lint_policy_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.lint_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.LintPolicyResponse() + ) + response = await client.lint_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == iam.LintPolicyRequest() + + +@pytest.mark.asyncio +async def test_lint_policy_async( + transport: str = "grpc_asyncio", request_type=iam.LintPolicyRequest +): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.lint_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam.LintPolicyResponse() + ) + response = await client.lint_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = iam.LintPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam.LintPolicyResponse) + + +@pytest.mark.asyncio +async def test_lint_policy_async_from_dict(): + await test_lint_policy_async(request_type=dict) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.IAMGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.IAMGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = IAMClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.IAMGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = IAMClient( + 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 = IAMClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.IAMGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = IAMClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.IAMGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = IAMClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.IAMGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.IAMGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.IAMGrpcTransport, + transports.IAMGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + ], +) +def test_transport_kind(transport_name): + transport = IAMClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.IAMGrpcTransport, + ) + + +def test_iam_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.IAMTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_iam_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.iam_admin_v1.services.iam.transports.IAMTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.IAMTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_service_accounts", + "get_service_account", + "create_service_account", + "update_service_account", + "patch_service_account", + "delete_service_account", + "undelete_service_account", + "enable_service_account", + "disable_service_account", + "list_service_account_keys", + "get_service_account_key", + "create_service_account_key", + "upload_service_account_key", + "delete_service_account_key", + "disable_service_account_key", + "enable_service_account_key", + "sign_blob", + "sign_jwt", + "get_iam_policy", + "set_iam_policy", + "test_iam_permissions", + "query_grantable_roles", + "list_roles", + "get_role", + "create_role", + "update_role", + "delete_role", + "undelete_role", + "query_testable_permissions", + "query_auditable_services", + "lint_policy", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_iam_base_transport_with_credentials_file(): + # Instantiate the 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.iam_admin_v1.services.iam.transports.IAMTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.IAMTransport( + 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_iam_base_transport_with_adc(): + # Test the default 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.iam_admin_v1.services.iam.transports.IAMTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.IAMTransport() + adc.assert_called_once() + + +def test_iam_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) + IAMClient() + 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.IAMGrpcTransport, + transports.IAMGrpcAsyncIOTransport, + ], +) +def test_iam_transport_auth_adc(transport_class): + # If 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.IAMGrpcTransport, + transports.IAMGrpcAsyncIOTransport, + ], +) +def test_iam_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.IAMGrpcTransport, grpc_helpers), + (transports.IAMGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_iam_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host 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( + "iam.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="iam.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", [transports.IAMGrpcTransport, transports.IAMGrpcAsyncIOTransport] +) +def test_iam_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + ], +) +def test_iam_host_no_port(transport_name): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint="iam.googleapis.com"), + transport=transport_name, + ) + assert client.transport._host == ("iam.googleapis.com:443") + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + ], +) +def test_iam_host_with_port(transport_name): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="iam.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ("iam.googleapis.com:8000") + + +def test_iam_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.IAMGrpcTransport( + 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_iam_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.IAMGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", [transports.IAMGrpcTransport, transports.IAMGrpcAsyncIOTransport] +) +def test_iam_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.IAMGrpcTransport, transports.IAMGrpcAsyncIOTransport] +) +def test_iam_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_key_path(): + project = "squid" + service_account = "clam" + key = "whelk" + expected = "projects/{project}/serviceAccounts/{service_account}/keys/{key}".format( + project=project, + service_account=service_account, + key=key, + ) + actual = IAMClient.key_path(project, service_account, key) + assert expected == actual + + +def test_parse_key_path(): + expected = { + "project": "octopus", + "service_account": "oyster", + "key": "nudibranch", + } + path = IAMClient.key_path(**expected) + + # Check that the path construction is reversible. + actual = IAMClient.parse_key_path(path) + assert expected == actual + + +def test_service_account_path(): + project = "cuttlefish" + service_account = "mussel" + expected = "projects/{project}/serviceAccounts/{service_account}".format( + project=project, + service_account=service_account, + ) + actual = IAMClient.service_account_path(project, service_account) + assert expected == actual + + +def test_parse_service_account_path(): + expected = { + "project": "winkle", + "service_account": "nautilus", + } + path = IAMClient.service_account_path(**expected) + + # Check that the path construction is reversible. + actual = IAMClient.parse_service_account_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = IAMClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = IAMClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = IAMClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = IAMClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = IAMClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = IAMClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = IAMClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = IAMClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = IAMClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format( + project=project, + ) + actual = IAMClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = IAMClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = IAMClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = IAMClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = IAMClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = IAMClient.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.IAMTransport, "_prep_wrapped_messages") as prep: + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.IAMTransport, "_prep_wrapped_messages") as prep: + transport_class = IAMClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = IAMAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = IAMClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "grpc", + ] + for transport in transports: + client = IAMClient( + 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", + [ + (IAMClient, transports.IAMGrpcTransport), + (IAMAsyncClient, transports.IAMGrpcAsyncIOTransport), + ], +) +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, + )