From 4419e5fc292e9a89f8f468a7db038a9bf62ad35e Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 15 Dec 2023 19:33:29 -0500 Subject: [PATCH] feat: Add custom constraints CRUD APIs, proper etag support in Org Policy Update/Delete API (#257) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: Add custom constraints CRUD APIs, proper etag support in Org Policy Update/Delete API docs: updated comments PiperOrigin-RevId: 591301652 Source-Link: https://github.com/googleapis/googleapis/commit/db5ce67d735d2ceb6fe925f3e317a3f30835cfd6 Source-Link: https://github.com/googleapis/googleapis-gen/commit/3c133266edaaf81b14c2dd8fd4705127dcbce06b Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiM2MxMzMyNjZlZGFhZjgxYjE0YzJkZDhmZDQ3MDUxMjdkY2JjZTA2YiJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: Owl Bot --- google/cloud/orgpolicy/__init__.py | 14 + google/cloud/orgpolicy_v2/__init__.py | 14 + google/cloud/orgpolicy_v2/gapic_metadata.json | 75 + .../services/org_policy/async_client.py | 745 ++- .../services/org_policy/client.py | 713 ++- .../services/org_policy/pagers.py | 128 + .../services/org_policy/transports/base.py | 124 + .../services/org_policy/transports/grpc.py | 224 +- .../org_policy/transports/grpc_asyncio.py | 230 +- .../services/org_policy/transports/rest.py | 824 ++- google/cloud/orgpolicy_v2/types/__init__.py | 14 + google/cloud/orgpolicy_v2/types/constraint.py | 200 +- google/cloud/orgpolicy_v2/types/orgpolicy.py | 302 +- ...g_policy_create_custom_constraint_async.py | 52 + ...rg_policy_create_custom_constraint_sync.py | 52 + ...g_policy_delete_custom_constraint_async.py | 50 + ...rg_policy_delete_custom_constraint_sync.py | 50 + ..._org_policy_get_custom_constraint_async.py | 52 + ...d_org_policy_get_custom_constraint_sync.py | 52 + ...rg_policy_list_custom_constraints_async.py | 53 + ...org_policy_list_custom_constraints_sync.py | 53 + ...g_policy_update_custom_constraint_async.py | 51 + ...rg_policy_update_custom_constraint_sync.py | 51 + ...et_metadata_google.cloud.orgpolicy.v2.json | 1127 +++- scripts/fixup_orgpolicy_v2_keywords.py | 7 +- .../gapic/orgpolicy_v2/test_org_policy.py | 4742 ++++++++++++++--- 26 files changed, 8716 insertions(+), 1283 deletions(-) create mode 100644 samples/generated_samples/orgpolicy_v2_generated_org_policy_create_custom_constraint_async.py create mode 100644 samples/generated_samples/orgpolicy_v2_generated_org_policy_create_custom_constraint_sync.py create mode 100644 samples/generated_samples/orgpolicy_v2_generated_org_policy_delete_custom_constraint_async.py create mode 100644 samples/generated_samples/orgpolicy_v2_generated_org_policy_delete_custom_constraint_sync.py create mode 100644 samples/generated_samples/orgpolicy_v2_generated_org_policy_get_custom_constraint_async.py create mode 100644 samples/generated_samples/orgpolicy_v2_generated_org_policy_get_custom_constraint_sync.py create mode 100644 samples/generated_samples/orgpolicy_v2_generated_org_policy_list_custom_constraints_async.py create mode 100644 samples/generated_samples/orgpolicy_v2_generated_org_policy_list_custom_constraints_sync.py create mode 100644 samples/generated_samples/orgpolicy_v2_generated_org_policy_update_custom_constraint_async.py create mode 100644 samples/generated_samples/orgpolicy_v2_generated_org_policy_update_custom_constraint_sync.py diff --git a/google/cloud/orgpolicy/__init__.py b/google/cloud/orgpolicy/__init__.py index 583a083..1d74e6a 100644 --- a/google/cloud/orgpolicy/__init__.py +++ b/google/cloud/orgpolicy/__init__.py @@ -24,33 +24,47 @@ ) from google.cloud.orgpolicy_v2.types.constraint import Constraint +from google.cloud.orgpolicy_v2.types.constraint import CustomConstraint from google.cloud.orgpolicy_v2.types.orgpolicy import AlternatePolicySpec +from google.cloud.orgpolicy_v2.types.orgpolicy import CreateCustomConstraintRequest from google.cloud.orgpolicy_v2.types.orgpolicy import CreatePolicyRequest +from google.cloud.orgpolicy_v2.types.orgpolicy import DeleteCustomConstraintRequest from google.cloud.orgpolicy_v2.types.orgpolicy import DeletePolicyRequest +from google.cloud.orgpolicy_v2.types.orgpolicy import GetCustomConstraintRequest from google.cloud.orgpolicy_v2.types.orgpolicy import GetEffectivePolicyRequest from google.cloud.orgpolicy_v2.types.orgpolicy import GetPolicyRequest from google.cloud.orgpolicy_v2.types.orgpolicy import ListConstraintsRequest from google.cloud.orgpolicy_v2.types.orgpolicy import ListConstraintsResponse +from google.cloud.orgpolicy_v2.types.orgpolicy import ListCustomConstraintsRequest +from google.cloud.orgpolicy_v2.types.orgpolicy import ListCustomConstraintsResponse from google.cloud.orgpolicy_v2.types.orgpolicy import ListPoliciesRequest from google.cloud.orgpolicy_v2.types.orgpolicy import ListPoliciesResponse from google.cloud.orgpolicy_v2.types.orgpolicy import Policy from google.cloud.orgpolicy_v2.types.orgpolicy import PolicySpec +from google.cloud.orgpolicy_v2.types.orgpolicy import UpdateCustomConstraintRequest from google.cloud.orgpolicy_v2.types.orgpolicy import UpdatePolicyRequest __all__ = ( "OrgPolicyClient", "OrgPolicyAsyncClient", "Constraint", + "CustomConstraint", "AlternatePolicySpec", + "CreateCustomConstraintRequest", "CreatePolicyRequest", + "DeleteCustomConstraintRequest", "DeletePolicyRequest", + "GetCustomConstraintRequest", "GetEffectivePolicyRequest", "GetPolicyRequest", "ListConstraintsRequest", "ListConstraintsResponse", + "ListCustomConstraintsRequest", + "ListCustomConstraintsResponse", "ListPoliciesRequest", "ListPoliciesResponse", "Policy", "PolicySpec", + "UpdateCustomConstraintRequest", "UpdatePolicyRequest", ) diff --git a/google/cloud/orgpolicy_v2/__init__.py b/google/cloud/orgpolicy_v2/__init__.py index fdd3724..65811eb 100644 --- a/google/cloud/orgpolicy_v2/__init__.py +++ b/google/cloud/orgpolicy_v2/__init__.py @@ -22,33 +22,47 @@ from .services.org_policy import OrgPolicyAsyncClient from .types.constraint import Constraint +from .types.constraint import CustomConstraint from .types.orgpolicy import AlternatePolicySpec +from .types.orgpolicy import CreateCustomConstraintRequest from .types.orgpolicy import CreatePolicyRequest +from .types.orgpolicy import DeleteCustomConstraintRequest from .types.orgpolicy import DeletePolicyRequest +from .types.orgpolicy import GetCustomConstraintRequest from .types.orgpolicy import GetEffectivePolicyRequest from .types.orgpolicy import GetPolicyRequest from .types.orgpolicy import ListConstraintsRequest from .types.orgpolicy import ListConstraintsResponse +from .types.orgpolicy import ListCustomConstraintsRequest +from .types.orgpolicy import ListCustomConstraintsResponse from .types.orgpolicy import ListPoliciesRequest from .types.orgpolicy import ListPoliciesResponse from .types.orgpolicy import Policy from .types.orgpolicy import PolicySpec +from .types.orgpolicy import UpdateCustomConstraintRequest from .types.orgpolicy import UpdatePolicyRequest __all__ = ( "OrgPolicyAsyncClient", "AlternatePolicySpec", "Constraint", + "CreateCustomConstraintRequest", "CreatePolicyRequest", + "CustomConstraint", + "DeleteCustomConstraintRequest", "DeletePolicyRequest", + "GetCustomConstraintRequest", "GetEffectivePolicyRequest", "GetPolicyRequest", "ListConstraintsRequest", "ListConstraintsResponse", + "ListCustomConstraintsRequest", + "ListCustomConstraintsResponse", "ListPoliciesRequest", "ListPoliciesResponse", "OrgPolicyClient", "Policy", "PolicySpec", + "UpdateCustomConstraintRequest", "UpdatePolicyRequest", ) diff --git a/google/cloud/orgpolicy_v2/gapic_metadata.json b/google/cloud/orgpolicy_v2/gapic_metadata.json index acfef15..d7aa35d 100644 --- a/google/cloud/orgpolicy_v2/gapic_metadata.json +++ b/google/cloud/orgpolicy_v2/gapic_metadata.json @@ -10,16 +10,31 @@ "grpc": { "libraryClient": "OrgPolicyClient", "rpcs": { + "CreateCustomConstraint": { + "methods": [ + "create_custom_constraint" + ] + }, "CreatePolicy": { "methods": [ "create_policy" ] }, + "DeleteCustomConstraint": { + "methods": [ + "delete_custom_constraint" + ] + }, "DeletePolicy": { "methods": [ "delete_policy" ] }, + "GetCustomConstraint": { + "methods": [ + "get_custom_constraint" + ] + }, "GetEffectivePolicy": { "methods": [ "get_effective_policy" @@ -35,11 +50,21 @@ "list_constraints" ] }, + "ListCustomConstraints": { + "methods": [ + "list_custom_constraints" + ] + }, "ListPolicies": { "methods": [ "list_policies" ] }, + "UpdateCustomConstraint": { + "methods": [ + "update_custom_constraint" + ] + }, "UpdatePolicy": { "methods": [ "update_policy" @@ -50,16 +75,31 @@ "grpc-async": { "libraryClient": "OrgPolicyAsyncClient", "rpcs": { + "CreateCustomConstraint": { + "methods": [ + "create_custom_constraint" + ] + }, "CreatePolicy": { "methods": [ "create_policy" ] }, + "DeleteCustomConstraint": { + "methods": [ + "delete_custom_constraint" + ] + }, "DeletePolicy": { "methods": [ "delete_policy" ] }, + "GetCustomConstraint": { + "methods": [ + "get_custom_constraint" + ] + }, "GetEffectivePolicy": { "methods": [ "get_effective_policy" @@ -75,11 +115,21 @@ "list_constraints" ] }, + "ListCustomConstraints": { + "methods": [ + "list_custom_constraints" + ] + }, "ListPolicies": { "methods": [ "list_policies" ] }, + "UpdateCustomConstraint": { + "methods": [ + "update_custom_constraint" + ] + }, "UpdatePolicy": { "methods": [ "update_policy" @@ -90,16 +140,31 @@ "rest": { "libraryClient": "OrgPolicyClient", "rpcs": { + "CreateCustomConstraint": { + "methods": [ + "create_custom_constraint" + ] + }, "CreatePolicy": { "methods": [ "create_policy" ] }, + "DeleteCustomConstraint": { + "methods": [ + "delete_custom_constraint" + ] + }, "DeletePolicy": { "methods": [ "delete_policy" ] }, + "GetCustomConstraint": { + "methods": [ + "get_custom_constraint" + ] + }, "GetEffectivePolicy": { "methods": [ "get_effective_policy" @@ -115,11 +180,21 @@ "list_constraints" ] }, + "ListCustomConstraints": { + "methods": [ + "list_custom_constraints" + ] + }, "ListPolicies": { "methods": [ "list_policies" ] }, + "UpdateCustomConstraint": { + "methods": [ + "update_custom_constraint" + ] + }, "UpdatePolicy": { "methods": [ "update_policy" diff --git a/google/cloud/orgpolicy_v2/services/org_policy/async_client.py b/google/cloud/orgpolicy_v2/services/org_policy/async_client.py index 1f28749..5a5cda1 100644 --- a/google/cloud/orgpolicy_v2/services/org_policy/async_client.py +++ b/google/cloud/orgpolicy_v2/services/org_policy/async_client.py @@ -45,6 +45,7 @@ from google.cloud.orgpolicy_v2.services.org_policy import pagers from google.cloud.orgpolicy_v2.types import constraint from google.cloud.orgpolicy_v2.types import orgpolicy +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import OrgPolicyTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import OrgPolicyGrpcAsyncIOTransport from .client import OrgPolicyClient @@ -53,26 +54,26 @@ class OrgPolicyAsyncClient: """An interface for managing organization policies. - The Cloud Org Policy service provides a simple mechanism for - organizations to restrict the allowed configurations across their - entire Cloud Resource hierarchy. + The Organization Policy Service provides a simple mechanism for + organizations to restrict the allowed configurations across + their entire resource hierarchy. - You can use a ``policy`` to configure restrictions in Cloud - resources. For example, you can enforce a ``policy`` that restricts - which Google Cloud Platform APIs can be activated in a certain part - of your resource hierarchy, or prevents serial port access to VM - instances in a particular folder. + You can use a policy to configure restrictions on resources. For + example, you can enforce a policy that restricts which Google + Cloud APIs can be activated in a certain part of your resource + hierarchy, or prevents serial port access to VM instances in a + particular folder. - ``Policies`` are inherited down through the resource hierarchy. A - ``policy`` applied to a parent resource automatically applies to all - its child resources unless overridden with a ``policy`` lower in the + Policies are inherited down through the resource hierarchy. A + policy applied to a parent resource automatically applies to all + its child resources unless overridden with a policy lower in the hierarchy. - A ``constraint`` defines an aspect of a resource's configuration - that can be controlled by an organization's policy administrator. - ``Policies`` are a collection of ``constraints`` that defines their - allowable configuration on a particular resource and its child - resources. + A constraint defines an aspect of a resource's configuration + that can be controlled by an organization's policy + administrator. Policies are a collection of constraints that + defines their allowable configuration on a particular resource + and its child resources. """ _client: OrgPolicyClient @@ -82,6 +83,10 @@ class OrgPolicyAsyncClient: constraint_path = staticmethod(OrgPolicyClient.constraint_path) parse_constraint_path = staticmethod(OrgPolicyClient.parse_constraint_path) + custom_constraint_path = staticmethod(OrgPolicyClient.custom_constraint_path) + parse_custom_constraint_path = staticmethod( + OrgPolicyClient.parse_custom_constraint_path + ) policy_path = staticmethod(OrgPolicyClient.policy_path) parse_policy_path = staticmethod(OrgPolicyClient.parse_policy_path) common_billing_account_path = staticmethod( @@ -241,8 +246,8 @@ async def list_constraints( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListConstraintsAsyncPager: - r"""Lists ``Constraints`` that could be applied on the specified - resource. + r"""Lists constraints that could be applied on the + specified resource. .. code-block:: python @@ -277,7 +282,7 @@ async def sample_list_constraints(): [google.cloud.orgpolicy.v2.OrgPolicy.ListConstraints] method. parent (:class:`str`): - Required. The Cloud resource that parents the + Required. The Google Cloud resource that parents the constraint. Must be in one of the following forms: - ``projects/{project_number}`` @@ -374,8 +379,8 @@ async def list_policies( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListPoliciesAsyncPager: - r"""Retrieves all of the ``Policies`` that exist on a particular - resource. + r"""Retrieves all of the policies that exist on a + particular resource. .. code-block:: python @@ -410,9 +415,10 @@ async def sample_list_policies(): [google.cloud.orgpolicy.v2.OrgPolicy.ListPolicies] method. parent (:class:`str`): - Required. The target Cloud resource that parents the set - of constraints and policies that will be returned from - this call. Must be in one of the following forms: + Required. The target Google Cloud resource that parents + the set of constraints and policies that will be + returned from this call. Must be in one of the following + forms: - ``projects/{project_number}`` - ``projects/{project_id}`` @@ -432,7 +438,7 @@ async def sample_list_policies(): google.cloud.orgpolicy_v2.services.org_policy.pagers.ListPoliciesAsyncPager: The response returned from the [ListPolicies] [google.cloud.orgpolicy.v2.OrgPolicy.ListPolicies] - method. It will be empty if no Policies are set on + method. It will be empty if no policies are set on the resource. Iterating over this object will yield results and @@ -509,11 +515,11 @@ async def get_policy( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> orgpolicy.Policy: - r"""Gets a ``Policy`` on a resource. + r"""Gets a policy on a resource. - If no ``Policy`` is set on the resource, NOT_FOUND is returned. + If no policy is set on the resource, ``NOT_FOUND`` is returned. The ``etag`` value can be used with ``UpdatePolicy()`` to update - a ``Policy`` during read-modify-write. + a policy during read-modify-write. .. code-block:: python @@ -546,8 +552,9 @@ async def sample_get_policy(): The request object. The request sent to the [GetPolicy] [google.cloud.orgpolicy.v2.OrgPolicy.GetPolicy] method. name (:class:`str`): - Required. Resource name of the policy. See ``Policy`` - for naming requirements. + Required. Resource name of the policy. See + [Policy][google.cloud.orgpolicy.v2.Policy] for naming + requirements. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -560,8 +567,10 @@ async def sample_get_policy(): Returns: google.cloud.orgpolicy_v2.types.Policy: - Defines a Cloud Organization Policy which is used to specify Constraints - for configurations of Cloud Platform resources. + Defines an organization policy which + is used to specify constraints for + configurations of Google Cloud + resources. """ # Create or coerce a protobuf request object. @@ -625,10 +634,10 @@ async def get_effective_policy( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> orgpolicy.Policy: - r"""Gets the effective ``Policy`` on a resource. This is the result - of merging ``Policies`` in the resource hierarchy and evaluating - conditions. The returned ``Policy`` will not have an ``etag`` or - ``condition`` set because it is a computed ``Policy`` across + r"""Gets the effective policy on a resource. This is the result of + merging policies in the resource hierarchy and evaluating + conditions. The returned policy will not have an ``etag`` or + ``condition`` set because it is an evaluated policy across multiple resources. Subtrees of Resource Manager resource hierarchy with 'under:' prefix will not be expanded. @@ -665,7 +674,8 @@ async def sample_get_effective_policy(): method. name (:class:`str`): Required. The effective policy to compute. See - ``Policy`` for naming rules. + [Policy][google.cloud.orgpolicy.v2.Policy] for naming + requirements. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -678,8 +688,10 @@ async def sample_get_effective_policy(): Returns: google.cloud.orgpolicy_v2.types.Policy: - Defines a Cloud Organization Policy which is used to specify Constraints - for configurations of Cloud Platform resources. + Defines an organization policy which + is used to specify constraints for + configurations of Google Cloud + resources. """ # Create or coerce a protobuf request object. @@ -744,13 +756,13 @@ async def create_policy( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> orgpolicy.Policy: - r"""Creates a Policy. + r"""Creates a policy. Returns a ``google.rpc.Status`` with ``google.rpc.Code.NOT_FOUND`` if the constraint does not exist. Returns a ``google.rpc.Status`` with ``google.rpc.Code.ALREADY_EXISTS`` if the policy already exists - on the given Cloud resource. + on the given Google Cloud resource. .. code-block:: python @@ -784,8 +796,8 @@ async def sample_create_policy(): [google.cloud.orgpolicy.v2.OrgPolicy.CreatePolicy] method. parent (:class:`str`): - Required. The Cloud resource that will parent the new - Policy. Must be in one of the following forms: + Required. The Google Cloud resource that will parent the + new policy. Must be in one of the following forms: - ``projects/{project_number}`` - ``projects/{project_id}`` @@ -796,7 +808,7 @@ async def sample_create_policy(): on the ``request`` instance; if ``request`` is provided, this should not be set. policy (:class:`google.cloud.orgpolicy_v2.types.Policy`): - Required. ``Policy`` to create. + Required. Policy to create. This corresponds to the ``policy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -808,8 +820,10 @@ async def sample_create_policy(): Returns: google.cloud.orgpolicy_v2.types.Policy: - Defines a Cloud Organization Policy which is used to specify Constraints - for configurations of Cloud Platform resources. + Defines an organization policy which + is used to specify constraints for + configurations of Google Cloud + resources. """ # Create or coerce a protobuf request object. @@ -875,7 +889,7 @@ async def update_policy( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> orgpolicy.Policy: - r"""Updates a Policy. + r"""Updates a policy. Returns a ``google.rpc.Status`` with ``google.rpc.Code.NOT_FOUND`` if the constraint or the policy do @@ -917,7 +931,7 @@ async def sample_update_policy(): [google.cloud.orgpolicy.v2.OrgPolicy.UpdatePolicy] method. policy (:class:`google.cloud.orgpolicy_v2.types.Policy`): - Required. ``Policy`` to update. + Required. Policy to update. This corresponds to the ``policy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -929,8 +943,10 @@ async def sample_update_policy(): Returns: google.cloud.orgpolicy_v2.types.Policy: - Defines a Cloud Organization Policy which is used to specify Constraints - for configurations of Cloud Platform resources. + Defines an organization policy which + is used to specify constraints for + configurations of Google Cloud + resources. """ # Create or coerce a protobuf request object. @@ -996,11 +1012,11 @@ async def delete_policy( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: - r"""Deletes a Policy. + r"""Deletes a policy. Returns a ``google.rpc.Status`` with - ``google.rpc.Code.NOT_FOUND`` if the constraint or Org Policy - does not exist. + ``google.rpc.Code.NOT_FOUND`` if the constraint or organization + policy does not exist. .. code-block:: python @@ -1031,8 +1047,9 @@ async def sample_delete_policy(): [google.cloud.orgpolicy.v2.OrgPolicy.DeletePolicy] method. name (:class:`str`): - Required. Name of the policy to delete. See ``Policy`` - for naming rules. + Required. Name of the policy to + delete. See the policy entry for naming + rules. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1092,6 +1109,624 @@ async def sample_delete_policy(): metadata=metadata, ) + async def create_custom_constraint( + self, + request: Optional[Union[orgpolicy.CreateCustomConstraintRequest, dict]] = None, + *, + parent: Optional[str] = None, + custom_constraint: Optional[constraint.CustomConstraint] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> constraint.CustomConstraint: + r"""Creates a custom constraint. + + Returns a ``google.rpc.Status`` with + ``google.rpc.Code.NOT_FOUND`` if the organization does not + exist. Returns a ``google.rpc.Status`` with + ``google.rpc.Code.ALREADY_EXISTS`` if the constraint already + exists on the given organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import orgpolicy_v2 + + async def sample_create_custom_constraint(): + # Create a client + client = orgpolicy_v2.OrgPolicyAsyncClient() + + # Initialize request argument(s) + request = orgpolicy_v2.CreateCustomConstraintRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_custom_constraint(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orgpolicy_v2.types.CreateCustomConstraintRequest, dict]]): + The request object. The request sent to the [CreateCustomConstraintRequest] + [google.cloud.orgpolicy.v2.OrgPolicy.CreateCustomConstraint] + method. + parent (:class:`str`): + Required. Must be in the following form: + + - ``organizations/{organization_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_constraint (:class:`google.cloud.orgpolicy_v2.types.CustomConstraint`): + Required. Custom constraint to + create. + + This corresponds to the ``custom_constraint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.orgpolicy_v2.types.CustomConstraint: + A custom constraint defined by customers which can *only* be applied to the + given resource types and organization. + + By creating a custom constraint, customers can apply + policies of this custom constraint. *Creating a + custom constraint itself does NOT apply any policy + enforcement*. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, custom_constraint]) + if request is 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 = orgpolicy.CreateCustomConstraintRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if custom_constraint is not None: + request.custom_constraint = custom_constraint + + # 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_custom_constraint, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.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((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_custom_constraint( + self, + request: Optional[Union[orgpolicy.UpdateCustomConstraintRequest, dict]] = None, + *, + custom_constraint: Optional[constraint.CustomConstraint] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> constraint.CustomConstraint: + r"""Updates a custom constraint. + + Returns a ``google.rpc.Status`` with + ``google.rpc.Code.NOT_FOUND`` if the constraint does not exist. + + Note: the supplied policy will perform a full overwrite of all + fields. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import orgpolicy_v2 + + async def sample_update_custom_constraint(): + # Create a client + client = orgpolicy_v2.OrgPolicyAsyncClient() + + # Initialize request argument(s) + request = orgpolicy_v2.UpdateCustomConstraintRequest( + ) + + # Make the request + response = await client.update_custom_constraint(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orgpolicy_v2.types.UpdateCustomConstraintRequest, dict]]): + The request object. The request sent to the [UpdateCustomConstraintRequest] + [google.cloud.orgpolicy.v2.OrgPolicy.UpdateCustomConstraint] + method. + custom_constraint (:class:`google.cloud.orgpolicy_v2.types.CustomConstraint`): + Required. ``CustomConstraint`` to update. + This corresponds to the ``custom_constraint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.orgpolicy_v2.types.CustomConstraint: + A custom constraint defined by customers which can *only* be applied to the + given resource types and organization. + + By creating a custom constraint, customers can apply + policies of this custom constraint. *Creating a + custom constraint itself does NOT apply any policy + enforcement*. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([custom_constraint]) + if request is 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 = orgpolicy.UpdateCustomConstraintRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if custom_constraint is not None: + request.custom_constraint = custom_constraint + + # 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_custom_constraint, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.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( + (("custom_constraint.name", request.custom_constraint.name),) + ), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_custom_constraint( + self, + request: Optional[Union[orgpolicy.GetCustomConstraintRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> constraint.CustomConstraint: + r"""Gets a custom constraint. + + Returns a ``google.rpc.Status`` with + ``google.rpc.Code.NOT_FOUND`` if the custom constraint does not + exist. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import orgpolicy_v2 + + async def sample_get_custom_constraint(): + # Create a client + client = orgpolicy_v2.OrgPolicyAsyncClient() + + # Initialize request argument(s) + request = orgpolicy_v2.GetCustomConstraintRequest( + name="name_value", + ) + + # Make the request + response = await client.get_custom_constraint(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.orgpolicy_v2.types.GetCustomConstraintRequest, dict]]): + The request object. The request sent to the [GetCustomConstraint] + [google.cloud.orgpolicy.v2.OrgPolicy.GetCustomConstraint] + method. + name (:class:`str`): + Required. Resource name of the custom + constraint. See the custom constraint + entry for naming requirements. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.orgpolicy_v2.types.CustomConstraint: + A custom constraint defined by customers which can *only* be applied to the + given resource types and organization. + + By creating a custom constraint, customers can apply + policies of this custom constraint. *Creating a + custom constraint itself does NOT apply any policy + enforcement*. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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 = orgpolicy.GetCustomConstraintRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_custom_constraint, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.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),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_custom_constraints( + self, + request: Optional[Union[orgpolicy.ListCustomConstraintsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCustomConstraintsAsyncPager: + r"""Retrieves all of the custom constraints that exist on + a particular organization 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 orgpolicy_v2 + + async def sample_list_custom_constraints(): + # Create a client + client = orgpolicy_v2.OrgPolicyAsyncClient() + + # Initialize request argument(s) + request = orgpolicy_v2.ListCustomConstraintsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_custom_constraints(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.orgpolicy_v2.types.ListCustomConstraintsRequest, dict]]): + The request object. The request sent to the [ListCustomConstraints] + [google.cloud.orgpolicy.v2.OrgPolicy.ListCustomConstraints] + method. + parent (:class:`str`): + Required. The target Google Cloud resource that parents + the set of custom constraints that will be returned from + this call. Must be in one of the following forms: + + - ``organizations/{organization_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.orgpolicy_v2.services.org_policy.pagers.ListCustomConstraintsAsyncPager: + The response returned from the [ListCustomConstraints] + [google.cloud.orgpolicy.v2.OrgPolicy.ListCustomConstraints] + method. It will be empty if no custom constraints are + set on the organization resource. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = orgpolicy.ListCustomConstraintsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # 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_custom_constraints, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.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((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListCustomConstraintsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_custom_constraint( + self, + request: Optional[Union[orgpolicy.DeleteCustomConstraintRequest, dict]] = 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 custom constraint. + + Returns a ``google.rpc.Status`` with + ``google.rpc.Code.NOT_FOUND`` if the constraint does not exist. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import orgpolicy_v2 + + async def sample_delete_custom_constraint(): + # Create a client + client = orgpolicy_v2.OrgPolicyAsyncClient() + + # Initialize request argument(s) + request = orgpolicy_v2.DeleteCustomConstraintRequest( + name="name_value", + ) + + # Make the request + await client.delete_custom_constraint(request=request) + + Args: + request (Optional[Union[google.cloud.orgpolicy_v2.types.DeleteCustomConstraintRequest, dict]]): + The request object. The request sent to the [DeleteCustomConstraint] + [google.cloud.orgpolicy.v2.OrgPolicy.DeleteCustomConstraint] + method. + name (:class:`str`): + Required. Name of the custom + constraint to delete. See the custom + constraint entry for naming rules. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be 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 = orgpolicy.DeleteCustomConstraintRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply 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_custom_constraint, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.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),)), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + async def __aenter__(self) -> "OrgPolicyAsyncClient": return self diff --git a/google/cloud/orgpolicy_v2/services/org_policy/client.py b/google/cloud/orgpolicy_v2/services/org_policy/client.py index 7ab4409..fbb0b61 100644 --- a/google/cloud/orgpolicy_v2/services/org_policy/client.py +++ b/google/cloud/orgpolicy_v2/services/org_policy/client.py @@ -49,6 +49,7 @@ from google.cloud.orgpolicy_v2.services.org_policy import pagers from google.cloud.orgpolicy_v2.types import constraint from google.cloud.orgpolicy_v2.types import orgpolicy +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import OrgPolicyTransport, DEFAULT_CLIENT_INFO from .transports.grpc import OrgPolicyGrpcTransport from .transports.grpc_asyncio import OrgPolicyGrpcAsyncIOTransport @@ -93,26 +94,26 @@ def get_transport_class( class OrgPolicyClient(metaclass=OrgPolicyClientMeta): """An interface for managing organization policies. - The Cloud Org Policy service provides a simple mechanism for - organizations to restrict the allowed configurations across their - entire Cloud Resource hierarchy. + The Organization Policy Service provides a simple mechanism for + organizations to restrict the allowed configurations across + their entire resource hierarchy. - You can use a ``policy`` to configure restrictions in Cloud - resources. For example, you can enforce a ``policy`` that restricts - which Google Cloud Platform APIs can be activated in a certain part - of your resource hierarchy, or prevents serial port access to VM - instances in a particular folder. + You can use a policy to configure restrictions on resources. For + example, you can enforce a policy that restricts which Google + Cloud APIs can be activated in a certain part of your resource + hierarchy, or prevents serial port access to VM instances in a + particular folder. - ``Policies`` are inherited down through the resource hierarchy. A - ``policy`` applied to a parent resource automatically applies to all - its child resources unless overridden with a ``policy`` lower in the + Policies are inherited down through the resource hierarchy. A + policy applied to a parent resource automatically applies to all + its child resources unless overridden with a policy lower in the hierarchy. - A ``constraint`` defines an aspect of a resource's configuration - that can be controlled by an organization's policy administrator. - ``Policies`` are a collection of ``constraints`` that defines their - allowable configuration on a particular resource and its child - resources. + A constraint defines an aspect of a resource's configuration + that can be controlled by an organization's policy + administrator. Policies are a collection of constraints that + defines their allowable configuration on a particular resource + and its child resources. """ @staticmethod @@ -216,6 +217,28 @@ def parse_constraint_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def custom_constraint_path( + organization: str, + custom_constraint: str, + ) -> str: + """Returns a fully-qualified custom_constraint string.""" + return ( + "organizations/{organization}/customConstraints/{custom_constraint}".format( + organization=organization, + custom_constraint=custom_constraint, + ) + ) + + @staticmethod + def parse_custom_constraint_path(path: str) -> Dict[str, str]: + """Parses a custom_constraint path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/customConstraints/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def policy_path( project: str, @@ -486,8 +509,8 @@ def list_constraints( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListConstraintsPager: - r"""Lists ``Constraints`` that could be applied on the specified - resource. + r"""Lists constraints that could be applied on the + specified resource. .. code-block:: python @@ -522,7 +545,7 @@ def sample_list_constraints(): [google.cloud.orgpolicy.v2.OrgPolicy.ListConstraints] method. parent (str): - Required. The Cloud resource that parents the + Required. The Google Cloud resource that parents the constraint. Must be in one of the following forms: - ``projects/{project_number}`` @@ -609,8 +632,8 @@ def list_policies( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListPoliciesPager: - r"""Retrieves all of the ``Policies`` that exist on a particular - resource. + r"""Retrieves all of the policies that exist on a + particular resource. .. code-block:: python @@ -645,9 +668,10 @@ def sample_list_policies(): [google.cloud.orgpolicy.v2.OrgPolicy.ListPolicies] method. parent (str): - Required. The target Cloud resource that parents the set - of constraints and policies that will be returned from - this call. Must be in one of the following forms: + Required. The target Google Cloud resource that parents + the set of constraints and policies that will be + returned from this call. Must be in one of the following + forms: - ``projects/{project_number}`` - ``projects/{project_id}`` @@ -667,7 +691,7 @@ def sample_list_policies(): google.cloud.orgpolicy_v2.services.org_policy.pagers.ListPoliciesPager: The response returned from the [ListPolicies] [google.cloud.orgpolicy.v2.OrgPolicy.ListPolicies] - method. It will be empty if no Policies are set on + method. It will be empty if no policies are set on the resource. Iterating over this object will yield results and @@ -734,11 +758,11 @@ def get_policy( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> orgpolicy.Policy: - r"""Gets a ``Policy`` on a resource. + r"""Gets a policy on a resource. - If no ``Policy`` is set on the resource, NOT_FOUND is returned. + If no policy is set on the resource, ``NOT_FOUND`` is returned. The ``etag`` value can be used with ``UpdatePolicy()`` to update - a ``Policy`` during read-modify-write. + a policy during read-modify-write. .. code-block:: python @@ -771,8 +795,9 @@ def sample_get_policy(): The request object. The request sent to the [GetPolicy] [google.cloud.orgpolicy.v2.OrgPolicy.GetPolicy] method. name (str): - Required. Resource name of the policy. See ``Policy`` - for naming requirements. + Required. Resource name of the policy. See + [Policy][google.cloud.orgpolicy.v2.Policy] for naming + requirements. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -785,8 +810,10 @@ def sample_get_policy(): Returns: google.cloud.orgpolicy_v2.types.Policy: - Defines a Cloud Organization Policy which is used to specify Constraints - for configurations of Cloud Platform resources. + Defines an organization policy which + is used to specify constraints for + configurations of Google Cloud + resources. """ # Create or coerce a protobuf request object. @@ -840,10 +867,10 @@ def get_effective_policy( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> orgpolicy.Policy: - r"""Gets the effective ``Policy`` on a resource. This is the result - of merging ``Policies`` in the resource hierarchy and evaluating - conditions. The returned ``Policy`` will not have an ``etag`` or - ``condition`` set because it is a computed ``Policy`` across + r"""Gets the effective policy on a resource. This is the result of + merging policies in the resource hierarchy and evaluating + conditions. The returned policy will not have an ``etag`` or + ``condition`` set because it is an evaluated policy across multiple resources. Subtrees of Resource Manager resource hierarchy with 'under:' prefix will not be expanded. @@ -880,7 +907,8 @@ def sample_get_effective_policy(): method. name (str): Required. The effective policy to compute. See - ``Policy`` for naming rules. + [Policy][google.cloud.orgpolicy.v2.Policy] for naming + requirements. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -893,8 +921,10 @@ def sample_get_effective_policy(): Returns: google.cloud.orgpolicy_v2.types.Policy: - Defines a Cloud Organization Policy which is used to specify Constraints - for configurations of Cloud Platform resources. + Defines an organization policy which + is used to specify constraints for + configurations of Google Cloud + resources. """ # Create or coerce a protobuf request object. @@ -949,13 +979,13 @@ def create_policy( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> orgpolicy.Policy: - r"""Creates a Policy. + r"""Creates a policy. Returns a ``google.rpc.Status`` with ``google.rpc.Code.NOT_FOUND`` if the constraint does not exist. Returns a ``google.rpc.Status`` with ``google.rpc.Code.ALREADY_EXISTS`` if the policy already exists - on the given Cloud resource. + on the given Google Cloud resource. .. code-block:: python @@ -989,8 +1019,8 @@ def sample_create_policy(): [google.cloud.orgpolicy.v2.OrgPolicy.CreatePolicy] method. parent (str): - Required. The Cloud resource that will parent the new - Policy. Must be in one of the following forms: + Required. The Google Cloud resource that will parent the + new policy. Must be in one of the following forms: - ``projects/{project_number}`` - ``projects/{project_id}`` @@ -1001,7 +1031,7 @@ def sample_create_policy(): on the ``request`` instance; if ``request`` is provided, this should not be set. policy (google.cloud.orgpolicy_v2.types.Policy): - Required. ``Policy`` to create. + Required. Policy to create. This corresponds to the ``policy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1013,8 +1043,10 @@ def sample_create_policy(): Returns: google.cloud.orgpolicy_v2.types.Policy: - Defines a Cloud Organization Policy which is used to specify Constraints - for configurations of Cloud Platform resources. + Defines an organization policy which + is used to specify constraints for + configurations of Google Cloud + resources. """ # Create or coerce a protobuf request object. @@ -1070,7 +1102,7 @@ def update_policy( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> orgpolicy.Policy: - r"""Updates a Policy. + r"""Updates a policy. Returns a ``google.rpc.Status`` with ``google.rpc.Code.NOT_FOUND`` if the constraint or the policy do @@ -1112,7 +1144,7 @@ def sample_update_policy(): [google.cloud.orgpolicy.v2.OrgPolicy.UpdatePolicy] method. policy (google.cloud.orgpolicy_v2.types.Policy): - Required. ``Policy`` to update. + Required. Policy to update. This corresponds to the ``policy`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1124,8 +1156,10 @@ def sample_update_policy(): Returns: google.cloud.orgpolicy_v2.types.Policy: - Defines a Cloud Organization Policy which is used to specify Constraints - for configurations of Cloud Platform resources. + Defines an organization policy which + is used to specify constraints for + configurations of Google Cloud + resources. """ # Create or coerce a protobuf request object. @@ -1181,11 +1215,11 @@ def delete_policy( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> None: - r"""Deletes a Policy. + r"""Deletes a policy. Returns a ``google.rpc.Status`` with - ``google.rpc.Code.NOT_FOUND`` if the constraint or Org Policy - does not exist. + ``google.rpc.Code.NOT_FOUND`` if the constraint or organization + policy does not exist. .. code-block:: python @@ -1216,8 +1250,9 @@ def sample_delete_policy(): [google.cloud.orgpolicy.v2.OrgPolicy.DeletePolicy] method. name (str): - Required. Name of the policy to delete. See ``Policy`` - for naming rules. + Required. Name of the policy to + delete. See the policy entry for naming + rules. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1267,6 +1302,574 @@ def sample_delete_policy(): metadata=metadata, ) + def create_custom_constraint( + self, + request: Optional[Union[orgpolicy.CreateCustomConstraintRequest, dict]] = None, + *, + parent: Optional[str] = None, + custom_constraint: Optional[constraint.CustomConstraint] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> constraint.CustomConstraint: + r"""Creates a custom constraint. + + Returns a ``google.rpc.Status`` with + ``google.rpc.Code.NOT_FOUND`` if the organization does not + exist. Returns a ``google.rpc.Status`` with + ``google.rpc.Code.ALREADY_EXISTS`` if the constraint already + exists on the given organization. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import orgpolicy_v2 + + def sample_create_custom_constraint(): + # Create a client + client = orgpolicy_v2.OrgPolicyClient() + + # Initialize request argument(s) + request = orgpolicy_v2.CreateCustomConstraintRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_custom_constraint(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orgpolicy_v2.types.CreateCustomConstraintRequest, dict]): + The request object. The request sent to the [CreateCustomConstraintRequest] + [google.cloud.orgpolicy.v2.OrgPolicy.CreateCustomConstraint] + method. + parent (str): + Required. Must be in the following form: + + - ``organizations/{organization_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_constraint (google.cloud.orgpolicy_v2.types.CustomConstraint): + Required. Custom constraint to + create. + + This corresponds to the ``custom_constraint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.orgpolicy_v2.types.CustomConstraint: + A custom constraint defined by customers which can *only* be applied to the + given resource types and organization. + + By creating a custom constraint, customers can apply + policies of this custom constraint. *Creating a + custom constraint itself does NOT apply any policy + enforcement*. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, custom_constraint]) + if request is 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 orgpolicy.CreateCustomConstraintRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, orgpolicy.CreateCustomConstraintRequest): + request = orgpolicy.CreateCustomConstraintRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if custom_constraint is not None: + request.custom_constraint = custom_constraint + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_custom_constraint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_custom_constraint( + self, + request: Optional[Union[orgpolicy.UpdateCustomConstraintRequest, dict]] = None, + *, + custom_constraint: Optional[constraint.CustomConstraint] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> constraint.CustomConstraint: + r"""Updates a custom constraint. + + Returns a ``google.rpc.Status`` with + ``google.rpc.Code.NOT_FOUND`` if the constraint does not exist. + + Note: the supplied policy will perform a full overwrite of all + fields. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import orgpolicy_v2 + + def sample_update_custom_constraint(): + # Create a client + client = orgpolicy_v2.OrgPolicyClient() + + # Initialize request argument(s) + request = orgpolicy_v2.UpdateCustomConstraintRequest( + ) + + # Make the request + response = client.update_custom_constraint(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orgpolicy_v2.types.UpdateCustomConstraintRequest, dict]): + The request object. The request sent to the [UpdateCustomConstraintRequest] + [google.cloud.orgpolicy.v2.OrgPolicy.UpdateCustomConstraint] + method. + custom_constraint (google.cloud.orgpolicy_v2.types.CustomConstraint): + Required. ``CustomConstraint`` to update. + This corresponds to the ``custom_constraint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.orgpolicy_v2.types.CustomConstraint: + A custom constraint defined by customers which can *only* be applied to the + given resource types and organization. + + By creating a custom constraint, customers can apply + policies of this custom constraint. *Creating a + custom constraint itself does NOT apply any policy + enforcement*. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([custom_constraint]) + if request is 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 orgpolicy.UpdateCustomConstraintRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, orgpolicy.UpdateCustomConstraintRequest): + request = orgpolicy.UpdateCustomConstraintRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if custom_constraint is not None: + request.custom_constraint = custom_constraint + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_custom_constraint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("custom_constraint.name", request.custom_constraint.name),) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_custom_constraint( + self, + request: Optional[Union[orgpolicy.GetCustomConstraintRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> constraint.CustomConstraint: + r"""Gets a custom constraint. + + Returns a ``google.rpc.Status`` with + ``google.rpc.Code.NOT_FOUND`` if the custom constraint does not + exist. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import orgpolicy_v2 + + def sample_get_custom_constraint(): + # Create a client + client = orgpolicy_v2.OrgPolicyClient() + + # Initialize request argument(s) + request = orgpolicy_v2.GetCustomConstraintRequest( + name="name_value", + ) + + # Make the request + response = client.get_custom_constraint(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.orgpolicy_v2.types.GetCustomConstraintRequest, dict]): + The request object. The request sent to the [GetCustomConstraint] + [google.cloud.orgpolicy.v2.OrgPolicy.GetCustomConstraint] + method. + name (str): + Required. Resource name of the custom + constraint. See the custom constraint + entry for naming requirements. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.orgpolicy_v2.types.CustomConstraint: + A custom constraint defined by customers which can *only* be applied to the + given resource types and organization. + + By creating a custom constraint, customers can apply + policies of this custom constraint. *Creating a + custom constraint itself does NOT apply any policy + enforcement*. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is 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 orgpolicy.GetCustomConstraintRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, orgpolicy.GetCustomConstraintRequest): + request = orgpolicy.GetCustomConstraintRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_custom_constraint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_custom_constraints( + self, + request: Optional[Union[orgpolicy.ListCustomConstraintsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListCustomConstraintsPager: + r"""Retrieves all of the custom constraints that exist on + a particular organization 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 orgpolicy_v2 + + def sample_list_custom_constraints(): + # Create a client + client = orgpolicy_v2.OrgPolicyClient() + + # Initialize request argument(s) + request = orgpolicy_v2.ListCustomConstraintsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_custom_constraints(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.orgpolicy_v2.types.ListCustomConstraintsRequest, dict]): + The request object. The request sent to the [ListCustomConstraints] + [google.cloud.orgpolicy.v2.OrgPolicy.ListCustomConstraints] + method. + parent (str): + Required. The target Google Cloud resource that parents + the set of custom constraints that will be returned from + this call. Must be in one of the following forms: + + - ``organizations/{organization_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.orgpolicy_v2.services.org_policy.pagers.ListCustomConstraintsPager: + The response returned from the [ListCustomConstraints] + [google.cloud.orgpolicy.v2.OrgPolicy.ListCustomConstraints] + method. It will be empty if no custom constraints are + set on the organization resource. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a orgpolicy.ListCustomConstraintsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, orgpolicy.ListCustomConstraintsRequest): + request = orgpolicy.ListCustomConstraintsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_custom_constraints] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListCustomConstraintsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_custom_constraint( + self, + request: Optional[Union[orgpolicy.DeleteCustomConstraintRequest, dict]] = 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 custom constraint. + + Returns a ``google.rpc.Status`` with + ``google.rpc.Code.NOT_FOUND`` if the constraint does not exist. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import orgpolicy_v2 + + def sample_delete_custom_constraint(): + # Create a client + client = orgpolicy_v2.OrgPolicyClient() + + # Initialize request argument(s) + request = orgpolicy_v2.DeleteCustomConstraintRequest( + name="name_value", + ) + + # Make the request + client.delete_custom_constraint(request=request) + + Args: + request (Union[google.cloud.orgpolicy_v2.types.DeleteCustomConstraintRequest, dict]): + The request object. The request sent to the [DeleteCustomConstraint] + [google.cloud.orgpolicy.v2.OrgPolicy.DeleteCustomConstraint] + method. + name (str): + Required. Name of the custom + constraint to delete. See the custom + constraint entry for naming rules. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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 orgpolicy.DeleteCustomConstraintRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, orgpolicy.DeleteCustomConstraintRequest): + request = orgpolicy.DeleteCustomConstraintRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_custom_constraint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + def __enter__(self) -> "OrgPolicyClient": return self diff --git a/google/cloud/orgpolicy_v2/services/org_policy/pagers.py b/google/cloud/orgpolicy_v2/services/org_policy/pagers.py index 6fc2f9e..a1e0f37 100644 --- a/google/cloud/orgpolicy_v2/services/org_policy/pagers.py +++ b/google/cloud/orgpolicy_v2/services/org_policy/pagers.py @@ -282,3 +282,131 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListCustomConstraintsPager: + """A pager for iterating through ``list_custom_constraints`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orgpolicy_v2.types.ListCustomConstraintsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``custom_constraints`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCustomConstraints`` requests and continue to iterate + through the ``custom_constraints`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orgpolicy_v2.types.ListCustomConstraintsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., orgpolicy.ListCustomConstraintsResponse], + request: orgpolicy.ListCustomConstraintsRequest, + response: orgpolicy.ListCustomConstraintsResponse, + *, + 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.orgpolicy_v2.types.ListCustomConstraintsRequest): + The initial request object. + response (google.cloud.orgpolicy_v2.types.ListCustomConstraintsResponse): + 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 = orgpolicy.ListCustomConstraintsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[orgpolicy.ListCustomConstraintsResponse]: + 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[constraint.CustomConstraint]: + for page in self.pages: + yield from page.custom_constraints + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListCustomConstraintsAsyncPager: + """A pager for iterating through ``list_custom_constraints`` requests. + + This class thinly wraps an initial + :class:`google.cloud.orgpolicy_v2.types.ListCustomConstraintsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``custom_constraints`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCustomConstraints`` requests and continue to iterate + through the ``custom_constraints`` field on the + corresponding responses. + + All the usual :class:`google.cloud.orgpolicy_v2.types.ListCustomConstraintsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[orgpolicy.ListCustomConstraintsResponse]], + request: orgpolicy.ListCustomConstraintsRequest, + response: orgpolicy.ListCustomConstraintsResponse, + *, + 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.orgpolicy_v2.types.ListCustomConstraintsRequest): + The initial request object. + response (google.cloud.orgpolicy_v2.types.ListCustomConstraintsResponse): + 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 = orgpolicy.ListCustomConstraintsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[orgpolicy.ListCustomConstraintsResponse]: + yield 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[constraint.CustomConstraint]: + async def async_generator(): + async for page in self.pages: + for response in page.custom_constraints: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/orgpolicy_v2/services/org_policy/transports/base.py b/google/cloud/orgpolicy_v2/services/org_policy/transports/base.py index 68797b2..e5efc9b 100644 --- a/google/cloud/orgpolicy_v2/services/org_policy/transports/base.py +++ b/google/cloud/orgpolicy_v2/services/org_policy/transports/base.py @@ -26,6 +26,7 @@ from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore +from google.cloud.orgpolicy_v2.types import constraint from google.cloud.orgpolicy_v2.types import orgpolicy from google.protobuf import empty_pb2 # type: ignore @@ -229,6 +230,81 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.create_custom_constraint: gapic_v1.method.wrap_method( + self.create_custom_constraint, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_custom_constraint: gapic_v1.method.wrap_method( + self.update_custom_constraint, + default_retry=retries.Retry( + initial=1.0, + maximum=10.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_custom_constraint: gapic_v1.method.wrap_method( + self.get_custom_constraint, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_custom_constraints: gapic_v1.method.wrap_method( + self.list_custom_constraints, + default_retry=retries.Retry( + initial=1.0, + maximum=10.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.delete_custom_constraint: gapic_v1.method.wrap_method( + self.delete_custom_constraint, + default_retry=retries.Retry( + initial=1.0, + maximum=10.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, + ), } def close(self): @@ -308,6 +384,54 @@ def delete_policy( ]: raise NotImplementedError() + @property + def create_custom_constraint( + self, + ) -> Callable[ + [orgpolicy.CreateCustomConstraintRequest], + Union[constraint.CustomConstraint, Awaitable[constraint.CustomConstraint]], + ]: + raise NotImplementedError() + + @property + def update_custom_constraint( + self, + ) -> Callable[ + [orgpolicy.UpdateCustomConstraintRequest], + Union[constraint.CustomConstraint, Awaitable[constraint.CustomConstraint]], + ]: + raise NotImplementedError() + + @property + def get_custom_constraint( + self, + ) -> Callable[ + [orgpolicy.GetCustomConstraintRequest], + Union[constraint.CustomConstraint, Awaitable[constraint.CustomConstraint]], + ]: + raise NotImplementedError() + + @property + def list_custom_constraints( + self, + ) -> Callable[ + [orgpolicy.ListCustomConstraintsRequest], + Union[ + orgpolicy.ListCustomConstraintsResponse, + Awaitable[orgpolicy.ListCustomConstraintsResponse], + ], + ]: + raise NotImplementedError() + + @property + def delete_custom_constraint( + self, + ) -> Callable[ + [orgpolicy.DeleteCustomConstraintRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc.py b/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc.py index e2de84e..4e25798 100644 --- a/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc.py +++ b/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc.py @@ -24,6 +24,7 @@ import grpc # type: ignore +from google.cloud.orgpolicy_v2.types import constraint from google.cloud.orgpolicy_v2.types import orgpolicy from google.protobuf import empty_pb2 # type: ignore from .base import OrgPolicyTransport, DEFAULT_CLIENT_INFO @@ -34,26 +35,26 @@ class OrgPolicyGrpcTransport(OrgPolicyTransport): An interface for managing organization policies. - The Cloud Org Policy service provides a simple mechanism for - organizations to restrict the allowed configurations across their - entire Cloud Resource hierarchy. + The Organization Policy Service provides a simple mechanism for + organizations to restrict the allowed configurations across + their entire resource hierarchy. - You can use a ``policy`` to configure restrictions in Cloud - resources. For example, you can enforce a ``policy`` that restricts - which Google Cloud Platform APIs can be activated in a certain part - of your resource hierarchy, or prevents serial port access to VM - instances in a particular folder. + You can use a policy to configure restrictions on resources. For + example, you can enforce a policy that restricts which Google + Cloud APIs can be activated in a certain part of your resource + hierarchy, or prevents serial port access to VM instances in a + particular folder. - ``Policies`` are inherited down through the resource hierarchy. A - ``policy`` applied to a parent resource automatically applies to all - its child resources unless overridden with a ``policy`` lower in the + Policies are inherited down through the resource hierarchy. A + policy applied to a parent resource automatically applies to all + its child resources unless overridden with a policy lower in the hierarchy. - A ``constraint`` defines an aspect of a resource's configuration - that can be controlled by an organization's policy administrator. - ``Policies`` are a collection of ``constraints`` that defines their - allowable configuration on a particular resource and its child - resources. + A constraint defines an aspect of a resource's configuration + that can be controlled by an organization's policy + administrator. Policies are a collection of constraints that + defines their allowable configuration on a particular resource + and its child resources. This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation @@ -259,8 +260,8 @@ def list_constraints( ]: r"""Return a callable for the list constraints method over gRPC. - Lists ``Constraints`` that could be applied on the specified - resource. + Lists constraints that could be applied on the + specified resource. Returns: Callable[[~.ListConstraintsRequest], @@ -286,8 +287,8 @@ def list_policies( ) -> Callable[[orgpolicy.ListPoliciesRequest], orgpolicy.ListPoliciesResponse]: r"""Return a callable for the list policies method over gRPC. - Retrieves all of the ``Policies`` that exist on a particular - resource. + Retrieves all of the policies that exist on a + particular resource. Returns: Callable[[~.ListPoliciesRequest], @@ -311,11 +312,11 @@ def list_policies( def get_policy(self) -> Callable[[orgpolicy.GetPolicyRequest], orgpolicy.Policy]: r"""Return a callable for the get policy method over gRPC. - Gets a ``Policy`` on a resource. + Gets a policy on a resource. - If no ``Policy`` is set on the resource, NOT_FOUND is returned. + If no policy is set on the resource, ``NOT_FOUND`` is returned. The ``etag`` value can be used with ``UpdatePolicy()`` to update - a ``Policy`` during read-modify-write. + a policy during read-modify-write. Returns: Callable[[~.GetPolicyRequest], @@ -341,10 +342,10 @@ def get_effective_policy( ) -> Callable[[orgpolicy.GetEffectivePolicyRequest], orgpolicy.Policy]: r"""Return a callable for the get effective policy method over gRPC. - Gets the effective ``Policy`` on a resource. This is the result - of merging ``Policies`` in the resource hierarchy and evaluating - conditions. The returned ``Policy`` will not have an ``etag`` or - ``condition`` set because it is a computed ``Policy`` across + Gets the effective policy on a resource. This is the result of + merging policies in the resource hierarchy and evaluating + conditions. The returned policy will not have an ``etag`` or + ``condition`` set because it is an evaluated policy across multiple resources. Subtrees of Resource Manager resource hierarchy with 'under:' prefix will not be expanded. @@ -372,13 +373,13 @@ def create_policy( ) -> Callable[[orgpolicy.CreatePolicyRequest], orgpolicy.Policy]: r"""Return a callable for the create policy method over gRPC. - Creates a Policy. + Creates a policy. Returns a ``google.rpc.Status`` with ``google.rpc.Code.NOT_FOUND`` if the constraint does not exist. Returns a ``google.rpc.Status`` with ``google.rpc.Code.ALREADY_EXISTS`` if the policy already exists - on the given Cloud resource. + on the given Google Cloud resource. Returns: Callable[[~.CreatePolicyRequest], @@ -404,7 +405,7 @@ def update_policy( ) -> Callable[[orgpolicy.UpdatePolicyRequest], orgpolicy.Policy]: r"""Return a callable for the update policy method over gRPC. - Updates a Policy. + Updates a policy. Returns a ``google.rpc.Status`` with ``google.rpc.Code.NOT_FOUND`` if the constraint or the policy do @@ -439,11 +440,11 @@ def delete_policy( ) -> Callable[[orgpolicy.DeletePolicyRequest], empty_pb2.Empty]: r"""Return a callable for the delete policy method over gRPC. - Deletes a Policy. + Deletes a policy. Returns a ``google.rpc.Status`` with - ``google.rpc.Code.NOT_FOUND`` if the constraint or Org Policy - does not exist. + ``google.rpc.Code.NOT_FOUND`` if the constraint or organization + policy does not exist. Returns: Callable[[~.DeletePolicyRequest], @@ -463,6 +464,163 @@ def delete_policy( ) return self._stubs["delete_policy"] + @property + def create_custom_constraint( + self, + ) -> Callable[ + [orgpolicy.CreateCustomConstraintRequest], constraint.CustomConstraint + ]: + r"""Return a callable for the create custom constraint method over gRPC. + + Creates a custom constraint. + + Returns a ``google.rpc.Status`` with + ``google.rpc.Code.NOT_FOUND`` if the organization does not + exist. Returns a ``google.rpc.Status`` with + ``google.rpc.Code.ALREADY_EXISTS`` if the constraint already + exists on the given organization. + + Returns: + Callable[[~.CreateCustomConstraintRequest], + ~.CustomConstraint]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_custom_constraint" not in self._stubs: + self._stubs["create_custom_constraint"] = self.grpc_channel.unary_unary( + "/google.cloud.orgpolicy.v2.OrgPolicy/CreateCustomConstraint", + request_serializer=orgpolicy.CreateCustomConstraintRequest.serialize, + response_deserializer=constraint.CustomConstraint.deserialize, + ) + return self._stubs["create_custom_constraint"] + + @property + def update_custom_constraint( + self, + ) -> Callable[ + [orgpolicy.UpdateCustomConstraintRequest], constraint.CustomConstraint + ]: + r"""Return a callable for the update custom constraint method over gRPC. + + Updates a custom constraint. + + Returns a ``google.rpc.Status`` with + ``google.rpc.Code.NOT_FOUND`` if the constraint does not exist. + + Note: the supplied policy will perform a full overwrite of all + fields. + + Returns: + Callable[[~.UpdateCustomConstraintRequest], + ~.CustomConstraint]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_custom_constraint" not in self._stubs: + self._stubs["update_custom_constraint"] = self.grpc_channel.unary_unary( + "/google.cloud.orgpolicy.v2.OrgPolicy/UpdateCustomConstraint", + request_serializer=orgpolicy.UpdateCustomConstraintRequest.serialize, + response_deserializer=constraint.CustomConstraint.deserialize, + ) + return self._stubs["update_custom_constraint"] + + @property + def get_custom_constraint( + self, + ) -> Callable[[orgpolicy.GetCustomConstraintRequest], constraint.CustomConstraint]: + r"""Return a callable for the get custom constraint method over gRPC. + + Gets a custom constraint. + + Returns a ``google.rpc.Status`` with + ``google.rpc.Code.NOT_FOUND`` if the custom constraint does not + exist. + + Returns: + Callable[[~.GetCustomConstraintRequest], + ~.CustomConstraint]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_custom_constraint" not in self._stubs: + self._stubs["get_custom_constraint"] = self.grpc_channel.unary_unary( + "/google.cloud.orgpolicy.v2.OrgPolicy/GetCustomConstraint", + request_serializer=orgpolicy.GetCustomConstraintRequest.serialize, + response_deserializer=constraint.CustomConstraint.deserialize, + ) + return self._stubs["get_custom_constraint"] + + @property + def list_custom_constraints( + self, + ) -> Callable[ + [orgpolicy.ListCustomConstraintsRequest], + orgpolicy.ListCustomConstraintsResponse, + ]: + r"""Return a callable for the list custom constraints method over gRPC. + + Retrieves all of the custom constraints that exist on + a particular organization resource. + + Returns: + Callable[[~.ListCustomConstraintsRequest], + ~.ListCustomConstraintsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_custom_constraints" not in self._stubs: + self._stubs["list_custom_constraints"] = self.grpc_channel.unary_unary( + "/google.cloud.orgpolicy.v2.OrgPolicy/ListCustomConstraints", + request_serializer=orgpolicy.ListCustomConstraintsRequest.serialize, + response_deserializer=orgpolicy.ListCustomConstraintsResponse.deserialize, + ) + return self._stubs["list_custom_constraints"] + + @property + def delete_custom_constraint( + self, + ) -> Callable[[orgpolicy.DeleteCustomConstraintRequest], empty_pb2.Empty]: + r"""Return a callable for the delete custom constraint method over gRPC. + + Deletes a custom constraint. + + Returns a ``google.rpc.Status`` with + ``google.rpc.Code.NOT_FOUND`` if the constraint does not exist. + + Returns: + Callable[[~.DeleteCustomConstraintRequest], + ~.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_custom_constraint" not in self._stubs: + self._stubs["delete_custom_constraint"] = self.grpc_channel.unary_unary( + "/google.cloud.orgpolicy.v2.OrgPolicy/DeleteCustomConstraint", + request_serializer=orgpolicy.DeleteCustomConstraintRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_custom_constraint"] + def close(self): self.grpc_channel.close() diff --git a/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc_asyncio.py b/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc_asyncio.py index b4a6b77..61bcd68 100644 --- a/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc_asyncio.py +++ b/google/cloud/orgpolicy_v2/services/org_policy/transports/grpc_asyncio.py @@ -24,6 +24,7 @@ import grpc # type: ignore from grpc.experimental import aio # type: ignore +from google.cloud.orgpolicy_v2.types import constraint from google.cloud.orgpolicy_v2.types import orgpolicy from google.protobuf import empty_pb2 # type: ignore from .base import OrgPolicyTransport, DEFAULT_CLIENT_INFO @@ -35,26 +36,26 @@ class OrgPolicyGrpcAsyncIOTransport(OrgPolicyTransport): An interface for managing organization policies. - The Cloud Org Policy service provides a simple mechanism for - organizations to restrict the allowed configurations across their - entire Cloud Resource hierarchy. + The Organization Policy Service provides a simple mechanism for + organizations to restrict the allowed configurations across + their entire resource hierarchy. - You can use a ``policy`` to configure restrictions in Cloud - resources. For example, you can enforce a ``policy`` that restricts - which Google Cloud Platform APIs can be activated in a certain part - of your resource hierarchy, or prevents serial port access to VM - instances in a particular folder. + You can use a policy to configure restrictions on resources. For + example, you can enforce a policy that restricts which Google + Cloud APIs can be activated in a certain part of your resource + hierarchy, or prevents serial port access to VM instances in a + particular folder. - ``Policies`` are inherited down through the resource hierarchy. A - ``policy`` applied to a parent resource automatically applies to all - its child resources unless overridden with a ``policy`` lower in the + Policies are inherited down through the resource hierarchy. A + policy applied to a parent resource automatically applies to all + its child resources unless overridden with a policy lower in the hierarchy. - A ``constraint`` defines an aspect of a resource's configuration - that can be controlled by an organization's policy administrator. - ``Policies`` are a collection of ``constraints`` that defines their - allowable configuration on a particular resource and its child - resources. + A constraint defines an aspect of a resource's configuration + that can be controlled by an organization's policy + administrator. Policies are a collection of constraints that + defines their allowable configuration on a particular resource + and its child resources. This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation @@ -262,8 +263,8 @@ def list_constraints( ]: r"""Return a callable for the list constraints method over gRPC. - Lists ``Constraints`` that could be applied on the specified - resource. + Lists constraints that could be applied on the + specified resource. Returns: Callable[[~.ListConstraintsRequest], @@ -291,8 +292,8 @@ def list_policies( ]: r"""Return a callable for the list policies method over gRPC. - Retrieves all of the ``Policies`` that exist on a particular - resource. + Retrieves all of the policies that exist on a + particular resource. Returns: Callable[[~.ListPoliciesRequest], @@ -318,11 +319,11 @@ def get_policy( ) -> Callable[[orgpolicy.GetPolicyRequest], Awaitable[orgpolicy.Policy]]: r"""Return a callable for the get policy method over gRPC. - Gets a ``Policy`` on a resource. + Gets a policy on a resource. - If no ``Policy`` is set on the resource, NOT_FOUND is returned. + If no policy is set on the resource, ``NOT_FOUND`` is returned. The ``etag`` value can be used with ``UpdatePolicy()`` to update - a ``Policy`` during read-modify-write. + a policy during read-modify-write. Returns: Callable[[~.GetPolicyRequest], @@ -348,10 +349,10 @@ def get_effective_policy( ) -> Callable[[orgpolicy.GetEffectivePolicyRequest], Awaitable[orgpolicy.Policy]]: r"""Return a callable for the get effective policy method over gRPC. - Gets the effective ``Policy`` on a resource. This is the result - of merging ``Policies`` in the resource hierarchy and evaluating - conditions. The returned ``Policy`` will not have an ``etag`` or - ``condition`` set because it is a computed ``Policy`` across + Gets the effective policy on a resource. This is the result of + merging policies in the resource hierarchy and evaluating + conditions. The returned policy will not have an ``etag`` or + ``condition`` set because it is an evaluated policy across multiple resources. Subtrees of Resource Manager resource hierarchy with 'under:' prefix will not be expanded. @@ -379,13 +380,13 @@ def create_policy( ) -> Callable[[orgpolicy.CreatePolicyRequest], Awaitable[orgpolicy.Policy]]: r"""Return a callable for the create policy method over gRPC. - Creates a Policy. + Creates a policy. Returns a ``google.rpc.Status`` with ``google.rpc.Code.NOT_FOUND`` if the constraint does not exist. Returns a ``google.rpc.Status`` with ``google.rpc.Code.ALREADY_EXISTS`` if the policy already exists - on the given Cloud resource. + on the given Google Cloud resource. Returns: Callable[[~.CreatePolicyRequest], @@ -411,7 +412,7 @@ def update_policy( ) -> Callable[[orgpolicy.UpdatePolicyRequest], Awaitable[orgpolicy.Policy]]: r"""Return a callable for the update policy method over gRPC. - Updates a Policy. + Updates a policy. Returns a ``google.rpc.Status`` with ``google.rpc.Code.NOT_FOUND`` if the constraint or the policy do @@ -446,11 +447,11 @@ def delete_policy( ) -> Callable[[orgpolicy.DeletePolicyRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete policy method over gRPC. - Deletes a Policy. + Deletes a policy. Returns a ``google.rpc.Status`` with - ``google.rpc.Code.NOT_FOUND`` if the constraint or Org Policy - does not exist. + ``google.rpc.Code.NOT_FOUND`` if the constraint or organization + policy does not exist. Returns: Callable[[~.DeletePolicyRequest], @@ -470,6 +471,169 @@ def delete_policy( ) return self._stubs["delete_policy"] + @property + def create_custom_constraint( + self, + ) -> Callable[ + [orgpolicy.CreateCustomConstraintRequest], + Awaitable[constraint.CustomConstraint], + ]: + r"""Return a callable for the create custom constraint method over gRPC. + + Creates a custom constraint. + + Returns a ``google.rpc.Status`` with + ``google.rpc.Code.NOT_FOUND`` if the organization does not + exist. Returns a ``google.rpc.Status`` with + ``google.rpc.Code.ALREADY_EXISTS`` if the constraint already + exists on the given organization. + + Returns: + Callable[[~.CreateCustomConstraintRequest], + Awaitable[~.CustomConstraint]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_custom_constraint" not in self._stubs: + self._stubs["create_custom_constraint"] = self.grpc_channel.unary_unary( + "/google.cloud.orgpolicy.v2.OrgPolicy/CreateCustomConstraint", + request_serializer=orgpolicy.CreateCustomConstraintRequest.serialize, + response_deserializer=constraint.CustomConstraint.deserialize, + ) + return self._stubs["create_custom_constraint"] + + @property + def update_custom_constraint( + self, + ) -> Callable[ + [orgpolicy.UpdateCustomConstraintRequest], + Awaitable[constraint.CustomConstraint], + ]: + r"""Return a callable for the update custom constraint method over gRPC. + + Updates a custom constraint. + + Returns a ``google.rpc.Status`` with + ``google.rpc.Code.NOT_FOUND`` if the constraint does not exist. + + Note: the supplied policy will perform a full overwrite of all + fields. + + Returns: + Callable[[~.UpdateCustomConstraintRequest], + Awaitable[~.CustomConstraint]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_custom_constraint" not in self._stubs: + self._stubs["update_custom_constraint"] = self.grpc_channel.unary_unary( + "/google.cloud.orgpolicy.v2.OrgPolicy/UpdateCustomConstraint", + request_serializer=orgpolicy.UpdateCustomConstraintRequest.serialize, + response_deserializer=constraint.CustomConstraint.deserialize, + ) + return self._stubs["update_custom_constraint"] + + @property + def get_custom_constraint( + self, + ) -> Callable[ + [orgpolicy.GetCustomConstraintRequest], Awaitable[constraint.CustomConstraint] + ]: + r"""Return a callable for the get custom constraint method over gRPC. + + Gets a custom constraint. + + Returns a ``google.rpc.Status`` with + ``google.rpc.Code.NOT_FOUND`` if the custom constraint does not + exist. + + Returns: + Callable[[~.GetCustomConstraintRequest], + Awaitable[~.CustomConstraint]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_custom_constraint" not in self._stubs: + self._stubs["get_custom_constraint"] = self.grpc_channel.unary_unary( + "/google.cloud.orgpolicy.v2.OrgPolicy/GetCustomConstraint", + request_serializer=orgpolicy.GetCustomConstraintRequest.serialize, + response_deserializer=constraint.CustomConstraint.deserialize, + ) + return self._stubs["get_custom_constraint"] + + @property + def list_custom_constraints( + self, + ) -> Callable[ + [orgpolicy.ListCustomConstraintsRequest], + Awaitable[orgpolicy.ListCustomConstraintsResponse], + ]: + r"""Return a callable for the list custom constraints method over gRPC. + + Retrieves all of the custom constraints that exist on + a particular organization resource. + + Returns: + Callable[[~.ListCustomConstraintsRequest], + Awaitable[~.ListCustomConstraintsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_custom_constraints" not in self._stubs: + self._stubs["list_custom_constraints"] = self.grpc_channel.unary_unary( + "/google.cloud.orgpolicy.v2.OrgPolicy/ListCustomConstraints", + request_serializer=orgpolicy.ListCustomConstraintsRequest.serialize, + response_deserializer=orgpolicy.ListCustomConstraintsResponse.deserialize, + ) + return self._stubs["list_custom_constraints"] + + @property + def delete_custom_constraint( + self, + ) -> Callable[ + [orgpolicy.DeleteCustomConstraintRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete custom constraint method over gRPC. + + Deletes a custom constraint. + + Returns a ``google.rpc.Status`` with + ``google.rpc.Code.NOT_FOUND`` if the constraint does not exist. + + Returns: + Callable[[~.DeleteCustomConstraintRequest], + 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_custom_constraint" not in self._stubs: + self._stubs["delete_custom_constraint"] = self.grpc_channel.unary_unary( + "/google.cloud.orgpolicy.v2.OrgPolicy/DeleteCustomConstraint", + request_serializer=orgpolicy.DeleteCustomConstraintRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_custom_constraint"] + def close(self): return self.grpc_channel.close() diff --git a/google/cloud/orgpolicy_v2/services/org_policy/transports/rest.py b/google/cloud/orgpolicy_v2/services/org_policy/transports/rest.py index 0b29cb8..e957b2f 100644 --- a/google/cloud/orgpolicy_v2/services/org_policy/transports/rest.py +++ b/google/cloud/orgpolicy_v2/services/org_policy/transports/rest.py @@ -39,6 +39,7 @@ OptionalRetry = Union[retries.Retry, object] # type: ignore +from google.cloud.orgpolicy_v2.types import constraint from google.cloud.orgpolicy_v2.types import orgpolicy from google.protobuf import empty_pb2 # type: ignore @@ -67,6 +68,14 @@ class OrgPolicyRestInterceptor: .. code-block:: python class MyCustomOrgPolicyInterceptor(OrgPolicyRestInterceptor): + def pre_create_custom_constraint(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_custom_constraint(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_policy(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -75,10 +84,22 @@ def post_create_policy(self, response): logging.log(f"Received response: {response}") return response + def pre_delete_custom_constraint(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + def pre_delete_policy(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata + def pre_get_custom_constraint(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_custom_constraint(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_effective_policy(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -103,6 +124,14 @@ def post_list_constraints(self, response): logging.log(f"Received response: {response}") return response + def pre_list_custom_constraints(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_custom_constraints(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_policies(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -111,6 +140,14 @@ def post_list_policies(self, response): logging.log(f"Received response: {response}") return response + def pre_update_custom_constraint(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_custom_constraint(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_policy(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -125,6 +162,29 @@ def post_update_policy(self, response): """ + def pre_create_custom_constraint( + self, + request: orgpolicy.CreateCustomConstraintRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[orgpolicy.CreateCustomConstraintRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_custom_constraint + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrgPolicy server. + """ + return request, metadata + + def post_create_custom_constraint( + self, response: constraint.CustomConstraint + ) -> constraint.CustomConstraint: + """Post-rpc interceptor for create_custom_constraint + + Override in a subclass to manipulate the response + after it is returned by the OrgPolicy server but before + it is returned to user code. + """ + return response + def pre_create_policy( self, request: orgpolicy.CreatePolicyRequest, @@ -146,6 +206,18 @@ def post_create_policy(self, response: orgpolicy.Policy) -> orgpolicy.Policy: """ return response + def pre_delete_custom_constraint( + self, + request: orgpolicy.DeleteCustomConstraintRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[orgpolicy.DeleteCustomConstraintRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_custom_constraint + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrgPolicy server. + """ + return request, metadata + def pre_delete_policy( self, request: orgpolicy.DeletePolicyRequest, @@ -158,6 +230,29 @@ def pre_delete_policy( """ return request, metadata + def pre_get_custom_constraint( + self, + request: orgpolicy.GetCustomConstraintRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[orgpolicy.GetCustomConstraintRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_custom_constraint + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrgPolicy server. + """ + return request, metadata + + def post_get_custom_constraint( + self, response: constraint.CustomConstraint + ) -> constraint.CustomConstraint: + """Post-rpc interceptor for get_custom_constraint + + Override in a subclass to manipulate the response + after it is returned by the OrgPolicy server but before + it is returned to user code. + """ + return response + def pre_get_effective_policy( self, request: orgpolicy.GetEffectivePolicyRequest, @@ -221,6 +316,29 @@ def post_list_constraints( """ return response + def pre_list_custom_constraints( + self, + request: orgpolicy.ListCustomConstraintsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[orgpolicy.ListCustomConstraintsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_custom_constraints + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrgPolicy server. + """ + return request, metadata + + def post_list_custom_constraints( + self, response: orgpolicy.ListCustomConstraintsResponse + ) -> orgpolicy.ListCustomConstraintsResponse: + """Post-rpc interceptor for list_custom_constraints + + Override in a subclass to manipulate the response + after it is returned by the OrgPolicy server but before + it is returned to user code. + """ + return response + def pre_list_policies( self, request: orgpolicy.ListPoliciesRequest, @@ -244,6 +362,29 @@ def post_list_policies( """ return response + def pre_update_custom_constraint( + self, + request: orgpolicy.UpdateCustomConstraintRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[orgpolicy.UpdateCustomConstraintRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_custom_constraint + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrgPolicy server. + """ + return request, metadata + + def post_update_custom_constraint( + self, response: constraint.CustomConstraint + ) -> constraint.CustomConstraint: + """Post-rpc interceptor for update_custom_constraint + + Override in a subclass to manipulate the response + after it is returned by the OrgPolicy server but before + it is returned to user code. + """ + return response + def pre_update_policy( self, request: orgpolicy.UpdatePolicyRequest, @@ -278,26 +419,26 @@ class OrgPolicyRestTransport(OrgPolicyTransport): An interface for managing organization policies. - The Cloud Org Policy service provides a simple mechanism for - organizations to restrict the allowed configurations across their - entire Cloud Resource hierarchy. + The Organization Policy Service provides a simple mechanism for + organizations to restrict the allowed configurations across + their entire resource hierarchy. - You can use a ``policy`` to configure restrictions in Cloud - resources. For example, you can enforce a ``policy`` that restricts - which Google Cloud Platform APIs can be activated in a certain part - of your resource hierarchy, or prevents serial port access to VM - instances in a particular folder. + You can use a policy to configure restrictions on resources. For + example, you can enforce a policy that restricts which Google + Cloud APIs can be activated in a certain part of your resource + hierarchy, or prevents serial port access to VM instances in a + particular folder. - ``Policies`` are inherited down through the resource hierarchy. A - ``policy`` applied to a parent resource automatically applies to all - its child resources unless overridden with a ``policy`` lower in the + Policies are inherited down through the resource hierarchy. A + policy applied to a parent resource automatically applies to all + its child resources unless overridden with a policy lower in the hierarchy. - A ``constraint`` defines an aspect of a resource's configuration - that can be controlled by an organization's policy administrator. - ``Policies`` are a collection of ``constraints`` that defines their - allowable configuration on a particular resource and its child - resources. + A constraint defines an aspect of a resource's configuration + that can be controlled by an organization's policy + administrator. Policies are a collection of constraints that + defines their allowable configuration on a particular resource + and its child resources. This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation @@ -383,6 +524,113 @@ def __init__( self._interceptor = interceptor or OrgPolicyRestInterceptor() self._prep_wrapped_messages(client_info) + class _CreateCustomConstraint(OrgPolicyRestStub): + def __hash__(self): + return hash("CreateCustomConstraint") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: orgpolicy.CreateCustomConstraintRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> constraint.CustomConstraint: + r"""Call the create custom constraint method over HTTP. + + Args: + request (~.orgpolicy.CreateCustomConstraintRequest): + The request object. The request sent to the [CreateCustomConstraintRequest] + [google.cloud.orgpolicy.v2.OrgPolicy.CreateCustomConstraint] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.constraint.CustomConstraint: + A custom constraint defined by customers which can + *only* be applied to the given resource types and + organization. + + By creating a custom constraint, customers can apply + policies of this custom constraint. *Creating a custom + constraint itself does NOT apply any policy + enforcement*. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=organizations/*}/customConstraints", + "body": "custom_constraint", + }, + ] + request, metadata = self._interceptor.pre_create_custom_constraint( + request, metadata + ) + pb_request = orgpolicy.CreateCustomConstraintRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = constraint.CustomConstraint() + pb_resp = constraint.CustomConstraint.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_custom_constraint(resp) + return resp + class _CreatePolicy(OrgPolicyRestStub): def __hash__(self): return hash("CreatePolicy") @@ -420,9 +668,10 @@ def __call__( Returns: ~.orgpolicy.Policy: - Defines a Cloud Organization ``Policy`` which is used to - specify ``Constraints`` for configurations of Cloud - Platform resources. + Defines an organization policy which + is used to specify constraints for + configurations of Google Cloud + resources. """ @@ -433,27 +682,198 @@ def __call__( "body": "policy", }, { - "method": "post", - "uri": "/v2/{parent=folders/*}/policies", - "body": "policy", + "method": "post", + "uri": "/v2/{parent=folders/*}/policies", + "body": "policy", + }, + { + "method": "post", + "uri": "/v2/{parent=organizations/*}/policies", + "body": "policy", + }, + ] + request, metadata = self._interceptor.pre_create_policy(request, metadata) + pb_request = orgpolicy.CreatePolicyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = orgpolicy.Policy() + pb_resp = orgpolicy.Policy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_policy(resp) + return resp + + class _DeleteCustomConstraint(OrgPolicyRestStub): + def __hash__(self): + return hash("DeleteCustomConstraint") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: orgpolicy.DeleteCustomConstraintRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete custom constraint method over HTTP. + + Args: + request (~.orgpolicy.DeleteCustomConstraintRequest): + The request object. The request sent to the [DeleteCustomConstraint] + [google.cloud.orgpolicy.v2.OrgPolicy.DeleteCustomConstraint] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=organizations/*/customConstraints/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_custom_constraint( + request, metadata + ) + pb_request = orgpolicy.DeleteCustomConstraintRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeletePolicy(OrgPolicyRestStub): + def __hash__(self): + return hash("DeletePolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: orgpolicy.DeletePolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete policy method over HTTP. + + Args: + request (~.orgpolicy.DeletePolicyRequest): + The request object. The request sent to the [DeletePolicy] + [google.cloud.orgpolicy.v2.OrgPolicy.DeletePolicy] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/policies/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=folders/*/policies/*}", }, { - "method": "post", - "uri": "/v2/{parent=organizations/*}/policies", - "body": "policy", + "method": "delete", + "uri": "/v2/{name=organizations/*/policies/*}", }, ] - request, metadata = self._interceptor.pre_create_policy(request, metadata) - pb_request = orgpolicy.CreatePolicyRequest.pb(request) + request, metadata = self._interceptor.pre_delete_policy(request, metadata) + pb_request = orgpolicy.DeletePolicyRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], - including_default_value_fields=False, - use_integers_for_enums=True, - ) uri = transcoded_request["uri"] method = transcoded_request["method"] @@ -477,7 +897,6 @@ def __call__( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -485,17 +904,9 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) - # Return the response - resp = orgpolicy.Policy() - pb_resp = orgpolicy.Policy.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_policy(resp) - return resp - - class _DeletePolicy(OrgPolicyRestStub): + class _GetCustomConstraint(OrgPolicyRestStub): def __hash__(self): - return hash("DeletePolicy") + return hash("GetCustomConstraint") __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @@ -509,42 +920,48 @@ def _get_unset_required_fields(cls, message_dict): def __call__( self, - request: orgpolicy.DeletePolicyRequest, + request: orgpolicy.GetCustomConstraintRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, str]] = (), - ): - r"""Call the delete policy method over HTTP. + ) -> constraint.CustomConstraint: + r"""Call the get custom constraint method over HTTP. Args: - request (~.orgpolicy.DeletePolicyRequest): - The request object. The request sent to the [DeletePolicy] - [google.cloud.orgpolicy.v2.OrgPolicy.DeletePolicy] + request (~.orgpolicy.GetCustomConstraintRequest): + The request object. The request sent to the [GetCustomConstraint] + [google.cloud.orgpolicy.v2.OrgPolicy.GetCustomConstraint] method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. + + Returns: + ~.constraint.CustomConstraint: + A custom constraint defined by customers which can + *only* be applied to the given resource types and + organization. + + By creating a custom constraint, customers can apply + policies of this custom constraint. *Creating a custom + constraint itself does NOT apply any policy + enforcement*. + """ http_options: List[Dict[str, str]] = [ { - "method": "delete", - "uri": "/v2/{name=projects/*/policies/*}", - }, - { - "method": "delete", - "uri": "/v2/{name=folders/*/policies/*}", - }, - { - "method": "delete", - "uri": "/v2/{name=organizations/*/policies/*}", + "method": "get", + "uri": "/v2/{name=organizations/*/customConstraints/*}", }, ] - request, metadata = self._interceptor.pre_delete_policy(request, metadata) - pb_request = orgpolicy.DeletePolicyRequest.pb(request) + request, metadata = self._interceptor.pre_get_custom_constraint( + request, metadata + ) + pb_request = orgpolicy.GetCustomConstraintRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) uri = transcoded_request["uri"] @@ -577,6 +994,14 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + # Return the response + resp = constraint.CustomConstraint() + pb_resp = constraint.CustomConstraint.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_custom_constraint(resp) + return resp + class _GetEffectivePolicy(OrgPolicyRestStub): def __hash__(self): return hash("GetEffectivePolicy") @@ -614,9 +1039,10 @@ def __call__( Returns: ~.orgpolicy.Policy: - Defines a Cloud Organization ``Policy`` which is used to - specify ``Constraints`` for configurations of Cloud - Platform resources. + Defines an organization policy which + is used to specify constraints for + configurations of Google Cloud + resources. """ @@ -714,9 +1140,10 @@ def __call__( Returns: ~.orgpolicy.Policy: - Defines a Cloud Organization ``Policy`` which is used to - specify ``Constraints`` for configurations of Cloud - Platform resources. + Defines an organization policy which + is used to specify constraints for + configurations of Google Cloud + resources. """ @@ -877,6 +1304,100 @@ def __call__( resp = self._interceptor.post_list_constraints(resp) return resp + class _ListCustomConstraints(OrgPolicyRestStub): + def __hash__(self): + return hash("ListCustomConstraints") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: orgpolicy.ListCustomConstraintsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> orgpolicy.ListCustomConstraintsResponse: + r"""Call the list custom constraints method over HTTP. + + Args: + request (~.orgpolicy.ListCustomConstraintsRequest): + The request object. The request sent to the [ListCustomConstraints] + [google.cloud.orgpolicy.v2.OrgPolicy.ListCustomConstraints] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.orgpolicy.ListCustomConstraintsResponse: + The response returned from the [ListCustomConstraints] + [google.cloud.orgpolicy.v2.OrgPolicy.ListCustomConstraints] + method. It will be empty if no custom constraints are + set on the organization resource. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=organizations/*}/customConstraints", + }, + ] + request, metadata = self._interceptor.pre_list_custom_constraints( + request, metadata + ) + pb_request = orgpolicy.ListCustomConstraintsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = orgpolicy.ListCustomConstraintsResponse() + pb_resp = orgpolicy.ListCustomConstraintsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_custom_constraints(resp) + return resp + class _ListPolicies(OrgPolicyRestStub): def __hash__(self): return hash("ListPolicies") @@ -916,8 +1437,8 @@ def __call__( ~.orgpolicy.ListPoliciesResponse: The response returned from the [ListPolicies] [google.cloud.orgpolicy.v2.OrgPolicy.ListPolicies] - method. It will be empty if no ``Policies`` are set on - the resource. + method. It will be empty if no policies are set on the + resource. """ @@ -977,6 +1498,113 @@ def __call__( resp = self._interceptor.post_list_policies(resp) return resp + class _UpdateCustomConstraint(OrgPolicyRestStub): + def __hash__(self): + return hash("UpdateCustomConstraint") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: orgpolicy.UpdateCustomConstraintRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> constraint.CustomConstraint: + r"""Call the update custom constraint method over HTTP. + + Args: + request (~.orgpolicy.UpdateCustomConstraintRequest): + The request object. The request sent to the [UpdateCustomConstraintRequest] + [google.cloud.orgpolicy.v2.OrgPolicy.UpdateCustomConstraint] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.constraint.CustomConstraint: + A custom constraint defined by customers which can + *only* be applied to the given resource types and + organization. + + By creating a custom constraint, customers can apply + policies of this custom constraint. *Creating a custom + constraint itself does NOT apply any policy + enforcement*. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{custom_constraint.name=organizations/*/customConstraints/*}", + "body": "custom_constraint", + }, + ] + request, metadata = self._interceptor.pre_update_custom_constraint( + request, metadata + ) + pb_request = orgpolicy.UpdateCustomConstraintRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = constraint.CustomConstraint() + pb_resp = constraint.CustomConstraint.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_custom_constraint(resp) + return resp + class _UpdatePolicy(OrgPolicyRestStub): def __hash__(self): return hash("UpdatePolicy") @@ -1014,9 +1642,10 @@ def __call__( Returns: ~.orgpolicy.Policy: - Defines a Cloud Organization ``Policy`` which is used to - specify ``Constraints`` for configurations of Cloud - Platform resources. + Defines an organization policy which + is used to specify constraints for + configurations of Google Cloud + resources. """ @@ -1087,6 +1716,16 @@ def __call__( resp = self._interceptor.post_update_policy(resp) return resp + @property + def create_custom_constraint( + self, + ) -> Callable[ + [orgpolicy.CreateCustomConstraintRequest], constraint.CustomConstraint + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCustomConstraint(self._session, self._host, self._interceptor) # type: ignore + @property def create_policy( self, @@ -1095,6 +1734,14 @@ def create_policy( # In C++ this would require a dynamic_cast return self._CreatePolicy(self._session, self._host, self._interceptor) # type: ignore + @property + def delete_custom_constraint( + self, + ) -> Callable[[orgpolicy.DeleteCustomConstraintRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteCustomConstraint(self._session, self._host, self._interceptor) # type: ignore + @property def delete_policy( self, @@ -1103,6 +1750,14 @@ def delete_policy( # In C++ this would require a dynamic_cast return self._DeletePolicy(self._session, self._host, self._interceptor) # type: ignore + @property + def get_custom_constraint( + self, + ) -> Callable[[orgpolicy.GetCustomConstraintRequest], constraint.CustomConstraint]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCustomConstraint(self._session, self._host, self._interceptor) # type: ignore + @property def get_effective_policy( self, @@ -1127,6 +1782,17 @@ def list_constraints( # In C++ this would require a dynamic_cast return self._ListConstraints(self._session, self._host, self._interceptor) # type: ignore + @property + def list_custom_constraints( + self, + ) -> Callable[ + [orgpolicy.ListCustomConstraintsRequest], + orgpolicy.ListCustomConstraintsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCustomConstraints(self._session, self._host, self._interceptor) # type: ignore + @property def list_policies( self, @@ -1135,6 +1801,16 @@ def list_policies( # In C++ this would require a dynamic_cast return self._ListPolicies(self._session, self._host, self._interceptor) # type: ignore + @property + def update_custom_constraint( + self, + ) -> Callable[ + [orgpolicy.UpdateCustomConstraintRequest], constraint.CustomConstraint + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCustomConstraint(self._session, self._host, self._interceptor) # type: ignore + @property def update_policy( self, diff --git a/google/cloud/orgpolicy_v2/types/__init__.py b/google/cloud/orgpolicy_v2/types/__init__.py index a945c0d..9cfdba6 100644 --- a/google/cloud/orgpolicy_v2/types/__init__.py +++ b/google/cloud/orgpolicy_v2/types/__init__.py @@ -15,34 +15,48 @@ # from .constraint import ( Constraint, + CustomConstraint, ) from .orgpolicy import ( AlternatePolicySpec, + CreateCustomConstraintRequest, CreatePolicyRequest, + DeleteCustomConstraintRequest, DeletePolicyRequest, + GetCustomConstraintRequest, GetEffectivePolicyRequest, GetPolicyRequest, ListConstraintsRequest, ListConstraintsResponse, + ListCustomConstraintsRequest, + ListCustomConstraintsResponse, ListPoliciesRequest, ListPoliciesResponse, Policy, PolicySpec, + UpdateCustomConstraintRequest, UpdatePolicyRequest, ) __all__ = ( "Constraint", + "CustomConstraint", "AlternatePolicySpec", + "CreateCustomConstraintRequest", "CreatePolicyRequest", + "DeleteCustomConstraintRequest", "DeletePolicyRequest", + "GetCustomConstraintRequest", "GetEffectivePolicyRequest", "GetPolicyRequest", "ListConstraintsRequest", "ListConstraintsResponse", + "ListCustomConstraintsRequest", + "ListCustomConstraintsResponse", "ListPoliciesRequest", "ListPoliciesResponse", "Policy", "PolicySpec", + "UpdateCustomConstraintRequest", "UpdatePolicyRequest", ) diff --git a/google/cloud/orgpolicy_v2/types/constraint.py b/google/cloud/orgpolicy_v2/types/constraint.py index aa1ef4c..7258e45 100644 --- a/google/cloud/orgpolicy_v2/types/constraint.py +++ b/google/cloud/orgpolicy_v2/types/constraint.py @@ -19,33 +19,35 @@ import proto # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + __protobuf__ = proto.module( package="google.cloud.orgpolicy.v2", manifest={ "Constraint", + "CustomConstraint", }, ) class Constraint(proto.Message): - r"""A ``constraint`` describes a way to restrict resource's - configuration. For example, you could enforce a constraint that - controls which cloud services can be activated across an - organization, or whether a Compute Engine instance can have serial - port connections established. ``Constraints`` can be configured by - the organization's policy administrator to fit the needs of the - organization by setting a ``policy`` that includes ``constraints`` - at different locations in the organization's resource hierarchy. - Policies are inherited down the resource hierarchy from higher - levels, but can also be overridden. For details about the - inheritance rules please read about + r"""A constraint describes a way to restrict resource's configuration. + For example, you could enforce a constraint that controls which + Google Cloud services can be activated across an organization, or + whether a Compute Engine instance can have serial port connections + established. Constraints can be configured by the organization + policy administrator to fit the needs of the organization by setting + a policy that includes constraints at different locations in the + organization's resource hierarchy. Policies are inherited down the + resource hierarchy from higher levels, but can also be overridden. + For details about the inheritance rules please read about [``policies``][google.cloud.OrgPolicy.v2.Policy]. - ``Constraints`` have a default behavior determined by the + Constraints have a default behavior determined by the ``constraint_default`` field, which is the enforcement behavior that - is used in the absence of a ``policy`` being defined or inherited - for the resource in question. + is used in the absence of a policy being defined or inherited for + the resource in question. This message has `oneof`_ fields (mutually exclusive fields). For each oneof, at most one member field can be set at the same time. @@ -56,7 +58,7 @@ class Constraint(proto.Message): Attributes: name (str): - Immutable. The resource name of the Constraint. Must be in + Immutable. The resource name of the constraint. Must be in one of the following forms: - ``projects/{project_number}/constraints/{constraint_name}`` @@ -70,13 +72,14 @@ class Constraint(proto.Message): Mutable. description (str): - Detailed description of what this ``Constraint`` controls as - well as how and where it is enforced. + Detailed description of what this constraint + controls as well as how and where it is + enforced. Mutable. constraint_default (google.cloud.orgpolicy_v2.types.Constraint.ConstraintDefault): The evaluation behavior of this constraint in - the absence of 'Policy'. + the absence of a policy. list_constraint (google.cloud.orgpolicy_v2.types.Constraint.ListConstraint): Defines this constraint as being a ListConstraint. @@ -87,12 +90,14 @@ class Constraint(proto.Message): BooleanConstraint. This field is a member of `oneof`_ ``constraint_type``. + supports_dry_run (bool): + Shows if dry run is supported for this + constraint or not. """ class ConstraintDefault(proto.Enum): - r"""Specifies the default behavior in the absence of any ``Policy`` for - the ``Constraint``. This must not be - ``CONSTRAINT_DEFAULT_UNSPECIFIED``. + r"""Specifies the default behavior in the absence of any policy for the + constraint. This must not be ``CONSTRAINT_DEFAULT_UNSPECIFIED``. Immutable after creation. @@ -114,9 +119,9 @@ class ConstraintDefault(proto.Enum): DENY = 2 class ListConstraint(proto.Message): - r"""A ``Constraint`` that allows or disallows a list of string values, - which are configured by an Organization's policy administrator with - a ``Policy``. + r"""A constraint that allows or disallows a list of string + values, which are configured by an Organization Policy + administrator with a policy. Attributes: supports_in (bool): @@ -125,9 +130,9 @@ class ListConstraint(proto.Message): For example, ``"in:Python"`` would match any value in the 'Python' group. supports_under (bool): - Indicates whether subtrees of Cloud Resource Manager - resource hierarchy can be used in ``Policy.allowed_values`` - and ``Policy.denied_values``. For example, + Indicates whether subtrees of the Resource Manager resource + hierarchy can be used in ``Policy.allowed_values`` and + ``Policy.denied_values``. For example, ``"under:folders/123"`` would match any resource under the 'folders/123' folder. """ @@ -142,9 +147,9 @@ class ListConstraint(proto.Message): ) class BooleanConstraint(proto.Message): - r"""A ``Constraint`` that is either enforced or not. + r"""A constraint that is either enforced or not. - For example a constraint + For example, a constraint ``constraints/compute.disableSerialPortAccess``. If it is enforced on a VM instance, serial port connections will not be opened to that instance. @@ -180,6 +185,143 @@ class BooleanConstraint(proto.Message): oneof="constraint_type", message=BooleanConstraint, ) + supports_dry_run: bool = proto.Field( + proto.BOOL, + number=7, + ) + + +class CustomConstraint(proto.Message): + r"""A custom constraint defined by customers which can *only* be applied + to the given resource types and organization. + + By creating a custom constraint, customers can apply policies of + this custom constraint. *Creating a custom constraint itself does + NOT apply any policy enforcement*. + + Attributes: + name (str): + Immutable. Name of the constraint. This is unique within the + organization. Format of the name should be + + - ``organizations/{organization_id}/customConstraints/{custom_constraint_id}`` + + Example: + ``organizations/123/customConstraints/custom.createOnlyE2TypeVms`` + + The max length is 70 characters and the minimum length is 1. + Note that the prefix + ``organizations/{organization_id}/customConstraints/`` is + not counted. + resource_types (MutableSequence[str]): + Immutable. The resource instance type on which this policy + applies. Format will be of the form : + ``/`` Example: + + - ``compute.googleapis.com/Instance``. + method_types (MutableSequence[google.cloud.orgpolicy_v2.types.CustomConstraint.MethodType]): + All the operations being applied for this + constraint. + condition (str): + Org policy condition/expression. For example: + ``resource.instanceName.matches("[production|test]_.*_(\d)+")`` + or, ``resource.management.auto_upgrade == true`` + + The max length of the condition is 1000 characters. + action_type (google.cloud.orgpolicy_v2.types.CustomConstraint.ActionType): + Allow or deny type. + display_name (str): + One line display name for the UI. The max length of the + display_name is 200 characters. + description (str): + Detailed information about this custom policy + constraint. The max length of the description is + 2000 characters. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last time this custom constraint was + updated. This represents the last time that the + ``CreateCustomConstraint`` or ``UpdateCustomConstraint`` RPC + was called + """ + + class MethodType(proto.Enum): + r"""The operation for which this constraint will be applied. To apply + this constraint only when creating new VMs, the ``method_types`` + should be ``CREATE`` only. To apply this constraint when creating or + deleting VMs, the ``method_types`` should be ``CREATE`` and + ``DELETE``. + + ``UPDATE`` only custom constraints are not supported. Use ``CREATE`` + or ``CREATE, UPDATE``. + + Values: + METHOD_TYPE_UNSPECIFIED (0): + Unspecified. Results in an error. + CREATE (1): + Constraint applied when creating the + resource. + UPDATE (2): + Constraint applied when updating the + resource. + DELETE (3): + Constraint applied when deleting the + resource. Not supported yet. + """ + METHOD_TYPE_UNSPECIFIED = 0 + CREATE = 1 + UPDATE = 2 + DELETE = 3 + + class ActionType(proto.Enum): + r"""Allow or deny type. + + Values: + ACTION_TYPE_UNSPECIFIED (0): + Unspecified. Results in an error. + ALLOW (1): + Allowed action type. + DENY (2): + Deny action type. + """ + ACTION_TYPE_UNSPECIFIED = 0 + ALLOW = 1 + DENY = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + method_types: MutableSequence[MethodType] = proto.RepeatedField( + proto.ENUM, + number=3, + enum=MethodType, + ) + condition: str = proto.Field( + proto.STRING, + number=4, + ) + action_type: ActionType = proto.Field( + proto.ENUM, + number=5, + enum=ActionType, + ) + display_name: str = proto.Field( + proto.STRING, + number=6, + ) + description: str = proto.Field( + proto.STRING, + number=7, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/orgpolicy_v2/types/orgpolicy.py b/google/cloud/orgpolicy_v2/types/orgpolicy.py index a9a9b8a..2687116 100644 --- a/google/cloud/orgpolicy_v2/types/orgpolicy.py +++ b/google/cloud/orgpolicy_v2/types/orgpolicy.py @@ -40,26 +40,32 @@ "CreatePolicyRequest", "UpdatePolicyRequest", "DeletePolicyRequest", + "CreateCustomConstraintRequest", + "GetCustomConstraintRequest", + "ListCustomConstraintsRequest", + "ListCustomConstraintsResponse", + "UpdateCustomConstraintRequest", + "DeleteCustomConstraintRequest", }, ) class Policy(proto.Message): - r"""Defines a Cloud Organization ``Policy`` which is used to specify - ``Constraints`` for configurations of Cloud Platform resources. + r"""Defines an organization policy which is used to specify + constraints for configurations of Google Cloud resources. Attributes: name (str): - Immutable. The resource name of the Policy. Must be one of - the following forms, where constraint_name is the name of - the constraint which this Policy configures: + Immutable. The resource name of the policy. Must be one of + the following forms, where ``constraint_name`` is the name + of the constraint which this policy configures: - ``projects/{project_number}/policies/{constraint_name}`` - ``folders/{folder_id}/policies/{constraint_name}`` - ``organizations/{organization_id}/policies/{constraint_name}`` For example, - "projects/123/policies/compute.disableSerialPortAccess". + ``projects/123/policies/compute.disableSerialPortAccess``. Note: ``projects/{project_id}/policies/{constraint_name}`` is also an acceptable name for API requests, but responses @@ -70,10 +76,18 @@ class Policy(proto.Message): alternate (google.cloud.orgpolicy_v2.types.AlternatePolicySpec): Deprecated. dry_run_spec (google.cloud.orgpolicy_v2.types.PolicySpec): - dry-run policy. + Dry-run policy. Audit-only policy, can be used to monitor how the policy would have impacted the existing and future resources if it's enforced. + etag (str): + Optional. An opaque tag indicating the + current state of the policy, used for + concurrency control. This 'etag' is computed by + the server based on the value of other fields, + and may be sent on update and delete requests to + ensure the client has an up-to-date value before + proceeding. """ name: str = proto.Field( @@ -95,6 +109,10 @@ class Policy(proto.Message): number=4, message="PolicySpec", ) + etag: str = proto.Field( + proto.STRING, + number=5, + ) class AlternatePolicySpec(proto.Message): @@ -108,8 +126,8 @@ class AlternatePolicySpec(proto.Message): while audit logging and to control the launch. Should be set only in the alternate policy. spec (google.cloud.orgpolicy_v2.types.PolicySpec): - Specify ``Constraint`` for configurations of Cloud Platform - resources. + Specify constraint for configurations of + Google Cloud resources. """ launch: str = proto.Field( @@ -124,52 +142,52 @@ class AlternatePolicySpec(proto.Message): class PolicySpec(proto.Message): - r"""Defines a Cloud Organization ``PolicySpec`` which is used to specify - ``Constraints`` for configurations of Cloud Platform resources. + r"""Defines a Google Cloud policy specification which is used to + specify constraints for configurations of Google Cloud + resources. Attributes: etag (str): An opaque tag indicating the current version of the - ``Policy``, used for concurrency control. + policySpec, used for concurrency control. This field is ignored if used in a ``CreatePolicy`` request. - When the ``Policy`` is returned from either a ``GetPolicy`` - or a ``ListPolicies`` request, this ``etag`` indicates the - version of the current ``Policy`` to use when executing a + When the policy is returned from either a ``GetPolicy`` or a + ``ListPolicies`` request, this ``etag`` indicates the + version of the current policySpec to use when executing a read-modify-write loop. - When the ``Policy`` is returned from a - ``GetEffectivePolicy`` request, the ``etag`` will be unset. + When the policy is returned from a ``GetEffectivePolicy`` + request, the ``etag`` will be unset. update_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time stamp this was previously updated. This represents the last time a call to ``CreatePolicy`` or - ``UpdatePolicy`` was made for that ``Policy``. + ``UpdatePolicy`` was made for that policy. rules (MutableSequence[google.cloud.orgpolicy_v2.types.PolicySpec.PolicyRule]): - Up to 10 PolicyRules are allowed. - - In Policies for boolean constraints, the following + In policies for boolean constraints, the following requirements apply: - - There must be one and only one PolicyRule where condition - is unset. - - BooleanPolicyRules with conditions must set ``enforced`` - to the opposite of the PolicyRule without a condition. - - During policy evaluation, PolicyRules with conditions + - There must be one and only one policy rule where + condition is unset. + - Boolean policy rules with conditions must set + ``enforced`` to the opposite of the policy rule without a + condition. + - During policy evaluation, policy rules with conditions that are true for a target resource take precedence. inherit_from_parent (bool): - Determines the inheritance behavior for this ``Policy``. + Determines the inheritance behavior for this policy. - If ``inherit_from_parent`` is true, PolicyRules set higher + If ``inherit_from_parent`` is true, policy rules set higher up in the hierarchy (up to the closest root) are inherited and present in the effective policy. If it is false, then no - rules are inherited, and this Policy becomes the new root - for evaluation. This field can be set only for Policies + rules are inherited, and this policy becomes the new root + for evaluation. This field can be set only for policies which configure list constraints. reset (bool): Ignores policies set above this resource and restores the ``constraint_default`` enforcement behavior of the specific - ``Constraint`` at this resource. This field can be set in + constraint at this resource. This field can be set in policies for either list or boolean constraints. If set, ``rules`` must be empty and ``inherit_from_parent`` must be set to false. @@ -187,27 +205,27 @@ class PolicyRule(proto.Message): Attributes: values (google.cloud.orgpolicy_v2.types.PolicySpec.PolicyRule.StringValues): - List of values to be used for this - PolicyRule. This field can be set only in - Policies for list constraints. + List of values to be used for this policy + rule. This field can be set only in policies for + list constraints. This field is a member of `oneof`_ ``kind``. allow_all (bool): Setting this to true means that all values are allowed. This field can be set only in - Policies for list constraints. + policies for list constraints. This field is a member of `oneof`_ ``kind``. deny_all (bool): Setting this to true means that all values are denied. This field can be set only in - Policies for list constraints. + policies for list constraints. This field is a member of `oneof`_ ``kind``. enforce (bool): - If ``true``, then the ``Policy`` is enforced. If ``false``, - then any configuration is acceptable. This field can be set - only in Policies for boolean constraints. + If ``true``, then the policy is enforced. If ``false``, then + any configuration is acceptable. This field can be set only + in policies for boolean constraints. This field is a member of `oneof`_ ``kind``. condition (google.type.expr_pb2.Expr): @@ -229,7 +247,7 @@ class PolicyRule(proto.Message): class StringValues(proto.Message): r"""A message that holds specific allowed and denied values. This - message can define specific values and subtrees of Cloud Resource + message can define specific values and subtrees of the Resource Manager resource hierarchy (``Organizations``, ``Folders``, ``Projects``) that are allowed or denied. This is achieved by using the ``under:`` and optional ``is:`` prefixes. The ``under:`` prefix @@ -237,10 +255,16 @@ class StringValues(proto.Message): used to denote specific values, and is required only if the value contains a ":". Values prefixed with "is:" are treated the same as values with no prefix. Ancestry subtrees must be in one of the - following formats: - "projects/", e.g. "projects/tokyo-rain-123" - - "folders/", e.g. "folders/1234" - "organizations/", e.g. - "organizations/1234" The ``supports_under`` field of the associated - ``Constraint`` defines whether ancestry prefixes can be used. + following formats: + + - ``projects/`` (for example, + ``projects/tokyo-rain-123``) + - ``folders/`` (for example, ``folders/1234``) + - ``organizations/`` (for example, + ``organizations/1234``) + + The ``supports_under`` field of the associated ``Constraint`` + defines whether ancestry prefixes can be used. Attributes: allowed_values (MutableSequence[str]): @@ -315,8 +339,8 @@ class ListConstraintsRequest(proto.Message): Attributes: parent (str): - Required. The Cloud resource that parents the constraint. - Must be in one of the following forms: + Required. The Google Cloud resource that parents the + constraint. Must be in one of the following forms: - ``projects/{project_number}`` - ``projects/{project_id}`` @@ -382,9 +406,9 @@ class ListPoliciesRequest(proto.Message): Attributes: parent (str): - Required. The target Cloud resource that parents the set of - constraints and policies that will be returned from this - call. Must be in one of the following forms: + Required. The target Google Cloud resource that parents the + set of constraints and policies that will be returned from + this call. Must be in one of the following forms: - ``projects/{project_number}`` - ``projects/{project_id}`` @@ -419,12 +443,12 @@ class ListPoliciesRequest(proto.Message): class ListPoliciesResponse(proto.Message): r"""The response returned from the [ListPolicies] [google.cloud.orgpolicy.v2.OrgPolicy.ListPolicies] method. It will - be empty if no ``Policies`` are set on the resource. + be empty if no policies are set on the resource. Attributes: policies (MutableSequence[google.cloud.orgpolicy_v2.types.Policy]): - All ``Policies`` that exist on the resource. It will be - empty if no ``Policies`` are set. + All policies that exist on the resource. It + will be empty if no policies are set. next_page_token (str): Page token used to retrieve the next page. This is currently not used, but the server may @@ -452,8 +476,9 @@ class GetPolicyRequest(proto.Message): Attributes: name (str): - Required. Resource name of the policy. See ``Policy`` for - naming requirements. + Required. Resource name of the policy. See + [Policy][google.cloud.orgpolicy.v2.Policy] for naming + requirements. """ name: str = proto.Field( @@ -468,8 +493,9 @@ class GetEffectivePolicyRequest(proto.Message): Attributes: name (str): - Required. The effective policy to compute. See ``Policy`` - for naming rules. + Required. The effective policy to compute. See + [Policy][google.cloud.orgpolicy.v2.Policy] for naming + requirements. """ name: str = proto.Field( @@ -484,15 +510,15 @@ class CreatePolicyRequest(proto.Message): Attributes: parent (str): - Required. The Cloud resource that will parent the new - Policy. Must be in one of the following forms: + Required. The Google Cloud resource that will parent the new + policy. Must be in one of the following forms: - ``projects/{project_number}`` - ``projects/{project_id}`` - ``folders/{folder_id}`` - ``organizations/{organization_id}`` policy (google.cloud.orgpolicy_v2.types.Policy): - Required. ``Policy`` to create. + Required. Policy to create. """ parent: str = proto.Field( @@ -512,7 +538,7 @@ class UpdatePolicyRequest(proto.Message): Attributes: policy (google.cloud.orgpolicy_v2.types.Policy): - Required. ``Policy`` to update. + Required. Policy to update. update_mask (google.protobuf.field_mask_pb2.FieldMask): Field mask used to specify the fields to be overwritten in the policy by the set. The fields specified in the @@ -538,7 +564,161 @@ class DeletePolicyRequest(proto.Message): Attributes: name (str): - Required. Name of the policy to delete. See ``Policy`` for + Required. Name of the policy to delete. + See the policy entry for naming rules. + etag (str): + Optional. The current etag of policy. If an + etag is provided and does not match the current + etag of the policy, deletion will be blocked and + an ABORTED error will be returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateCustomConstraintRequest(proto.Message): + r"""The request sent to the [CreateCustomConstraintRequest] + [google.cloud.orgpolicy.v2.OrgPolicy.CreateCustomConstraint] method. + + Attributes: + parent (str): + Required. Must be in the following form: + + - ``organizations/{organization_id}`` + custom_constraint (google.cloud.orgpolicy_v2.types.CustomConstraint): + Required. Custom constraint to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + custom_constraint: constraint.CustomConstraint = proto.Field( + proto.MESSAGE, + number=2, + message=constraint.CustomConstraint, + ) + + +class GetCustomConstraintRequest(proto.Message): + r"""The request sent to the [GetCustomConstraint] + [google.cloud.orgpolicy.v2.OrgPolicy.GetCustomConstraint] method. + + Attributes: + name (str): + Required. Resource name of the custom + constraint. See the custom constraint entry for + naming requirements. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListCustomConstraintsRequest(proto.Message): + r"""The request sent to the [ListCustomConstraints] + [google.cloud.orgpolicy.v2.OrgPolicy.ListCustomConstraints] method. + + Attributes: + parent (str): + Required. The target Google Cloud resource that parents the + set of custom constraints that will be returned from this + call. Must be in one of the following forms: + + - ``organizations/{organization_id}`` + page_size (int): + Size of the pages to be returned. This is + currently unsupported and will be ignored. The + server may at any point start using this field + to limit page size. + page_token (str): + Page token used to retrieve the next page. + This is currently unsupported and will be + ignored. The server may at any point start using + this field. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListCustomConstraintsResponse(proto.Message): + r"""The response returned from the [ListCustomConstraints] + [google.cloud.orgpolicy.v2.OrgPolicy.ListCustomConstraints] method. + It will be empty if no custom constraints are set on the + organization resource. + + Attributes: + custom_constraints (MutableSequence[google.cloud.orgpolicy_v2.types.CustomConstraint]): + All custom constraints that exist on the + organization resource. It will be empty if no + custom constraints are set. + next_page_token (str): + Page token used to retrieve the next page. + This is currently not used, but the server may + at any point start supplying a valid token. + """ + + @property + def raw_page(self): + return self + + custom_constraints: MutableSequence[ + constraint.CustomConstraint + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=constraint.CustomConstraint, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateCustomConstraintRequest(proto.Message): + r"""The request sent to the [UpdateCustomConstraintRequest] + [google.cloud.orgpolicy.v2.OrgPolicy.UpdateCustomConstraint] method. + + Attributes: + custom_constraint (google.cloud.orgpolicy_v2.types.CustomConstraint): + Required. ``CustomConstraint`` to update. + """ + + custom_constraint: constraint.CustomConstraint = proto.Field( + proto.MESSAGE, + number=1, + message=constraint.CustomConstraint, + ) + + +class DeleteCustomConstraintRequest(proto.Message): + r"""The request sent to the [DeleteCustomConstraint] + [google.cloud.orgpolicy.v2.OrgPolicy.DeleteCustomConstraint] method. + + Attributes: + name (str): + Required. Name of the custom constraint to + delete. See the custom constraint entry for naming rules. """ diff --git a/samples/generated_samples/orgpolicy_v2_generated_org_policy_create_custom_constraint_async.py b/samples/generated_samples/orgpolicy_v2_generated_org_policy_create_custom_constraint_async.py new file mode 100644 index 0000000..3a51e9f --- /dev/null +++ b/samples/generated_samples/orgpolicy_v2_generated_org_policy_create_custom_constraint_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCustomConstraint +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-org-policy + + +# [START orgpolicy_v2_generated_OrgPolicy_CreateCustomConstraint_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import orgpolicy_v2 + + +async def sample_create_custom_constraint(): + # Create a client + client = orgpolicy_v2.OrgPolicyAsyncClient() + + # Initialize request argument(s) + request = orgpolicy_v2.CreateCustomConstraintRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_custom_constraint(request=request) + + # Handle the response + print(response) + +# [END orgpolicy_v2_generated_OrgPolicy_CreateCustomConstraint_async] diff --git a/samples/generated_samples/orgpolicy_v2_generated_org_policy_create_custom_constraint_sync.py b/samples/generated_samples/orgpolicy_v2_generated_org_policy_create_custom_constraint_sync.py new file mode 100644 index 0000000..3ffb32c --- /dev/null +++ b/samples/generated_samples/orgpolicy_v2_generated_org_policy_create_custom_constraint_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCustomConstraint +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-org-policy + + +# [START orgpolicy_v2_generated_OrgPolicy_CreateCustomConstraint_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import orgpolicy_v2 + + +def sample_create_custom_constraint(): + # Create a client + client = orgpolicy_v2.OrgPolicyClient() + + # Initialize request argument(s) + request = orgpolicy_v2.CreateCustomConstraintRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_custom_constraint(request=request) + + # Handle the response + print(response) + +# [END orgpolicy_v2_generated_OrgPolicy_CreateCustomConstraint_sync] diff --git a/samples/generated_samples/orgpolicy_v2_generated_org_policy_delete_custom_constraint_async.py b/samples/generated_samples/orgpolicy_v2_generated_org_policy_delete_custom_constraint_async.py new file mode 100644 index 0000000..445dd34 --- /dev/null +++ b/samples/generated_samples/orgpolicy_v2_generated_org_policy_delete_custom_constraint_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteCustomConstraint +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-org-policy + + +# [START orgpolicy_v2_generated_OrgPolicy_DeleteCustomConstraint_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import orgpolicy_v2 + + +async def sample_delete_custom_constraint(): + # Create a client + client = orgpolicy_v2.OrgPolicyAsyncClient() + + # Initialize request argument(s) + request = orgpolicy_v2.DeleteCustomConstraintRequest( + name="name_value", + ) + + # Make the request + await client.delete_custom_constraint(request=request) + + +# [END orgpolicy_v2_generated_OrgPolicy_DeleteCustomConstraint_async] diff --git a/samples/generated_samples/orgpolicy_v2_generated_org_policy_delete_custom_constraint_sync.py b/samples/generated_samples/orgpolicy_v2_generated_org_policy_delete_custom_constraint_sync.py new file mode 100644 index 0000000..e30d141 --- /dev/null +++ b/samples/generated_samples/orgpolicy_v2_generated_org_policy_delete_custom_constraint_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteCustomConstraint +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-org-policy + + +# [START orgpolicy_v2_generated_OrgPolicy_DeleteCustomConstraint_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import orgpolicy_v2 + + +def sample_delete_custom_constraint(): + # Create a client + client = orgpolicy_v2.OrgPolicyClient() + + # Initialize request argument(s) + request = orgpolicy_v2.DeleteCustomConstraintRequest( + name="name_value", + ) + + # Make the request + client.delete_custom_constraint(request=request) + + +# [END orgpolicy_v2_generated_OrgPolicy_DeleteCustomConstraint_sync] diff --git a/samples/generated_samples/orgpolicy_v2_generated_org_policy_get_custom_constraint_async.py b/samples/generated_samples/orgpolicy_v2_generated_org_policy_get_custom_constraint_async.py new file mode 100644 index 0000000..623c1dd --- /dev/null +++ b/samples/generated_samples/orgpolicy_v2_generated_org_policy_get_custom_constraint_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCustomConstraint +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-org-policy + + +# [START orgpolicy_v2_generated_OrgPolicy_GetCustomConstraint_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import orgpolicy_v2 + + +async def sample_get_custom_constraint(): + # Create a client + client = orgpolicy_v2.OrgPolicyAsyncClient() + + # Initialize request argument(s) + request = orgpolicy_v2.GetCustomConstraintRequest( + name="name_value", + ) + + # Make the request + response = await client.get_custom_constraint(request=request) + + # Handle the response + print(response) + +# [END orgpolicy_v2_generated_OrgPolicy_GetCustomConstraint_async] diff --git a/samples/generated_samples/orgpolicy_v2_generated_org_policy_get_custom_constraint_sync.py b/samples/generated_samples/orgpolicy_v2_generated_org_policy_get_custom_constraint_sync.py new file mode 100644 index 0000000..bf1ffb8 --- /dev/null +++ b/samples/generated_samples/orgpolicy_v2_generated_org_policy_get_custom_constraint_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCustomConstraint +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-org-policy + + +# [START orgpolicy_v2_generated_OrgPolicy_GetCustomConstraint_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import orgpolicy_v2 + + +def sample_get_custom_constraint(): + # Create a client + client = orgpolicy_v2.OrgPolicyClient() + + # Initialize request argument(s) + request = orgpolicy_v2.GetCustomConstraintRequest( + name="name_value", + ) + + # Make the request + response = client.get_custom_constraint(request=request) + + # Handle the response + print(response) + +# [END orgpolicy_v2_generated_OrgPolicy_GetCustomConstraint_sync] diff --git a/samples/generated_samples/orgpolicy_v2_generated_org_policy_list_custom_constraints_async.py b/samples/generated_samples/orgpolicy_v2_generated_org_policy_list_custom_constraints_async.py new file mode 100644 index 0000000..5da8e00 --- /dev/null +++ b/samples/generated_samples/orgpolicy_v2_generated_org_policy_list_custom_constraints_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCustomConstraints +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-org-policy + + +# [START orgpolicy_v2_generated_OrgPolicy_ListCustomConstraints_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import orgpolicy_v2 + + +async def sample_list_custom_constraints(): + # Create a client + client = orgpolicy_v2.OrgPolicyAsyncClient() + + # Initialize request argument(s) + request = orgpolicy_v2.ListCustomConstraintsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_custom_constraints(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END orgpolicy_v2_generated_OrgPolicy_ListCustomConstraints_async] diff --git a/samples/generated_samples/orgpolicy_v2_generated_org_policy_list_custom_constraints_sync.py b/samples/generated_samples/orgpolicy_v2_generated_org_policy_list_custom_constraints_sync.py new file mode 100644 index 0000000..ff76a00 --- /dev/null +++ b/samples/generated_samples/orgpolicy_v2_generated_org_policy_list_custom_constraints_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCustomConstraints +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-org-policy + + +# [START orgpolicy_v2_generated_OrgPolicy_ListCustomConstraints_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import orgpolicy_v2 + + +def sample_list_custom_constraints(): + # Create a client + client = orgpolicy_v2.OrgPolicyClient() + + # Initialize request argument(s) + request = orgpolicy_v2.ListCustomConstraintsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_custom_constraints(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END orgpolicy_v2_generated_OrgPolicy_ListCustomConstraints_sync] diff --git a/samples/generated_samples/orgpolicy_v2_generated_org_policy_update_custom_constraint_async.py b/samples/generated_samples/orgpolicy_v2_generated_org_policy_update_custom_constraint_async.py new file mode 100644 index 0000000..856a615 --- /dev/null +++ b/samples/generated_samples/orgpolicy_v2_generated_org_policy_update_custom_constraint_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCustomConstraint +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-org-policy + + +# [START orgpolicy_v2_generated_OrgPolicy_UpdateCustomConstraint_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import orgpolicy_v2 + + +async def sample_update_custom_constraint(): + # Create a client + client = orgpolicy_v2.OrgPolicyAsyncClient() + + # Initialize request argument(s) + request = orgpolicy_v2.UpdateCustomConstraintRequest( + ) + + # Make the request + response = await client.update_custom_constraint(request=request) + + # Handle the response + print(response) + +# [END orgpolicy_v2_generated_OrgPolicy_UpdateCustomConstraint_async] diff --git a/samples/generated_samples/orgpolicy_v2_generated_org_policy_update_custom_constraint_sync.py b/samples/generated_samples/orgpolicy_v2_generated_org_policy_update_custom_constraint_sync.py new file mode 100644 index 0000000..baf9603 --- /dev/null +++ b/samples/generated_samples/orgpolicy_v2_generated_org_policy_update_custom_constraint_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCustomConstraint +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-org-policy + + +# [START orgpolicy_v2_generated_OrgPolicy_UpdateCustomConstraint_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import orgpolicy_v2 + + +def sample_update_custom_constraint(): + # Create a client + client = orgpolicy_v2.OrgPolicyClient() + + # Initialize request argument(s) + request = orgpolicy_v2.UpdateCustomConstraintRequest( + ) + + # Make the request + response = client.update_custom_constraint(request=request) + + # Handle the response + print(response) + +# [END orgpolicy_v2_generated_OrgPolicy_UpdateCustomConstraint_sync] diff --git a/samples/generated_samples/snippet_metadata_google.cloud.orgpolicy.v2.json b/samples/generated_samples/snippet_metadata_google.cloud.orgpolicy.v2.json index 7fa6f49..b5d00f8 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.orgpolicy.v2.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.orgpolicy.v2.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-org-policy", - "version": "1.9.0" + "version": "0.1.0" }, "snippets": [ { @@ -19,27 +19,27 @@ "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient", "shortName": "OrgPolicyAsyncClient" }, - "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient.create_policy", + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient.create_custom_constraint", "method": { - "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.CreatePolicy", + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.CreateCustomConstraint", "service": { "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", "shortName": "OrgPolicy" }, - "shortName": "CreatePolicy" + "shortName": "CreateCustomConstraint" }, "parameters": [ { "name": "request", - "type": "google.cloud.orgpolicy_v2.types.CreatePolicyRequest" + "type": "google.cloud.orgpolicy_v2.types.CreateCustomConstraintRequest" }, { "name": "parent", "type": "str" }, { - "name": "policy", - "type": "google.cloud.orgpolicy_v2.types.Policy" + "name": "custom_constraint", + "type": "google.cloud.orgpolicy_v2.types.CustomConstraint" }, { "name": "retry", @@ -54,14 +54,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.orgpolicy_v2.types.Policy", - "shortName": "create_policy" + "resultType": "google.cloud.orgpolicy_v2.types.CustomConstraint", + "shortName": "create_custom_constraint" }, - "description": "Sample for CreatePolicy", - "file": "orgpolicy_v2_generated_org_policy_create_policy_async.py", + "description": "Sample for CreateCustomConstraint", + "file": "orgpolicy_v2_generated_org_policy_create_custom_constraint_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "orgpolicy_v2_generated_OrgPolicy_CreatePolicy_async", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_CreateCustomConstraint_async", "segments": [ { "end": 51, @@ -94,7 +94,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "orgpolicy_v2_generated_org_policy_create_policy_async.py" + "title": "orgpolicy_v2_generated_org_policy_create_custom_constraint_async.py" }, { "canonical": true, @@ -103,27 +103,27 @@ "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient", "shortName": "OrgPolicyClient" }, - "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient.create_policy", + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient.create_custom_constraint", "method": { - "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.CreatePolicy", + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.CreateCustomConstraint", "service": { "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", "shortName": "OrgPolicy" }, - "shortName": "CreatePolicy" + "shortName": "CreateCustomConstraint" }, "parameters": [ { "name": "request", - "type": "google.cloud.orgpolicy_v2.types.CreatePolicyRequest" + "type": "google.cloud.orgpolicy_v2.types.CreateCustomConstraintRequest" }, { "name": "parent", "type": "str" }, { - "name": "policy", - "type": "google.cloud.orgpolicy_v2.types.Policy" + "name": "custom_constraint", + "type": "google.cloud.orgpolicy_v2.types.CustomConstraint" }, { "name": "retry", @@ -138,14 +138,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.orgpolicy_v2.types.Policy", - "shortName": "create_policy" + "resultType": "google.cloud.orgpolicy_v2.types.CustomConstraint", + "shortName": "create_custom_constraint" }, - "description": "Sample for CreatePolicy", - "file": "orgpolicy_v2_generated_org_policy_create_policy_sync.py", + "description": "Sample for CreateCustomConstraint", + "file": "orgpolicy_v2_generated_org_policy_create_custom_constraint_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "orgpolicy_v2_generated_OrgPolicy_CreatePolicy_sync", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_CreateCustomConstraint_sync", "segments": [ { "end": 51, @@ -178,7 +178,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "orgpolicy_v2_generated_org_policy_create_policy_sync.py" + "title": "orgpolicy_v2_generated_org_policy_create_custom_constraint_sync.py" }, { "canonical": true, @@ -188,24 +188,28 @@ "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient", "shortName": "OrgPolicyAsyncClient" }, - "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient.delete_policy", + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient.create_policy", "method": { - "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.DeletePolicy", + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.CreatePolicy", "service": { "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", "shortName": "OrgPolicy" }, - "shortName": "DeletePolicy" + "shortName": "CreatePolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.orgpolicy_v2.types.DeletePolicyRequest" + "type": "google.cloud.orgpolicy_v2.types.CreatePolicyRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "policy", + "type": "google.cloud.orgpolicy_v2.types.Policy" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -219,21 +223,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "shortName": "delete_policy" + "resultType": "google.cloud.orgpolicy_v2.types.Policy", + "shortName": "create_policy" }, - "description": "Sample for DeletePolicy", - "file": "orgpolicy_v2_generated_org_policy_delete_policy_async.py", + "description": "Sample for CreatePolicy", + "file": "orgpolicy_v2_generated_org_policy_create_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "orgpolicy_v2_generated_OrgPolicy_DeletePolicy_async", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_CreatePolicy_async", "segments": [ { - "end": 49, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 51, "start": 27, "type": "SHORT" }, @@ -248,15 +253,17 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "orgpolicy_v2_generated_org_policy_delete_policy_async.py" + "title": "orgpolicy_v2_generated_org_policy_create_policy_async.py" }, { "canonical": true, @@ -265,24 +272,28 @@ "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient", "shortName": "OrgPolicyClient" }, - "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient.delete_policy", + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient.create_policy", "method": { - "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.DeletePolicy", + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.CreatePolicy", "service": { "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", "shortName": "OrgPolicy" }, - "shortName": "DeletePolicy" + "shortName": "CreatePolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.orgpolicy_v2.types.DeletePolicyRequest" + "type": "google.cloud.orgpolicy_v2.types.CreatePolicyRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "policy", + "type": "google.cloud.orgpolicy_v2.types.Policy" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -296,21 +307,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "shortName": "delete_policy" + "resultType": "google.cloud.orgpolicy_v2.types.Policy", + "shortName": "create_policy" }, - "description": "Sample for DeletePolicy", - "file": "orgpolicy_v2_generated_org_policy_delete_policy_sync.py", + "description": "Sample for CreatePolicy", + "file": "orgpolicy_v2_generated_org_policy_create_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "orgpolicy_v2_generated_OrgPolicy_DeletePolicy_sync", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_CreatePolicy_sync", "segments": [ { - "end": 49, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 51, "start": 27, "type": "SHORT" }, @@ -325,15 +337,17 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "orgpolicy_v2_generated_org_policy_delete_policy_sync.py" + "title": "orgpolicy_v2_generated_org_policy_create_policy_sync.py" }, { "canonical": true, @@ -343,19 +357,19 @@ "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient", "shortName": "OrgPolicyAsyncClient" }, - "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient.get_effective_policy", + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient.delete_custom_constraint", "method": { - "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.GetEffectivePolicy", + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.DeleteCustomConstraint", "service": { "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", "shortName": "OrgPolicy" }, - "shortName": "GetEffectivePolicy" + "shortName": "DeleteCustomConstraint" }, "parameters": [ { "name": "request", - "type": "google.cloud.orgpolicy_v2.types.GetEffectivePolicyRequest" + "type": "google.cloud.orgpolicy_v2.types.DeleteCustomConstraintRequest" }, { "name": "name", @@ -374,22 +388,21 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.orgpolicy_v2.types.Policy", - "shortName": "get_effective_policy" + "shortName": "delete_custom_constraint" }, - "description": "Sample for GetEffectivePolicy", - "file": "orgpolicy_v2_generated_org_policy_get_effective_policy_async.py", + "description": "Sample for DeleteCustomConstraint", + "file": "orgpolicy_v2_generated_org_policy_delete_custom_constraint_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "orgpolicy_v2_generated_OrgPolicy_GetEffectivePolicy_async", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_DeleteCustomConstraint_async", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -404,17 +417,15 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "orgpolicy_v2_generated_org_policy_get_effective_policy_async.py" + "title": "orgpolicy_v2_generated_org_policy_delete_custom_constraint_async.py" }, { "canonical": true, @@ -423,19 +434,19 @@ "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient", "shortName": "OrgPolicyClient" }, - "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient.get_effective_policy", + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient.delete_custom_constraint", "method": { - "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.GetEffectivePolicy", + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.DeleteCustomConstraint", "service": { "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", "shortName": "OrgPolicy" }, - "shortName": "GetEffectivePolicy" + "shortName": "DeleteCustomConstraint" }, "parameters": [ { "name": "request", - "type": "google.cloud.orgpolicy_v2.types.GetEffectivePolicyRequest" + "type": "google.cloud.orgpolicy_v2.types.DeleteCustomConstraintRequest" }, { "name": "name", @@ -454,22 +465,21 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.orgpolicy_v2.types.Policy", - "shortName": "get_effective_policy" + "shortName": "delete_custom_constraint" }, - "description": "Sample for GetEffectivePolicy", - "file": "orgpolicy_v2_generated_org_policy_get_effective_policy_sync.py", + "description": "Sample for DeleteCustomConstraint", + "file": "orgpolicy_v2_generated_org_policy_delete_custom_constraint_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "orgpolicy_v2_generated_OrgPolicy_GetEffectivePolicy_sync", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_DeleteCustomConstraint_sync", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -484,17 +494,15 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "orgpolicy_v2_generated_org_policy_get_effective_policy_sync.py" + "title": "orgpolicy_v2_generated_org_policy_delete_custom_constraint_sync.py" }, { "canonical": true, @@ -504,19 +512,19 @@ "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient", "shortName": "OrgPolicyAsyncClient" }, - "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient.get_policy", + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient.delete_policy", "method": { - "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.GetPolicy", + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.DeletePolicy", "service": { "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", "shortName": "OrgPolicy" }, - "shortName": "GetPolicy" + "shortName": "DeletePolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.orgpolicy_v2.types.GetPolicyRequest" + "type": "google.cloud.orgpolicy_v2.types.DeletePolicyRequest" }, { "name": "name", @@ -535,22 +543,21 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.orgpolicy_v2.types.Policy", - "shortName": "get_policy" + "shortName": "delete_policy" }, - "description": "Sample for GetPolicy", - "file": "orgpolicy_v2_generated_org_policy_get_policy_async.py", + "description": "Sample for DeletePolicy", + "file": "orgpolicy_v2_generated_org_policy_delete_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "orgpolicy_v2_generated_OrgPolicy_GetPolicy_async", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_DeletePolicy_async", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -565,17 +572,15 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "orgpolicy_v2_generated_org_policy_get_policy_async.py" + "title": "orgpolicy_v2_generated_org_policy_delete_policy_async.py" }, { "canonical": true, @@ -584,19 +589,19 @@ "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient", "shortName": "OrgPolicyClient" }, - "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient.get_policy", + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient.delete_policy", "method": { - "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.GetPolicy", + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.DeletePolicy", "service": { "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", "shortName": "OrgPolicy" }, - "shortName": "GetPolicy" + "shortName": "DeletePolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.orgpolicy_v2.types.GetPolicyRequest" + "type": "google.cloud.orgpolicy_v2.types.DeletePolicyRequest" }, { "name": "name", @@ -615,22 +620,21 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.orgpolicy_v2.types.Policy", - "shortName": "get_policy" + "shortName": "delete_policy" }, - "description": "Sample for GetPolicy", - "file": "orgpolicy_v2_generated_org_policy_get_policy_sync.py", + "description": "Sample for DeletePolicy", + "file": "orgpolicy_v2_generated_org_policy_delete_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "orgpolicy_v2_generated_OrgPolicy_GetPolicy_sync", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_DeletePolicy_sync", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -645,17 +649,15 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "orgpolicy_v2_generated_org_policy_get_policy_sync.py" + "title": "orgpolicy_v2_generated_org_policy_delete_policy_sync.py" }, { "canonical": true, @@ -665,22 +667,22 @@ "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient", "shortName": "OrgPolicyAsyncClient" }, - "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient.list_constraints", + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient.get_custom_constraint", "method": { - "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.ListConstraints", + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.GetCustomConstraint", "service": { "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", "shortName": "OrgPolicy" }, - "shortName": "ListConstraints" + "shortName": "GetCustomConstraint" }, "parameters": [ { "name": "request", - "type": "google.cloud.orgpolicy_v2.types.ListConstraintsRequest" + "type": "google.cloud.orgpolicy_v2.types.GetCustomConstraintRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -696,22 +698,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.orgpolicy_v2.services.org_policy.pagers.ListConstraintsAsyncPager", - "shortName": "list_constraints" + "resultType": "google.cloud.orgpolicy_v2.types.CustomConstraint", + "shortName": "get_custom_constraint" }, - "description": "Sample for ListConstraints", - "file": "orgpolicy_v2_generated_org_policy_list_constraints_async.py", + "description": "Sample for GetCustomConstraint", + "file": "orgpolicy_v2_generated_org_policy_get_custom_constraint_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "orgpolicy_v2_generated_OrgPolicy_ListConstraints_async", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_GetCustomConstraint_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -731,12 +733,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "orgpolicy_v2_generated_org_policy_list_constraints_async.py" + "title": "orgpolicy_v2_generated_org_policy_get_custom_constraint_async.py" }, { "canonical": true, @@ -745,22 +747,22 @@ "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient", "shortName": "OrgPolicyClient" }, - "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient.list_constraints", + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient.get_custom_constraint", "method": { - "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.ListConstraints", + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.GetCustomConstraint", "service": { "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", "shortName": "OrgPolicy" }, - "shortName": "ListConstraints" + "shortName": "GetCustomConstraint" }, "parameters": [ { "name": "request", - "type": "google.cloud.orgpolicy_v2.types.ListConstraintsRequest" + "type": "google.cloud.orgpolicy_v2.types.GetCustomConstraintRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -776,22 +778,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.orgpolicy_v2.services.org_policy.pagers.ListConstraintsPager", - "shortName": "list_constraints" + "resultType": "google.cloud.orgpolicy_v2.types.CustomConstraint", + "shortName": "get_custom_constraint" }, - "description": "Sample for ListConstraints", - "file": "orgpolicy_v2_generated_org_policy_list_constraints_sync.py", + "description": "Sample for GetCustomConstraint", + "file": "orgpolicy_v2_generated_org_policy_get_custom_constraint_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "orgpolicy_v2_generated_OrgPolicy_ListConstraints_sync", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_GetCustomConstraint_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -811,12 +813,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "orgpolicy_v2_generated_org_policy_list_constraints_sync.py" + "title": "orgpolicy_v2_generated_org_policy_get_custom_constraint_sync.py" }, { "canonical": true, @@ -826,22 +828,22 @@ "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient", "shortName": "OrgPolicyAsyncClient" }, - "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient.list_policies", + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient.get_effective_policy", "method": { - "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.ListPolicies", + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.GetEffectivePolicy", "service": { "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", "shortName": "OrgPolicy" }, - "shortName": "ListPolicies" + "shortName": "GetEffectivePolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.orgpolicy_v2.types.ListPoliciesRequest" + "type": "google.cloud.orgpolicy_v2.types.GetEffectivePolicyRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -857,22 +859,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.orgpolicy_v2.services.org_policy.pagers.ListPoliciesAsyncPager", - "shortName": "list_policies" + "resultType": "google.cloud.orgpolicy_v2.types.Policy", + "shortName": "get_effective_policy" }, - "description": "Sample for ListPolicies", - "file": "orgpolicy_v2_generated_org_policy_list_policies_async.py", + "description": "Sample for GetEffectivePolicy", + "file": "orgpolicy_v2_generated_org_policy_get_effective_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "orgpolicy_v2_generated_OrgPolicy_ListPolicies_async", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_GetEffectivePolicy_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -892,12 +894,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "orgpolicy_v2_generated_org_policy_list_policies_async.py" + "title": "orgpolicy_v2_generated_org_policy_get_effective_policy_async.py" }, { "canonical": true, @@ -906,22 +908,22 @@ "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient", "shortName": "OrgPolicyClient" }, - "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient.list_policies", + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient.get_effective_policy", "method": { - "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.ListPolicies", + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.GetEffectivePolicy", "service": { "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", "shortName": "OrgPolicy" }, - "shortName": "ListPolicies" + "shortName": "GetEffectivePolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.orgpolicy_v2.types.ListPoliciesRequest" + "type": "google.cloud.orgpolicy_v2.types.GetEffectivePolicyRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -937,8 +939,652 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.orgpolicy_v2.services.org_policy.pagers.ListPoliciesPager", - "shortName": "list_policies" + "resultType": "google.cloud.orgpolicy_v2.types.Policy", + "shortName": "get_effective_policy" + }, + "description": "Sample for GetEffectivePolicy", + "file": "orgpolicy_v2_generated_org_policy_get_effective_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_GetEffectivePolicy_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "orgpolicy_v2_generated_org_policy_get_effective_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient", + "shortName": "OrgPolicyAsyncClient" + }, + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient.get_policy", + "method": { + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.GetPolicy", + "service": { + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", + "shortName": "OrgPolicy" + }, + "shortName": "GetPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orgpolicy_v2.types.GetPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.orgpolicy_v2.types.Policy", + "shortName": "get_policy" + }, + "description": "Sample for GetPolicy", + "file": "orgpolicy_v2_generated_org_policy_get_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_GetPolicy_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "orgpolicy_v2_generated_org_policy_get_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient", + "shortName": "OrgPolicyClient" + }, + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient.get_policy", + "method": { + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.GetPolicy", + "service": { + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", + "shortName": "OrgPolicy" + }, + "shortName": "GetPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orgpolicy_v2.types.GetPolicyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.orgpolicy_v2.types.Policy", + "shortName": "get_policy" + }, + "description": "Sample for GetPolicy", + "file": "orgpolicy_v2_generated_org_policy_get_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_GetPolicy_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "orgpolicy_v2_generated_org_policy_get_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient", + "shortName": "OrgPolicyAsyncClient" + }, + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient.list_constraints", + "method": { + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.ListConstraints", + "service": { + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", + "shortName": "OrgPolicy" + }, + "shortName": "ListConstraints" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orgpolicy_v2.types.ListConstraintsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.orgpolicy_v2.services.org_policy.pagers.ListConstraintsAsyncPager", + "shortName": "list_constraints" + }, + "description": "Sample for ListConstraints", + "file": "orgpolicy_v2_generated_org_policy_list_constraints_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_ListConstraints_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": "orgpolicy_v2_generated_org_policy_list_constraints_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient", + "shortName": "OrgPolicyClient" + }, + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient.list_constraints", + "method": { + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.ListConstraints", + "service": { + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", + "shortName": "OrgPolicy" + }, + "shortName": "ListConstraints" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orgpolicy_v2.types.ListConstraintsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.orgpolicy_v2.services.org_policy.pagers.ListConstraintsPager", + "shortName": "list_constraints" + }, + "description": "Sample for ListConstraints", + "file": "orgpolicy_v2_generated_org_policy_list_constraints_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_ListConstraints_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": "orgpolicy_v2_generated_org_policy_list_constraints_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient", + "shortName": "OrgPolicyAsyncClient" + }, + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient.list_custom_constraints", + "method": { + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.ListCustomConstraints", + "service": { + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", + "shortName": "OrgPolicy" + }, + "shortName": "ListCustomConstraints" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orgpolicy_v2.types.ListCustomConstraintsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.orgpolicy_v2.services.org_policy.pagers.ListCustomConstraintsAsyncPager", + "shortName": "list_custom_constraints" + }, + "description": "Sample for ListCustomConstraints", + "file": "orgpolicy_v2_generated_org_policy_list_custom_constraints_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_ListCustomConstraints_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": "orgpolicy_v2_generated_org_policy_list_custom_constraints_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient", + "shortName": "OrgPolicyClient" + }, + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient.list_custom_constraints", + "method": { + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.ListCustomConstraints", + "service": { + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", + "shortName": "OrgPolicy" + }, + "shortName": "ListCustomConstraints" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orgpolicy_v2.types.ListCustomConstraintsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.orgpolicy_v2.services.org_policy.pagers.ListCustomConstraintsPager", + "shortName": "list_custom_constraints" + }, + "description": "Sample for ListCustomConstraints", + "file": "orgpolicy_v2_generated_org_policy_list_custom_constraints_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_ListCustomConstraints_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": "orgpolicy_v2_generated_org_policy_list_custom_constraints_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient", + "shortName": "OrgPolicyAsyncClient" + }, + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient.list_policies", + "method": { + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.ListPolicies", + "service": { + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", + "shortName": "OrgPolicy" + }, + "shortName": "ListPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orgpolicy_v2.types.ListPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.orgpolicy_v2.services.org_policy.pagers.ListPoliciesAsyncPager", + "shortName": "list_policies" + }, + "description": "Sample for ListPolicies", + "file": "orgpolicy_v2_generated_org_policy_list_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_ListPolicies_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": "orgpolicy_v2_generated_org_policy_list_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient", + "shortName": "OrgPolicyClient" + }, + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient.list_policies", + "method": { + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.ListPolicies", + "service": { + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", + "shortName": "OrgPolicy" + }, + "shortName": "ListPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orgpolicy_v2.types.ListPoliciesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.orgpolicy_v2.services.org_policy.pagers.ListPoliciesPager", + "shortName": "list_policies" }, "description": "Sample for ListPolicies", "file": "orgpolicy_v2_generated_org_policy_list_policies_sync.py", @@ -979,6 +1625,167 @@ ], "title": "orgpolicy_v2_generated_org_policy_list_policies_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient", + "shortName": "OrgPolicyAsyncClient" + }, + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyAsyncClient.update_custom_constraint", + "method": { + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.UpdateCustomConstraint", + "service": { + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", + "shortName": "OrgPolicy" + }, + "shortName": "UpdateCustomConstraint" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orgpolicy_v2.types.UpdateCustomConstraintRequest" + }, + { + "name": "custom_constraint", + "type": "google.cloud.orgpolicy_v2.types.CustomConstraint" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.orgpolicy_v2.types.CustomConstraint", + "shortName": "update_custom_constraint" + }, + "description": "Sample for UpdateCustomConstraint", + "file": "orgpolicy_v2_generated_org_policy_update_custom_constraint_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_UpdateCustomConstraint_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": "orgpolicy_v2_generated_org_policy_update_custom_constraint_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient", + "shortName": "OrgPolicyClient" + }, + "fullName": "google.cloud.orgpolicy_v2.OrgPolicyClient.update_custom_constraint", + "method": { + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy.UpdateCustomConstraint", + "service": { + "fullName": "google.cloud.orgpolicy.v2.OrgPolicy", + "shortName": "OrgPolicy" + }, + "shortName": "UpdateCustomConstraint" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.orgpolicy_v2.types.UpdateCustomConstraintRequest" + }, + { + "name": "custom_constraint", + "type": "google.cloud.orgpolicy_v2.types.CustomConstraint" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.orgpolicy_v2.types.CustomConstraint", + "shortName": "update_custom_constraint" + }, + "description": "Sample for UpdateCustomConstraint", + "file": "orgpolicy_v2_generated_org_policy_update_custom_constraint_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "orgpolicy_v2_generated_OrgPolicy_UpdateCustomConstraint_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": "orgpolicy_v2_generated_org_policy_update_custom_constraint_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/scripts/fixup_orgpolicy_v2_keywords.py b/scripts/fixup_orgpolicy_v2_keywords.py index 59612b6..d3f9108 100644 --- a/scripts/fixup_orgpolicy_v2_keywords.py +++ b/scripts/fixup_orgpolicy_v2_keywords.py @@ -39,12 +39,17 @@ def partition( class orgpolicyCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_custom_constraint': ('parent', 'custom_constraint', ), 'create_policy': ('parent', 'policy', ), - 'delete_policy': ('name', ), + 'delete_custom_constraint': ('name', ), + 'delete_policy': ('name', 'etag', ), + 'get_custom_constraint': ('name', ), 'get_effective_policy': ('name', ), 'get_policy': ('name', ), 'list_constraints': ('parent', 'page_size', 'page_token', ), + 'list_custom_constraints': ('parent', 'page_size', 'page_token', ), 'list_policies': ('parent', 'page_size', 'page_token', ), + 'update_custom_constraint': ('custom_constraint', ), 'update_policy': ('policy', 'update_mask', ), } diff --git a/tests/unit/gapic/orgpolicy_v2/test_org_policy.py b/tests/unit/gapic/orgpolicy_v2/test_org_policy.py index 0361263..f021bc5 100644 --- a/tests/unit/gapic/orgpolicy_v2/test_org_policy.py +++ b/tests/unit/gapic/orgpolicy_v2/test_org_policy.py @@ -1549,6 +1549,7 @@ def test_get_policy(request_type, transport: str = "grpc"): # Designate an appropriate return value for the call. call.return_value = orgpolicy.Policy( name="name_value", + etag="etag_value", ) response = client.get_policy(request) @@ -1560,6 +1561,7 @@ def test_get_policy(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, orgpolicy.Policy) assert response.name == "name_value" + assert response.etag == "etag_value" def test_get_policy_empty_call(): @@ -1597,6 +1599,7 @@ async def test_get_policy_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( orgpolicy.Policy( name="name_value", + etag="etag_value", ) ) response = await client.get_policy(request) @@ -1609,6 +1612,7 @@ async def test_get_policy_async( # Establish that the response is the type that we expect. assert isinstance(response, orgpolicy.Policy) assert response.name == "name_value" + assert response.etag == "etag_value" @pytest.mark.asyncio @@ -1779,6 +1783,7 @@ def test_get_effective_policy(request_type, transport: str = "grpc"): # Designate an appropriate return value for the call. call.return_value = orgpolicy.Policy( name="name_value", + etag="etag_value", ) response = client.get_effective_policy(request) @@ -1790,6 +1795,7 @@ def test_get_effective_policy(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, orgpolicy.Policy) assert response.name == "name_value" + assert response.etag == "etag_value" def test_get_effective_policy_empty_call(): @@ -1831,6 +1837,7 @@ async def test_get_effective_policy_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( orgpolicy.Policy( name="name_value", + etag="etag_value", ) ) response = await client.get_effective_policy(request) @@ -1843,6 +1850,7 @@ async def test_get_effective_policy_async( # Establish that the response is the type that we expect. assert isinstance(response, orgpolicy.Policy) assert response.name == "name_value" + assert response.etag == "etag_value" @pytest.mark.asyncio @@ -2019,6 +2027,7 @@ def test_create_policy(request_type, transport: str = "grpc"): # Designate an appropriate return value for the call. call.return_value = orgpolicy.Policy( name="name_value", + etag="etag_value", ) response = client.create_policy(request) @@ -2030,6 +2039,7 @@ def test_create_policy(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, orgpolicy.Policy) assert response.name == "name_value" + assert response.etag == "etag_value" def test_create_policy_empty_call(): @@ -2067,6 +2077,7 @@ async def test_create_policy_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( orgpolicy.Policy( name="name_value", + etag="etag_value", ) ) response = await client.create_policy(request) @@ -2079,6 +2090,7 @@ async def test_create_policy_async( # Establish that the response is the type that we expect. assert isinstance(response, orgpolicy.Policy) assert response.name == "name_value" + assert response.etag == "etag_value" @pytest.mark.asyncio @@ -2257,6 +2269,7 @@ def test_update_policy(request_type, transport: str = "grpc"): # Designate an appropriate return value for the call. call.return_value = orgpolicy.Policy( name="name_value", + etag="etag_value", ) response = client.update_policy(request) @@ -2268,6 +2281,7 @@ def test_update_policy(request_type, transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, orgpolicy.Policy) assert response.name == "name_value" + assert response.etag == "etag_value" def test_update_policy_empty_call(): @@ -2305,6 +2319,7 @@ async def test_update_policy_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( orgpolicy.Policy( name="name_value", + etag="etag_value", ) ) response = await client.update_policy(request) @@ -2317,6 +2332,7 @@ async def test_update_policy_async( # Establish that the response is the type that we expect. assert isinstance(response, orgpolicy.Policy) assert response.name == "name_value" + assert response.etag == "etag_value" @pytest.mark.asyncio @@ -2683,6 +2699,1507 @@ async def test_delete_policy_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + orgpolicy.CreateCustomConstraintRequest, + dict, + ], +) +def test_create_custom_constraint(request_type, transport: str = "grpc"): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_constraint), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = constraint.CustomConstraint( + name="name_value", + resource_types=["resource_types_value"], + method_types=[constraint.CustomConstraint.MethodType.CREATE], + condition="condition_value", + action_type=constraint.CustomConstraint.ActionType.ALLOW, + display_name="display_name_value", + description="description_value", + ) + response = client.create_custom_constraint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == orgpolicy.CreateCustomConstraintRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, constraint.CustomConstraint) + assert response.name == "name_value" + assert response.resource_types == ["resource_types_value"] + assert response.method_types == [constraint.CustomConstraint.MethodType.CREATE] + assert response.condition == "condition_value" + assert response.action_type == constraint.CustomConstraint.ActionType.ALLOW + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_create_custom_constraint_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = OrgPolicyClient( + credentials=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_custom_constraint), "__call__" + ) as call: + client.create_custom_constraint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == orgpolicy.CreateCustomConstraintRequest() + + +@pytest.mark.asyncio +async def test_create_custom_constraint_async( + transport: str = "grpc_asyncio", + request_type=orgpolicy.CreateCustomConstraintRequest, +): + client = OrgPolicyAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_constraint), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + constraint.CustomConstraint( + name="name_value", + resource_types=["resource_types_value"], + method_types=[constraint.CustomConstraint.MethodType.CREATE], + condition="condition_value", + action_type=constraint.CustomConstraint.ActionType.ALLOW, + display_name="display_name_value", + description="description_value", + ) + ) + response = await client.create_custom_constraint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == orgpolicy.CreateCustomConstraintRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, constraint.CustomConstraint) + assert response.name == "name_value" + assert response.resource_types == ["resource_types_value"] + assert response.method_types == [constraint.CustomConstraint.MethodType.CREATE] + assert response.condition == "condition_value" + assert response.action_type == constraint.CustomConstraint.ActionType.ALLOW + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +@pytest.mark.asyncio +async def test_create_custom_constraint_async_from_dict(): + await test_create_custom_constraint_async(request_type=dict) + + +def test_create_custom_constraint_field_headers(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = orgpolicy.CreateCustomConstraintRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_constraint), "__call__" + ) as call: + call.return_value = constraint.CustomConstraint() + client.create_custom_constraint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_custom_constraint_field_headers_async(): + client = OrgPolicyAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = orgpolicy.CreateCustomConstraintRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_constraint), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + constraint.CustomConstraint() + ) + await client.create_custom_constraint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_custom_constraint_flattened(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_constraint), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = constraint.CustomConstraint() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_custom_constraint( + parent="parent_value", + custom_constraint=constraint.CustomConstraint(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].custom_constraint + mock_val = constraint.CustomConstraint(name="name_value") + assert arg == mock_val + + +def test_create_custom_constraint_flattened_error(): + client = OrgPolicyClient( + credentials=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_custom_constraint( + orgpolicy.CreateCustomConstraintRequest(), + parent="parent_value", + custom_constraint=constraint.CustomConstraint(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_custom_constraint_flattened_async(): + client = OrgPolicyAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_constraint), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = constraint.CustomConstraint() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + constraint.CustomConstraint() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_custom_constraint( + parent="parent_value", + custom_constraint=constraint.CustomConstraint(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].custom_constraint + mock_val = constraint.CustomConstraint(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_custom_constraint_flattened_error_async(): + client = OrgPolicyAsyncClient( + credentials=ga_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_custom_constraint( + orgpolicy.CreateCustomConstraintRequest(), + parent="parent_value", + custom_constraint=constraint.CustomConstraint(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + orgpolicy.UpdateCustomConstraintRequest, + dict, + ], +) +def test_update_custom_constraint(request_type, transport: str = "grpc"): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_constraint), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = constraint.CustomConstraint( + name="name_value", + resource_types=["resource_types_value"], + method_types=[constraint.CustomConstraint.MethodType.CREATE], + condition="condition_value", + action_type=constraint.CustomConstraint.ActionType.ALLOW, + display_name="display_name_value", + description="description_value", + ) + response = client.update_custom_constraint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == orgpolicy.UpdateCustomConstraintRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, constraint.CustomConstraint) + assert response.name == "name_value" + assert response.resource_types == ["resource_types_value"] + assert response.method_types == [constraint.CustomConstraint.MethodType.CREATE] + assert response.condition == "condition_value" + assert response.action_type == constraint.CustomConstraint.ActionType.ALLOW + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_update_custom_constraint_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = OrgPolicyClient( + credentials=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_custom_constraint), "__call__" + ) as call: + client.update_custom_constraint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == orgpolicy.UpdateCustomConstraintRequest() + + +@pytest.mark.asyncio +async def test_update_custom_constraint_async( + transport: str = "grpc_asyncio", + request_type=orgpolicy.UpdateCustomConstraintRequest, +): + client = OrgPolicyAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_constraint), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + constraint.CustomConstraint( + name="name_value", + resource_types=["resource_types_value"], + method_types=[constraint.CustomConstraint.MethodType.CREATE], + condition="condition_value", + action_type=constraint.CustomConstraint.ActionType.ALLOW, + display_name="display_name_value", + description="description_value", + ) + ) + response = await client.update_custom_constraint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == orgpolicy.UpdateCustomConstraintRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, constraint.CustomConstraint) + assert response.name == "name_value" + assert response.resource_types == ["resource_types_value"] + assert response.method_types == [constraint.CustomConstraint.MethodType.CREATE] + assert response.condition == "condition_value" + assert response.action_type == constraint.CustomConstraint.ActionType.ALLOW + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +@pytest.mark.asyncio +async def test_update_custom_constraint_async_from_dict(): + await test_update_custom_constraint_async(request_type=dict) + + +def test_update_custom_constraint_field_headers(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = orgpolicy.UpdateCustomConstraintRequest() + + request.custom_constraint.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_constraint), "__call__" + ) as call: + call.return_value = constraint.CustomConstraint() + client.update_custom_constraint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "custom_constraint.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_custom_constraint_field_headers_async(): + client = OrgPolicyAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = orgpolicy.UpdateCustomConstraintRequest() + + request.custom_constraint.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_constraint), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + constraint.CustomConstraint() + ) + await client.update_custom_constraint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "custom_constraint.name=name_value", + ) in kw["metadata"] + + +def test_update_custom_constraint_flattened(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_constraint), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = constraint.CustomConstraint() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_custom_constraint( + custom_constraint=constraint.CustomConstraint(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].custom_constraint + mock_val = constraint.CustomConstraint(name="name_value") + assert arg == mock_val + + +def test_update_custom_constraint_flattened_error(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_custom_constraint( + orgpolicy.UpdateCustomConstraintRequest(), + custom_constraint=constraint.CustomConstraint(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_update_custom_constraint_flattened_async(): + client = OrgPolicyAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_constraint), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = constraint.CustomConstraint() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + constraint.CustomConstraint() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_custom_constraint( + custom_constraint=constraint.CustomConstraint(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].custom_constraint + mock_val = constraint.CustomConstraint(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_custom_constraint_flattened_error_async(): + client = OrgPolicyAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_custom_constraint( + orgpolicy.UpdateCustomConstraintRequest(), + custom_constraint=constraint.CustomConstraint(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + orgpolicy.GetCustomConstraintRequest, + dict, + ], +) +def test_get_custom_constraint(request_type, transport: str = "grpc"): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_constraint), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = constraint.CustomConstraint( + name="name_value", + resource_types=["resource_types_value"], + method_types=[constraint.CustomConstraint.MethodType.CREATE], + condition="condition_value", + action_type=constraint.CustomConstraint.ActionType.ALLOW, + display_name="display_name_value", + description="description_value", + ) + response = client.get_custom_constraint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == orgpolicy.GetCustomConstraintRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, constraint.CustomConstraint) + assert response.name == "name_value" + assert response.resource_types == ["resource_types_value"] + assert response.method_types == [constraint.CustomConstraint.MethodType.CREATE] + assert response.condition == "condition_value" + assert response.action_type == constraint.CustomConstraint.ActionType.ALLOW + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_get_custom_constraint_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = OrgPolicyClient( + credentials=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_custom_constraint), "__call__" + ) as call: + client.get_custom_constraint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == orgpolicy.GetCustomConstraintRequest() + + +@pytest.mark.asyncio +async def test_get_custom_constraint_async( + transport: str = "grpc_asyncio", request_type=orgpolicy.GetCustomConstraintRequest +): + client = OrgPolicyAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_constraint), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + constraint.CustomConstraint( + name="name_value", + resource_types=["resource_types_value"], + method_types=[constraint.CustomConstraint.MethodType.CREATE], + condition="condition_value", + action_type=constraint.CustomConstraint.ActionType.ALLOW, + display_name="display_name_value", + description="description_value", + ) + ) + response = await client.get_custom_constraint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == orgpolicy.GetCustomConstraintRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, constraint.CustomConstraint) + assert response.name == "name_value" + assert response.resource_types == ["resource_types_value"] + assert response.method_types == [constraint.CustomConstraint.MethodType.CREATE] + assert response.condition == "condition_value" + assert response.action_type == constraint.CustomConstraint.ActionType.ALLOW + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +@pytest.mark.asyncio +async def test_get_custom_constraint_async_from_dict(): + await test_get_custom_constraint_async(request_type=dict) + + +def test_get_custom_constraint_field_headers(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = orgpolicy.GetCustomConstraintRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_constraint), "__call__" + ) as call: + call.return_value = constraint.CustomConstraint() + client.get_custom_constraint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_custom_constraint_field_headers_async(): + client = OrgPolicyAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = orgpolicy.GetCustomConstraintRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_constraint), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + constraint.CustomConstraint() + ) + await client.get_custom_constraint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_custom_constraint_flattened(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_constraint), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = constraint.CustomConstraint() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_custom_constraint( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_custom_constraint_flattened_error(): + client = OrgPolicyClient( + credentials=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_custom_constraint( + orgpolicy.GetCustomConstraintRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_custom_constraint_flattened_async(): + client = OrgPolicyAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_constraint), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = constraint.CustomConstraint() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + constraint.CustomConstraint() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_custom_constraint( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_custom_constraint_flattened_error_async(): + client = OrgPolicyAsyncClient( + credentials=ga_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_custom_constraint( + orgpolicy.GetCustomConstraintRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + orgpolicy.ListCustomConstraintsRequest, + dict, + ], +) +def test_list_custom_constraints(request_type, transport: str = "grpc"): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_constraints), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = orgpolicy.ListCustomConstraintsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_custom_constraints(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == orgpolicy.ListCustomConstraintsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomConstraintsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_custom_constraints_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = OrgPolicyClient( + credentials=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_custom_constraints), "__call__" + ) as call: + client.list_custom_constraints() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == orgpolicy.ListCustomConstraintsRequest() + + +@pytest.mark.asyncio +async def test_list_custom_constraints_async( + transport: str = "grpc_asyncio", request_type=orgpolicy.ListCustomConstraintsRequest +): + client = OrgPolicyAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_constraints), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + orgpolicy.ListCustomConstraintsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_custom_constraints(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == orgpolicy.ListCustomConstraintsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomConstraintsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_custom_constraints_async_from_dict(): + await test_list_custom_constraints_async(request_type=dict) + + +def test_list_custom_constraints_field_headers(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = orgpolicy.ListCustomConstraintsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_constraints), "__call__" + ) as call: + call.return_value = orgpolicy.ListCustomConstraintsResponse() + client.list_custom_constraints(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_custom_constraints_field_headers_async(): + client = OrgPolicyAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = orgpolicy.ListCustomConstraintsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_constraints), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + orgpolicy.ListCustomConstraintsResponse() + ) + await client.list_custom_constraints(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_custom_constraints_flattened(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_constraints), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = orgpolicy.ListCustomConstraintsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_custom_constraints( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_custom_constraints_flattened_error(): + client = OrgPolicyClient( + credentials=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_custom_constraints( + orgpolicy.ListCustomConstraintsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_custom_constraints_flattened_async(): + client = OrgPolicyAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_constraints), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = orgpolicy.ListCustomConstraintsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + orgpolicy.ListCustomConstraintsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_custom_constraints( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_custom_constraints_flattened_error_async(): + client = OrgPolicyAsyncClient( + credentials=ga_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_custom_constraints( + orgpolicy.ListCustomConstraintsRequest(), + parent="parent_value", + ) + + +def test_list_custom_constraints_pager(transport_name: str = "grpc"): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_constraints), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + orgpolicy.ListCustomConstraintsResponse( + custom_constraints=[ + constraint.CustomConstraint(), + constraint.CustomConstraint(), + constraint.CustomConstraint(), + ], + next_page_token="abc", + ), + orgpolicy.ListCustomConstraintsResponse( + custom_constraints=[], + next_page_token="def", + ), + orgpolicy.ListCustomConstraintsResponse( + custom_constraints=[ + constraint.CustomConstraint(), + ], + next_page_token="ghi", + ), + orgpolicy.ListCustomConstraintsResponse( + custom_constraints=[ + constraint.CustomConstraint(), + constraint.CustomConstraint(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_custom_constraints(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, constraint.CustomConstraint) for i in results) + + +def test_list_custom_constraints_pages(transport_name: str = "grpc"): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_constraints), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + orgpolicy.ListCustomConstraintsResponse( + custom_constraints=[ + constraint.CustomConstraint(), + constraint.CustomConstraint(), + constraint.CustomConstraint(), + ], + next_page_token="abc", + ), + orgpolicy.ListCustomConstraintsResponse( + custom_constraints=[], + next_page_token="def", + ), + orgpolicy.ListCustomConstraintsResponse( + custom_constraints=[ + constraint.CustomConstraint(), + ], + next_page_token="ghi", + ), + orgpolicy.ListCustomConstraintsResponse( + custom_constraints=[ + constraint.CustomConstraint(), + constraint.CustomConstraint(), + ], + ), + RuntimeError, + ) + pages = list(client.list_custom_constraints(request={}).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_custom_constraints_async_pager(): + client = OrgPolicyAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_constraints), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + orgpolicy.ListCustomConstraintsResponse( + custom_constraints=[ + constraint.CustomConstraint(), + constraint.CustomConstraint(), + constraint.CustomConstraint(), + ], + next_page_token="abc", + ), + orgpolicy.ListCustomConstraintsResponse( + custom_constraints=[], + next_page_token="def", + ), + orgpolicy.ListCustomConstraintsResponse( + custom_constraints=[ + constraint.CustomConstraint(), + ], + next_page_token="ghi", + ), + orgpolicy.ListCustomConstraintsResponse( + custom_constraints=[ + constraint.CustomConstraint(), + constraint.CustomConstraint(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_custom_constraints( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, constraint.CustomConstraint) for i in responses) + + +@pytest.mark.asyncio +async def test_list_custom_constraints_async_pages(): + client = OrgPolicyAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_constraints), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + orgpolicy.ListCustomConstraintsResponse( + custom_constraints=[ + constraint.CustomConstraint(), + constraint.CustomConstraint(), + constraint.CustomConstraint(), + ], + next_page_token="abc", + ), + orgpolicy.ListCustomConstraintsResponse( + custom_constraints=[], + next_page_token="def", + ), + orgpolicy.ListCustomConstraintsResponse( + custom_constraints=[ + constraint.CustomConstraint(), + ], + next_page_token="ghi", + ), + orgpolicy.ListCustomConstraintsResponse( + custom_constraints=[ + constraint.CustomConstraint(), + constraint.CustomConstraint(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# 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_custom_constraints(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", + [ + orgpolicy.DeleteCustomConstraintRequest, + dict, + ], +) +def test_delete_custom_constraint(request_type, transport: str = "grpc"): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_constraint), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_custom_constraint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == orgpolicy.DeleteCustomConstraintRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_custom_constraint_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = OrgPolicyClient( + credentials=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_custom_constraint), "__call__" + ) as call: + client.delete_custom_constraint() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == orgpolicy.DeleteCustomConstraintRequest() + + +@pytest.mark.asyncio +async def test_delete_custom_constraint_async( + transport: str = "grpc_asyncio", + request_type=orgpolicy.DeleteCustomConstraintRequest, +): + client = OrgPolicyAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_constraint), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_custom_constraint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == orgpolicy.DeleteCustomConstraintRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_custom_constraint_async_from_dict(): + await test_delete_custom_constraint_async(request_type=dict) + + +def test_delete_custom_constraint_field_headers(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = orgpolicy.DeleteCustomConstraintRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_custom_constraint), "__call__" + ) as call: + call.return_value = None + client.delete_custom_constraint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_custom_constraint_field_headers_async(): + client = OrgPolicyAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = orgpolicy.DeleteCustomConstraintRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_custom_constraint), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_custom_constraint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_custom_constraint_flattened(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_custom_constraint), "__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_custom_constraint( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_custom_constraint_flattened_error(): + client = OrgPolicyClient( + credentials=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_custom_constraint( + orgpolicy.DeleteCustomConstraintRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_custom_constraint_flattened_async(): + client = OrgPolicyAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_custom_constraint), "__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_custom_constraint( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_custom_constraint_flattened_error_async(): + client = OrgPolicyAsyncClient( + credentials=ga_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_custom_constraint( + orgpolicy.DeleteCustomConstraintRequest(), + name="name_value", + ) + + @pytest.mark.parametrize( "request_type", [ @@ -2690,46 +4207,1725 @@ async def test_delete_policy_flattened_error_async(): dict, ], ) -def test_list_constraints_rest(request_type): +def test_list_constraints_rest(request_type): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = orgpolicy.ListConstraintsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = orgpolicy.ListConstraintsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_constraints(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConstraintsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_constraints_rest_required_fields( + request_type=orgpolicy.ListConstraintsRequest, +): + transport_class = transports.OrgPolicyRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_constraints._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_constraints._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = orgpolicy.ListConstraintsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = orgpolicy.ListConstraintsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_constraints(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_constraints_rest_unset_required_fields(): + transport = transports.OrgPolicyRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_constraints._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_constraints_rest_interceptors(null_interceptor): + transport = transports.OrgPolicyRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OrgPolicyRestInterceptor(), + ) + client = OrgPolicyClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.OrgPolicyRestInterceptor, "post_list_constraints" + ) as post, mock.patch.object( + transports.OrgPolicyRestInterceptor, "pre_list_constraints" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = orgpolicy.ListConstraintsRequest.pb( + orgpolicy.ListConstraintsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = orgpolicy.ListConstraintsResponse.to_json( + orgpolicy.ListConstraintsResponse() + ) + + request = orgpolicy.ListConstraintsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = orgpolicy.ListConstraintsResponse() + + client.list_constraints( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_constraints_rest_bad_request( + transport: str = "rest", request_type=orgpolicy.ListConstraintsRequest +): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_constraints(request) + + +def test_list_constraints_rest_flattened(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = orgpolicy.ListConstraintsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = orgpolicy.ListConstraintsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_constraints(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*}/constraints" % client.transport._host, args[1] + ) + + +def test_list_constraints_rest_flattened_error(transport: str = "rest"): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_constraints( + orgpolicy.ListConstraintsRequest(), + parent="parent_value", + ) + + +def test_list_constraints_rest_pager(transport: str = "rest"): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + orgpolicy.ListConstraintsResponse( + constraints=[ + constraint.Constraint(), + constraint.Constraint(), + constraint.Constraint(), + ], + next_page_token="abc", + ), + orgpolicy.ListConstraintsResponse( + constraints=[], + next_page_token="def", + ), + orgpolicy.ListConstraintsResponse( + constraints=[ + constraint.Constraint(), + ], + next_page_token="ghi", + ), + orgpolicy.ListConstraintsResponse( + constraints=[ + constraint.Constraint(), + constraint.Constraint(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(orgpolicy.ListConstraintsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1"} + + pager = client.list_constraints(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, constraint.Constraint) for i in results) + + pages = list(client.list_constraints(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + orgpolicy.ListPoliciesRequest, + dict, + ], +) +def test_list_policies_rest(request_type): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = orgpolicy.ListPoliciesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = orgpolicy.ListPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPoliciesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_policies_rest_required_fields(request_type=orgpolicy.ListPoliciesRequest): + transport_class = transports.OrgPolicyRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_policies._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_policies._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = orgpolicy.ListPoliciesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = orgpolicy.ListPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_policies(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_policies_rest_unset_required_fields(): + transport = transports.OrgPolicyRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_policies._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_policies_rest_interceptors(null_interceptor): + transport = transports.OrgPolicyRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OrgPolicyRestInterceptor(), + ) + client = OrgPolicyClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.OrgPolicyRestInterceptor, "post_list_policies" + ) as post, mock.patch.object( + transports.OrgPolicyRestInterceptor, "pre_list_policies" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = orgpolicy.ListPoliciesRequest.pb(orgpolicy.ListPoliciesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = orgpolicy.ListPoliciesResponse.to_json( + orgpolicy.ListPoliciesResponse() + ) + + request = orgpolicy.ListPoliciesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = orgpolicy.ListPoliciesResponse() + + client.list_policies( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_policies_rest_bad_request( + transport: str = "rest", request_type=orgpolicy.ListPoliciesRequest +): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_policies(request) + + +def test_list_policies_rest_flattened(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = orgpolicy.ListPoliciesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = orgpolicy.ListPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_policies(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*}/policies" % client.transport._host, args[1] + ) + + +def test_list_policies_rest_flattened_error(transport: str = "rest"): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_policies( + orgpolicy.ListPoliciesRequest(), + parent="parent_value", + ) + + +def test_list_policies_rest_pager(transport: str = "rest"): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + orgpolicy.ListPoliciesResponse( + policies=[ + orgpolicy.Policy(), + orgpolicy.Policy(), + orgpolicy.Policy(), + ], + next_page_token="abc", + ), + orgpolicy.ListPoliciesResponse( + policies=[], + next_page_token="def", + ), + orgpolicy.ListPoliciesResponse( + policies=[ + orgpolicy.Policy(), + ], + next_page_token="ghi", + ), + orgpolicy.ListPoliciesResponse( + policies=[ + orgpolicy.Policy(), + orgpolicy.Policy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(orgpolicy.ListPoliciesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1"} + + pager = client.list_policies(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, orgpolicy.Policy) for i in results) + + pages = list(client.list_policies(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + orgpolicy.GetPolicyRequest, + dict, + ], +) +def test_get_policy_rest(request_type): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/policies/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = orgpolicy.Policy( + name="name_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = orgpolicy.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, orgpolicy.Policy) + assert response.name == "name_value" + assert response.etag == "etag_value" + + +def test_get_policy_rest_required_fields(request_type=orgpolicy.GetPolicyRequest): + transport_class = transports.OrgPolicyRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = orgpolicy.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = orgpolicy.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_policy_rest_unset_required_fields(): + transport = transports.OrgPolicyRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_policy_rest_interceptors(null_interceptor): + transport = transports.OrgPolicyRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OrgPolicyRestInterceptor(), + ) + client = OrgPolicyClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.OrgPolicyRestInterceptor, "post_get_policy" + ) as post, mock.patch.object( + transports.OrgPolicyRestInterceptor, "pre_get_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = orgpolicy.GetPolicyRequest.pb(orgpolicy.GetPolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = orgpolicy.Policy.to_json(orgpolicy.Policy()) + + request = orgpolicy.GetPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = orgpolicy.Policy() + + client.get_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_policy_rest_bad_request( + transport: str = "rest", request_type=orgpolicy.GetPolicyRequest +): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/policies/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_policy(request) + + +def test_get_policy_rest_flattened(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = orgpolicy.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/policies/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = orgpolicy.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/policies/*}" % client.transport._host, args[1] + ) + + +def test_get_policy_rest_flattened_error(transport: str = "rest"): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_policy( + orgpolicy.GetPolicyRequest(), + name="name_value", + ) + + +def test_get_policy_rest_error(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + orgpolicy.GetEffectivePolicyRequest, + dict, + ], +) +def test_get_effective_policy_rest(request_type): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/policies/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = orgpolicy.Policy( + name="name_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = orgpolicy.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_effective_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, orgpolicy.Policy) + assert response.name == "name_value" + assert response.etag == "etag_value" + + +def test_get_effective_policy_rest_required_fields( + request_type=orgpolicy.GetEffectivePolicyRequest, +): + transport_class = transports.OrgPolicyRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_effective_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_effective_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = orgpolicy.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = orgpolicy.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_effective_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_effective_policy_rest_unset_required_fields(): + transport = transports.OrgPolicyRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_effective_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_effective_policy_rest_interceptors(null_interceptor): + transport = transports.OrgPolicyRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OrgPolicyRestInterceptor(), + ) + client = OrgPolicyClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.OrgPolicyRestInterceptor, "post_get_effective_policy" + ) as post, mock.patch.object( + transports.OrgPolicyRestInterceptor, "pre_get_effective_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = orgpolicy.GetEffectivePolicyRequest.pb( + orgpolicy.GetEffectivePolicyRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = orgpolicy.Policy.to_json(orgpolicy.Policy()) + + request = orgpolicy.GetEffectivePolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = orgpolicy.Policy() + + client.get_effective_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_effective_policy_rest_bad_request( + transport: str = "rest", request_type=orgpolicy.GetEffectivePolicyRequest +): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/policies/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_effective_policy(request) + + +def test_get_effective_policy_rest_flattened(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = orgpolicy.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/policies/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = orgpolicy.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_effective_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=projects/*/policies/*}:getEffectivePolicy" + % client.transport._host, + args[1], + ) + + +def test_get_effective_policy_rest_flattened_error(transport: str = "rest"): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_effective_policy( + orgpolicy.GetEffectivePolicyRequest(), + name="name_value", + ) + + +def test_get_effective_policy_rest_error(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + orgpolicy.CreatePolicyRequest, + dict, + ], +) +def test_create_policy_rest(request_type): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request_init["policy"] = { + "name": "name_value", + "spec": { + "etag": "etag_value", + "update_time": {"seconds": 751, "nanos": 543}, + "rules": [ + { + "values": { + "allowed_values": [ + "allowed_values_value1", + "allowed_values_value2", + ], + "denied_values": [ + "denied_values_value1", + "denied_values_value2", + ], + }, + "allow_all": True, + "deny_all": True, + "enforce": True, + "condition": { + "expression": "expression_value", + "title": "title_value", + "description": "description_value", + "location": "location_value", + }, + } + ], + "inherit_from_parent": True, + "reset": True, + }, + "alternate": {"launch": "launch_value", "spec": {}}, + "dry_run_spec": {}, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = orgpolicy.CreatePolicyRequest.meta.fields["policy"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["policy"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["policy"][field])): + del request_init["policy"][field][i][subfield] + else: + del request_init["policy"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = orgpolicy.Policy( + name="name_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = orgpolicy.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, orgpolicy.Policy) + assert response.name == "name_value" + assert response.etag == "etag_value" + + +def test_create_policy_rest_required_fields(request_type=orgpolicy.CreatePolicyRequest): + transport_class = transports.OrgPolicyRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = orgpolicy.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = orgpolicy.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_policy_rest_unset_required_fields(): + transport = transports.OrgPolicyRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_policy._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "policy", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_policy_rest_interceptors(null_interceptor): + transport = transports.OrgPolicyRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OrgPolicyRestInterceptor(), + ) + client = OrgPolicyClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.OrgPolicyRestInterceptor, "post_create_policy" + ) as post, mock.patch.object( + transports.OrgPolicyRestInterceptor, "pre_create_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = orgpolicy.CreatePolicyRequest.pb(orgpolicy.CreatePolicyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = orgpolicy.Policy.to_json(orgpolicy.Policy()) + + request = orgpolicy.CreatePolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = orgpolicy.Policy() + + client.create_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_policy_rest_bad_request( + transport: str = "rest", request_type=orgpolicy.CreatePolicyRequest +): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_policy(request) + + +def test_create_policy_rest_flattened(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = orgpolicy.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + policy=orgpolicy.Policy(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = orgpolicy.Policy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{parent=projects/*}/policies" % client.transport._host, args[1] + ) + + +def test_create_policy_rest_flattened_error(transport: str = "rest"): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_policy( + orgpolicy.CreatePolicyRequest(), + parent="parent_value", + policy=orgpolicy.Policy(name="name_value"), + ) + + +def test_create_policy_rest_error(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + orgpolicy.UpdatePolicyRequest, + dict, + ], +) +def test_update_policy_rest(request_type): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} + # send a request that will satisfy transcoding + request_init = {"policy": {"name": "projects/sample1/policies/sample2"}} + request_init["policy"] = { + "name": "projects/sample1/policies/sample2", + "spec": { + "etag": "etag_value", + "update_time": {"seconds": 751, "nanos": 543}, + "rules": [ + { + "values": { + "allowed_values": [ + "allowed_values_value1", + "allowed_values_value2", + ], + "denied_values": [ + "denied_values_value1", + "denied_values_value2", + ], + }, + "allow_all": True, + "deny_all": True, + "enforce": True, + "condition": { + "expression": "expression_value", + "title": "title_value", + "description": "description_value", + "location": "location_value", + }, + } + ], + "inherit_from_parent": True, + "reset": True, + }, + "alternate": {"launch": "launch_value", "spec": {}}, + "dry_run_spec": {}, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = orgpolicy.UpdatePolicyRequest.meta.fields["policy"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["policy"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["policy"][field])): + del request_init["policy"][field][i][subfield] + else: + del request_init["policy"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = orgpolicy.ListConstraintsResponse( - next_page_token="next_page_token_value", + return_value = orgpolicy.Policy( + name="name_value", + etag="etag_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = orgpolicy.ListConstraintsResponse.pb(return_value) + return_value = orgpolicy.Policy.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_constraints(request) + response = client.update_policy(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConstraintsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, orgpolicy.Policy) + assert response.name == "name_value" + assert response.etag == "etag_value" -def test_list_constraints_rest_required_fields( - request_type=orgpolicy.ListConstraintsRequest, -): +def test_update_policy_rest_required_fields(request_type=orgpolicy.UpdatePolicyRequest): transport_class = transports.OrgPolicyRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -2744,28 +5940,19 @@ def test_list_constraints_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_constraints._get_unset_required_fields(jsonified_request) + ).update_policy._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_constraints._get_unset_required_fields(jsonified_request) + ).update_policy._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2774,7 +5961,7 @@ def test_list_constraints_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = orgpolicy.ListConstraintsResponse() + return_value = orgpolicy.Policy() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -2786,47 +5973,40 @@ def test_list_constraints_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = orgpolicy.ListConstraintsResponse.pb(return_value) + return_value = orgpolicy.Policy.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_constraints(request) + response = client.update_policy(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_constraints_rest_unset_required_fields(): +def test_update_policy_rest_unset_required_fields(): transport = transports.OrgPolicyRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_constraints._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.update_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("policy",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_constraints_rest_interceptors(null_interceptor): +def test_update_policy_rest_interceptors(null_interceptor): transport = transports.OrgPolicyRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.OrgPolicyRestInterceptor(), @@ -2837,15 +6017,13 @@ def test_list_constraints_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.OrgPolicyRestInterceptor, "post_list_constraints" + transports.OrgPolicyRestInterceptor, "post_update_policy" ) as post, mock.patch.object( - transports.OrgPolicyRestInterceptor, "pre_list_constraints" + transports.OrgPolicyRestInterceptor, "pre_update_policy" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = orgpolicy.ListConstraintsRequest.pb( - orgpolicy.ListConstraintsRequest() - ) + pb_message = orgpolicy.UpdatePolicyRequest.pb(orgpolicy.UpdatePolicyRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2856,19 +6034,17 @@ def test_list_constraints_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = orgpolicy.ListConstraintsResponse.to_json( - orgpolicy.ListConstraintsResponse() - ) + req.return_value._content = orgpolicy.Policy.to_json(orgpolicy.Policy()) - request = orgpolicy.ListConstraintsRequest() + request = orgpolicy.UpdatePolicyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = orgpolicy.ListConstraintsResponse() + post.return_value = orgpolicy.Policy() - client.list_constraints( + client.update_policy( request, metadata=[ ("key", "val"), @@ -2880,8 +6056,8 @@ def test_list_constraints_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_constraints_rest_bad_request( - transport: str = "rest", request_type=orgpolicy.ListConstraintsRequest +def test_update_policy_rest_bad_request( + transport: str = "rest", request_type=orgpolicy.UpdatePolicyRequest ): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2889,7 +6065,7 @@ def test_list_constraints_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} + request_init = {"policy": {"name": "projects/sample1/policies/sample2"}} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -2901,10 +6077,10 @@ def test_list_constraints_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_constraints(request) + client.update_policy(request) -def test_list_constraints_rest_flattened(): +def test_update_policy_rest_flattened(): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -2913,14 +6089,14 @@ def test_list_constraints_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = orgpolicy.ListConstraintsResponse() + return_value = orgpolicy.Policy() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1"} + sample_request = {"policy": {"name": "projects/sample1/policies/sample2"}} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + policy=orgpolicy.Policy(name="name_value"), ) mock_args.update(sample_request) @@ -2928,23 +6104,24 @@ def test_list_constraints_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = orgpolicy.ListConstraintsResponse.pb(return_value) + return_value = orgpolicy.Policy.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_constraints(**mock_args) + client.update_policy(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{parent=projects/*}/constraints" % client.transport._host, args[1] + "%s/v2/{policy.name=projects/*/policies/*}" % client.transport._host, + args[1], ) -def test_list_constraints_rest_flattened_error(transport: str = "rest"): +def test_update_policy_rest_flattened_error(transport: str = "rest"): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2953,118 +6130,58 @@ def test_list_constraints_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_constraints( - orgpolicy.ListConstraintsRequest(), - parent="parent_value", + client.update_policy( + orgpolicy.UpdatePolicyRequest(), + policy=orgpolicy.Policy(name="name_value"), ) -def test_list_constraints_rest_pager(transport: str = "rest"): +def test_update_policy_rest_error(): client = OrgPolicyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - orgpolicy.ListConstraintsResponse( - constraints=[ - constraint.Constraint(), - constraint.Constraint(), - constraint.Constraint(), - ], - next_page_token="abc", - ), - orgpolicy.ListConstraintsResponse( - constraints=[], - next_page_token="def", - ), - orgpolicy.ListConstraintsResponse( - constraints=[ - constraint.Constraint(), - ], - next_page_token="ghi", - ), - orgpolicy.ListConstraintsResponse( - constraints=[ - constraint.Constraint(), - constraint.Constraint(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(orgpolicy.ListConstraintsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "projects/sample1"} - - pager = client.list_constraints(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, constraint.Constraint) for i in results) - - pages = list(client.list_constraints(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - orgpolicy.ListPoliciesRequest, + orgpolicy.DeletePolicyRequest, dict, ], ) -def test_list_policies_rest(request_type): +def test_delete_policy_rest(request_type): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} + request_init = {"name": "projects/sample1/policies/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = orgpolicy.ListPoliciesResponse( - next_page_token="next_page_token_value", - ) + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = orgpolicy.ListPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_policies(request) + response = client.delete_policy(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPoliciesPager) - assert response.next_page_token == "next_page_token_value" + assert response is None -def test_list_policies_rest_required_fields(request_type=orgpolicy.ListPoliciesRequest): +def test_delete_policy_rest_required_fields(request_type=orgpolicy.DeletePolicyRequest): transport_class = transports.OrgPolicyRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -3079,28 +6196,23 @@ def test_list_policies_rest_required_fields(request_type=orgpolicy.ListPoliciesR unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_policies._get_unset_required_fields(jsonified_request) + ).delete_policy._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_policies._get_unset_required_fields(jsonified_request) + ).delete_policy._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + assert not set(unset_fields) - set(("etag",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3109,7 +6221,7 @@ def test_list_policies_rest_required_fields(request_type=orgpolicy.ListPoliciesR request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = orgpolicy.ListPoliciesResponse() + return_value = None # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -3121,47 +6233,36 @@ def test_list_policies_rest_required_fields(request_type=orgpolicy.ListPoliciesR pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "delete", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = orgpolicy.ListPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_policies(request) + response = client.delete_policy(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_policies_rest_unset_required_fields(): +def test_delete_policy_rest_unset_required_fields(): transport = transports.OrgPolicyRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_policies._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.delete_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag",)) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_policies_rest_interceptors(null_interceptor): +def test_delete_policy_rest_interceptors(null_interceptor): transport = transports.OrgPolicyRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.OrgPolicyRestInterceptor(), @@ -3172,13 +6273,10 @@ def test_list_policies_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.OrgPolicyRestInterceptor, "post_list_policies" - ) as post, mock.patch.object( - transports.OrgPolicyRestInterceptor, "pre_list_policies" + transports.OrgPolicyRestInterceptor, "pre_delete_policy" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = orgpolicy.ListPoliciesRequest.pb(orgpolicy.ListPoliciesRequest()) + pb_message = orgpolicy.DeletePolicyRequest.pb(orgpolicy.DeletePolicyRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3189,19 +6287,15 @@ def test_list_policies_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = orgpolicy.ListPoliciesResponse.to_json( - orgpolicy.ListPoliciesResponse() - ) - request = orgpolicy.ListPoliciesRequest() + request = orgpolicy.DeletePolicyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = orgpolicy.ListPoliciesResponse() - client.list_policies( + client.delete_policy( request, metadata=[ ("key", "val"), @@ -3210,11 +6304,10 @@ def test_list_policies_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_list_policies_rest_bad_request( - transport: str = "rest", request_type=orgpolicy.ListPoliciesRequest +def test_delete_policy_rest_bad_request( + transport: str = "rest", request_type=orgpolicy.DeletePolicyRequest ): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3222,7 +6315,7 @@ def test_list_policies_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} + request_init = {"name": "projects/sample1/policies/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -3234,10 +6327,10 @@ def test_list_policies_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_policies(request) + client.delete_policy(request) -def test_list_policies_rest_flattened(): +def test_delete_policy_rest_flattened(): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -3246,38 +6339,36 @@ def test_list_policies_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = orgpolicy.ListPoliciesResponse() + return_value = None # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1"} + sample_request = {"name": "projects/sample1/policies/sample2"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = orgpolicy.ListPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_policies(**mock_args) + client.delete_policy(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{parent=projects/*}/policies" % client.transport._host, args[1] + "%s/v2/{name=projects/*/policies/*}" % client.transport._host, args[1] ) -def test_list_policies_rest_flattened_error(transport: str = "rest"): +def test_delete_policy_rest_flattened_error(transport: str = "rest"): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3286,118 +6377,156 @@ def test_list_policies_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_policies( - orgpolicy.ListPoliciesRequest(), - parent="parent_value", + client.delete_policy( + orgpolicy.DeletePolicyRequest(), + name="name_value", ) -def test_list_policies_rest_pager(transport: str = "rest"): +def test_delete_policy_rest_error(): client = OrgPolicyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - orgpolicy.ListPoliciesResponse( - policies=[ - orgpolicy.Policy(), - orgpolicy.Policy(), - orgpolicy.Policy(), - ], - next_page_token="abc", - ), - orgpolicy.ListPoliciesResponse( - policies=[], - next_page_token="def", - ), - orgpolicy.ListPoliciesResponse( - policies=[ - orgpolicy.Policy(), - ], - next_page_token="ghi", - ), - orgpolicy.ListPoliciesResponse( - policies=[ - orgpolicy.Policy(), - orgpolicy.Policy(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(orgpolicy.ListPoliciesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "projects/sample1"} - - pager = client.list_policies(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, orgpolicy.Policy) for i in results) - - pages = list(client.list_policies(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - orgpolicy.GetPolicyRequest, + orgpolicy.CreateCustomConstraintRequest, dict, ], ) -def test_get_policy_rest(request_type): +def test_create_custom_constraint_rest(request_type): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/policies/sample2"} + request_init = {"parent": "organizations/sample1"} + request_init["custom_constraint"] = { + "name": "name_value", + "resource_types": ["resource_types_value1", "resource_types_value2"], + "method_types": [1], + "condition": "condition_value", + "action_type": 1, + "display_name": "display_name_value", + "description": "description_value", + "update_time": {"seconds": 751, "nanos": 543}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = orgpolicy.CreateCustomConstraintRequest.meta.fields[ + "custom_constraint" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["custom_constraint"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["custom_constraint"][field])): + del request_init["custom_constraint"][field][i][subfield] + else: + del request_init["custom_constraint"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = orgpolicy.Policy( + return_value = constraint.CustomConstraint( name="name_value", + resource_types=["resource_types_value"], + method_types=[constraint.CustomConstraint.MethodType.CREATE], + condition="condition_value", + action_type=constraint.CustomConstraint.ActionType.ALLOW, + display_name="display_name_value", + description="description_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = orgpolicy.Policy.pb(return_value) + return_value = constraint.CustomConstraint.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_policy(request) + response = client.create_custom_constraint(request) # Establish that the response is the type that we expect. - assert isinstance(response, orgpolicy.Policy) + assert isinstance(response, constraint.CustomConstraint) assert response.name == "name_value" + assert response.resource_types == ["resource_types_value"] + assert response.method_types == [constraint.CustomConstraint.MethodType.CREATE] + assert response.condition == "condition_value" + assert response.action_type == constraint.CustomConstraint.ActionType.ALLOW + assert response.display_name == "display_name_value" + assert response.description == "description_value" -def test_get_policy_rest_required_fields(request_type=orgpolicy.GetPolicyRequest): +def test_create_custom_constraint_rest_required_fields( + request_type=orgpolicy.CreateCustomConstraintRequest, +): transport_class = transports.OrgPolicyRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -3412,21 +6541,21 @@ def test_get_policy_rest_required_fields(request_type=orgpolicy.GetPolicyRequest unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_policy._get_unset_required_fields(jsonified_request) + ).create_custom_constraint._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_policy._get_unset_required_fields(jsonified_request) + ).create_custom_constraint._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3435,7 +6564,7 @@ def test_get_policy_rest_required_fields(request_type=orgpolicy.GetPolicyRequest request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = orgpolicy.Policy() + return_value = constraint.CustomConstraint() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -3447,39 +6576,48 @@ def test_get_policy_rest_required_fields(request_type=orgpolicy.GetPolicyRequest pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = orgpolicy.Policy.pb(return_value) + return_value = constraint.CustomConstraint.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_policy(request) + response = client.create_custom_constraint(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_policy_rest_unset_required_fields(): +def test_create_custom_constraint_rest_unset_required_fields(): transport = transports.OrgPolicyRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.create_custom_constraint._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "customConstraint", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_policy_rest_interceptors(null_interceptor): +def test_create_custom_constraint_rest_interceptors(null_interceptor): transport = transports.OrgPolicyRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.OrgPolicyRestInterceptor(), @@ -3490,13 +6628,15 @@ def test_get_policy_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.OrgPolicyRestInterceptor, "post_get_policy" + transports.OrgPolicyRestInterceptor, "post_create_custom_constraint" ) as post, mock.patch.object( - transports.OrgPolicyRestInterceptor, "pre_get_policy" + transports.OrgPolicyRestInterceptor, "pre_create_custom_constraint" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = orgpolicy.GetPolicyRequest.pb(orgpolicy.GetPolicyRequest()) + pb_message = orgpolicy.CreateCustomConstraintRequest.pb( + orgpolicy.CreateCustomConstraintRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3507,17 +6647,19 @@ def test_get_policy_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = orgpolicy.Policy.to_json(orgpolicy.Policy()) + req.return_value._content = constraint.CustomConstraint.to_json( + constraint.CustomConstraint() + ) - request = orgpolicy.GetPolicyRequest() + request = orgpolicy.CreateCustomConstraintRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = orgpolicy.Policy() + post.return_value = constraint.CustomConstraint() - client.get_policy( + client.create_custom_constraint( request, metadata=[ ("key", "val"), @@ -3529,8 +6671,8 @@ def test_get_policy_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_policy_rest_bad_request( - transport: str = "rest", request_type=orgpolicy.GetPolicyRequest +def test_create_custom_constraint_rest_bad_request( + transport: str = "rest", request_type=orgpolicy.CreateCustomConstraintRequest ): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3538,7 +6680,7 @@ def test_get_policy_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/policies/sample2"} + request_init = {"parent": "organizations/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -3550,10 +6692,10 @@ def test_get_policy_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_policy(request) + client.create_custom_constraint(request) -def test_get_policy_rest_flattened(): +def test_create_custom_constraint_rest_flattened(): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -3562,14 +6704,15 @@ def test_get_policy_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = orgpolicy.Policy() + return_value = constraint.CustomConstraint() # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/policies/sample2"} + sample_request = {"parent": "organizations/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + custom_constraint=constraint.CustomConstraint(name="name_value"), ) mock_args.update(sample_request) @@ -3577,23 +6720,24 @@ def test_get_policy_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = orgpolicy.Policy.pb(return_value) + return_value = constraint.CustomConstraint.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_policy(**mock_args) + client.create_custom_constraint(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{name=projects/*/policies/*}" % client.transport._host, args[1] + "%s/v2/{parent=organizations/*}/customConstraints" % client.transport._host, + args[1], ) -def test_get_policy_rest_flattened_error(transport: str = "rest"): +def test_create_custom_constraint_rest_flattened_error(transport: str = "rest"): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3602,13 +6746,14 @@ def test_get_policy_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_policy( - orgpolicy.GetPolicyRequest(), - name="name_value", + client.create_custom_constraint( + orgpolicy.CreateCustomConstraintRequest(), + parent="parent_value", + custom_constraint=constraint.CustomConstraint(name="name_value"), ) -def test_get_policy_rest_error(): +def test_create_custom_constraint_rest_error(): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -3617,50 +6762,142 @@ def test_get_policy_rest_error(): @pytest.mark.parametrize( "request_type", [ - orgpolicy.GetEffectivePolicyRequest, + orgpolicy.UpdateCustomConstraintRequest, dict, ], ) -def test_get_effective_policy_rest(request_type): +def test_update_custom_constraint_rest(request_type): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/policies/sample2"} + request_init = { + "custom_constraint": {"name": "organizations/sample1/customConstraints/sample2"} + } + request_init["custom_constraint"] = { + "name": "organizations/sample1/customConstraints/sample2", + "resource_types": ["resource_types_value1", "resource_types_value2"], + "method_types": [1], + "condition": "condition_value", + "action_type": 1, + "display_name": "display_name_value", + "description": "description_value", + "update_time": {"seconds": 751, "nanos": 543}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = orgpolicy.UpdateCustomConstraintRequest.meta.fields[ + "custom_constraint" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["custom_constraint"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["custom_constraint"][field])): + del request_init["custom_constraint"][field][i][subfield] + else: + del request_init["custom_constraint"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = orgpolicy.Policy( + return_value = constraint.CustomConstraint( name="name_value", + resource_types=["resource_types_value"], + method_types=[constraint.CustomConstraint.MethodType.CREATE], + condition="condition_value", + action_type=constraint.CustomConstraint.ActionType.ALLOW, + display_name="display_name_value", + description="description_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = orgpolicy.Policy.pb(return_value) + return_value = constraint.CustomConstraint.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_effective_policy(request) + response = client.update_custom_constraint(request) # Establish that the response is the type that we expect. - assert isinstance(response, orgpolicy.Policy) + assert isinstance(response, constraint.CustomConstraint) assert response.name == "name_value" + assert response.resource_types == ["resource_types_value"] + assert response.method_types == [constraint.CustomConstraint.MethodType.CREATE] + assert response.condition == "condition_value" + assert response.action_type == constraint.CustomConstraint.ActionType.ALLOW + assert response.display_name == "display_name_value" + assert response.description == "description_value" -def test_get_effective_policy_rest_required_fields( - request_type=orgpolicy.GetEffectivePolicyRequest, +def test_update_custom_constraint_rest_required_fields( + request_type=orgpolicy.UpdateCustomConstraintRequest, ): transport_class = transports.OrgPolicyRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -3675,21 +6912,17 @@ def test_get_effective_policy_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_effective_policy._get_unset_required_fields(jsonified_request) + ).update_custom_constraint._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_effective_policy._get_unset_required_fields(jsonified_request) + ).update_custom_constraint._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3698,7 +6931,7 @@ def test_get_effective_policy_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = orgpolicy.Policy() + return_value = constraint.CustomConstraint() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -3710,39 +6943,40 @@ def test_get_effective_policy_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = orgpolicy.Policy.pb(return_value) + return_value = constraint.CustomConstraint.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_effective_policy(request) + response = client.update_custom_constraint(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_effective_policy_rest_unset_required_fields(): +def test_update_custom_constraint_rest_unset_required_fields(): transport = transports.OrgPolicyRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_effective_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.update_custom_constraint._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("customConstraint",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_effective_policy_rest_interceptors(null_interceptor): +def test_update_custom_constraint_rest_interceptors(null_interceptor): transport = transports.OrgPolicyRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.OrgPolicyRestInterceptor(), @@ -3753,14 +6987,14 @@ def test_get_effective_policy_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.OrgPolicyRestInterceptor, "post_get_effective_policy" + transports.OrgPolicyRestInterceptor, "post_update_custom_constraint" ) as post, mock.patch.object( - transports.OrgPolicyRestInterceptor, "pre_get_effective_policy" + transports.OrgPolicyRestInterceptor, "pre_update_custom_constraint" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = orgpolicy.GetEffectivePolicyRequest.pb( - orgpolicy.GetEffectivePolicyRequest() + pb_message = orgpolicy.UpdateCustomConstraintRequest.pb( + orgpolicy.UpdateCustomConstraintRequest() ) transcode.return_value = { "method": "post", @@ -3772,17 +7006,19 @@ def test_get_effective_policy_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = orgpolicy.Policy.to_json(orgpolicy.Policy()) + req.return_value._content = constraint.CustomConstraint.to_json( + constraint.CustomConstraint() + ) - request = orgpolicy.GetEffectivePolicyRequest() + request = orgpolicy.UpdateCustomConstraintRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = orgpolicy.Policy() + post.return_value = constraint.CustomConstraint() - client.get_effective_policy( + client.update_custom_constraint( request, metadata=[ ("key", "val"), @@ -3794,8 +7030,8 @@ def test_get_effective_policy_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_effective_policy_rest_bad_request( - transport: str = "rest", request_type=orgpolicy.GetEffectivePolicyRequest +def test_update_custom_constraint_rest_bad_request( + transport: str = "rest", request_type=orgpolicy.UpdateCustomConstraintRequest ): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3803,7 +7039,9 @@ def test_get_effective_policy_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/policies/sample2"} + request_init = { + "custom_constraint": {"name": "organizations/sample1/customConstraints/sample2"} + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -3815,10 +7053,10 @@ def test_get_effective_policy_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_effective_policy(request) + client.update_custom_constraint(request) -def test_get_effective_policy_rest_flattened(): +def test_update_custom_constraint_rest_flattened(): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -3827,206 +7065,123 @@ def test_get_effective_policy_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = orgpolicy.Policy() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/policies/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = orgpolicy.Policy.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.get_effective_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{name=projects/*/policies/*}:getEffectivePolicy" - % client.transport._host, - args[1], - ) - - -def test_get_effective_policy_rest_flattened_error(transport: str = "rest"): - client = OrgPolicyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_effective_policy( - orgpolicy.GetEffectivePolicyRequest(), - name="name_value", - ) - - -def test_get_effective_policy_rest_error(): - client = OrgPolicyClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - orgpolicy.CreatePolicyRequest, - dict, - ], -) -def test_create_policy_rest(request_type): - client = OrgPolicyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} - request_init["policy"] = { - "name": "name_value", - "spec": { - "etag": "etag_value", - "update_time": {"seconds": 751, "nanos": 543}, - "rules": [ - { - "values": { - "allowed_values": [ - "allowed_values_value1", - "allowed_values_value2", - ], - "denied_values": [ - "denied_values_value1", - "denied_values_value2", - ], - }, - "allow_all": True, - "deny_all": True, - "enforce": True, - "condition": { - "expression": "expression_value", - "title": "title_value", - "description": "description_value", - "location": "location_value", - }, - } - ], - "inherit_from_parent": True, - "reset": True, - }, - "alternate": {"launch": "launch_value", "spec": {}}, - "dry_run_spec": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + return_value = constraint.CustomConstraint() - # Determine if the message type is proto-plus or protobuf - test_field = orgpolicy.CreatePolicyRequest.meta.fields["policy"] + # get arguments that satisfy an http rule for this method + sample_request = { + "custom_constraint": { + "name": "organizations/sample1/customConstraints/sample2" + } + } - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # get truthy value for each flattened field + mock_args = dict( + custom_constraint=constraint.CustomConstraint(name="name_value"), + ) + mock_args.update(sample_request) - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = constraint.CustomConstraint.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + client.update_custom_constraint(**mock_args) - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{custom_constraint.name=organizations/*/customConstraints/*}" + % client.transport._host, + args[1], + ) - subfields_not_in_runtime = [] - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["policy"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value +def test_update_custom_constraint_rest_flattened_error(transport: str = "rest"): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_custom_constraint( + orgpolicy.UpdateCustomConstraintRequest(), + custom_constraint=constraint.CustomConstraint(name="name_value"), + ) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["policy"][field])): - del request_init["policy"][field][i][subfield] - else: - del request_init["policy"][field][subfield] + +def test_update_custom_constraint_rest_error(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + orgpolicy.GetCustomConstraintRequest, + dict, + ], +) +def test_get_custom_constraint_rest(request_type): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/customConstraints/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = orgpolicy.Policy( + return_value = constraint.CustomConstraint( name="name_value", + resource_types=["resource_types_value"], + method_types=[constraint.CustomConstraint.MethodType.CREATE], + condition="condition_value", + action_type=constraint.CustomConstraint.ActionType.ALLOW, + display_name="display_name_value", + description="description_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = orgpolicy.Policy.pb(return_value) + return_value = constraint.CustomConstraint.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_policy(request) + response = client.get_custom_constraint(request) # Establish that the response is the type that we expect. - assert isinstance(response, orgpolicy.Policy) + assert isinstance(response, constraint.CustomConstraint) assert response.name == "name_value" + assert response.resource_types == ["resource_types_value"] + assert response.method_types == [constraint.CustomConstraint.MethodType.CREATE] + assert response.condition == "condition_value" + assert response.action_type == constraint.CustomConstraint.ActionType.ALLOW + assert response.display_name == "display_name_value" + assert response.description == "description_value" -def test_create_policy_rest_required_fields(request_type=orgpolicy.CreatePolicyRequest): +def test_get_custom_constraint_rest_required_fields( + request_type=orgpolicy.GetCustomConstraintRequest, +): transport_class = transports.OrgPolicyRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -4041,21 +7196,21 @@ def test_create_policy_rest_required_fields(request_type=orgpolicy.CreatePolicyR unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_policy._get_unset_required_fields(jsonified_request) + ).get_custom_constraint._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_policy._get_unset_required_fields(jsonified_request) + ).get_custom_constraint._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4064,7 +7219,7 @@ def test_create_policy_rest_required_fields(request_type=orgpolicy.CreatePolicyR request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = orgpolicy.Policy() + return_value = constraint.CustomConstraint() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -4076,48 +7231,39 @@ def test_create_policy_rest_required_fields(request_type=orgpolicy.CreatePolicyR pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = orgpolicy.Policy.pb(return_value) + return_value = constraint.CustomConstraint.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_policy(request) + response = client.get_custom_constraint(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_policy_rest_unset_required_fields(): +def test_get_custom_constraint_rest_unset_required_fields(): transport = transports.OrgPolicyRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_policy._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "policy", - ) - ) - ) + unset_fields = transport.get_custom_constraint._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_policy_rest_interceptors(null_interceptor): +def test_get_custom_constraint_rest_interceptors(null_interceptor): transport = transports.OrgPolicyRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.OrgPolicyRestInterceptor(), @@ -4128,13 +7274,15 @@ def test_create_policy_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.OrgPolicyRestInterceptor, "post_create_policy" + transports.OrgPolicyRestInterceptor, "post_get_custom_constraint" ) as post, mock.patch.object( - transports.OrgPolicyRestInterceptor, "pre_create_policy" + transports.OrgPolicyRestInterceptor, "pre_get_custom_constraint" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = orgpolicy.CreatePolicyRequest.pb(orgpolicy.CreatePolicyRequest()) + pb_message = orgpolicy.GetCustomConstraintRequest.pb( + orgpolicy.GetCustomConstraintRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4145,17 +7293,19 @@ def test_create_policy_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = orgpolicy.Policy.to_json(orgpolicy.Policy()) + req.return_value._content = constraint.CustomConstraint.to_json( + constraint.CustomConstraint() + ) - request = orgpolicy.CreatePolicyRequest() + request = orgpolicy.GetCustomConstraintRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = orgpolicy.Policy() + post.return_value = constraint.CustomConstraint() - client.create_policy( + client.get_custom_constraint( request, metadata=[ ("key", "val"), @@ -4167,8 +7317,8 @@ def test_create_policy_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_policy_rest_bad_request( - transport: str = "rest", request_type=orgpolicy.CreatePolicyRequest +def test_get_custom_constraint_rest_bad_request( + transport: str = "rest", request_type=orgpolicy.GetCustomConstraintRequest ): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4176,7 +7326,7 @@ def test_create_policy_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1"} + request_init = {"name": "organizations/sample1/customConstraints/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -4188,10 +7338,10 @@ def test_create_policy_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_policy(request) + client.get_custom_constraint(request) -def test_create_policy_rest_flattened(): +def test_get_custom_constraint_rest_flattened(): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -4200,205 +7350,106 @@ def test_create_policy_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = orgpolicy.Policy() + return_value = constraint.CustomConstraint() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - policy=orgpolicy.Policy(name="name_value"), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = orgpolicy.Policy.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.create_policy(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v2/{parent=projects/*}/policies" % client.transport._host, args[1] - ) - - -def test_create_policy_rest_flattened_error(transport: str = "rest"): - client = OrgPolicyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_policy( - orgpolicy.CreatePolicyRequest(), - parent="parent_value", - policy=orgpolicy.Policy(name="name_value"), - ) - - -def test_create_policy_rest_error(): - client = OrgPolicyClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - orgpolicy.UpdatePolicyRequest, - dict, - ], -) -def test_update_policy_rest(request_type): - client = OrgPolicyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"policy": {"name": "projects/sample1/policies/sample2"}} - request_init["policy"] = { - "name": "projects/sample1/policies/sample2", - "spec": { - "etag": "etag_value", - "update_time": {"seconds": 751, "nanos": 543}, - "rules": [ - { - "values": { - "allowed_values": [ - "allowed_values_value1", - "allowed_values_value2", - ], - "denied_values": [ - "denied_values_value1", - "denied_values_value2", - ], - }, - "allow_all": True, - "deny_all": True, - "enforce": True, - "condition": { - "expression": "expression_value", - "title": "title_value", - "description": "description_value", - "location": "location_value", - }, - } - ], - "inherit_from_parent": True, - "reset": True, - }, - "alternate": {"launch": "launch_value", "spec": {}}, - "dry_run_spec": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + sample_request = {"name": "organizations/sample1/customConstraints/sample2"} - # Determine if the message type is proto-plus or protobuf - test_field = orgpolicy.UpdatePolicyRequest.meta.fields["policy"] + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = constraint.CustomConstraint.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + client.get_custom_constraint(**mock_args) - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v2/{name=organizations/*/customConstraints/*}" % client.transport._host, + args[1], + ) - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - subfields_not_in_runtime = [] +def test_get_custom_constraint_rest_flattened_error(transport: str = "rest"): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["policy"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_custom_constraint( + orgpolicy.GetCustomConstraintRequest(), + name="name_value", + ) - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["policy"][field])): - del request_init["policy"][field][i][subfield] - else: - del request_init["policy"][field][subfield] +def test_get_custom_constraint_rest_error(): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + orgpolicy.ListCustomConstraintsRequest, + dict, + ], +) +def test_list_custom_constraints_rest(request_type): + client = OrgPolicyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = orgpolicy.Policy( - name="name_value", + return_value = orgpolicy.ListCustomConstraintsResponse( + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = orgpolicy.Policy.pb(return_value) + return_value = orgpolicy.ListCustomConstraintsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_policy(request) + response = client.list_custom_constraints(request) # Establish that the response is the type that we expect. - assert isinstance(response, orgpolicy.Policy) - assert response.name == "name_value" + assert isinstance(response, pagers.ListCustomConstraintsPager) + assert response.next_page_token == "next_page_token_value" -def test_update_policy_rest_required_fields(request_type=orgpolicy.UpdatePolicyRequest): +def test_list_custom_constraints_rest_required_fields( + request_type=orgpolicy.ListCustomConstraintsRequest, +): transport_class = transports.OrgPolicyRestTransport request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -4413,19 +7464,28 @@ def test_update_policy_rest_required_fields(request_type=orgpolicy.UpdatePolicyR unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_policy._get_unset_required_fields(jsonified_request) + ).list_custom_constraints._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["parent"] = "parent_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_policy._get_unset_required_fields(jsonified_request) + ).list_custom_constraints._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask",)) + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4434,7 +7494,7 @@ def test_update_policy_rest_required_fields(request_type=orgpolicy.UpdatePolicyR request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = orgpolicy.Policy() + return_value = orgpolicy.ListCustomConstraintsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -4446,40 +7506,47 @@ def test_update_policy_rest_required_fields(request_type=orgpolicy.UpdatePolicyR pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = orgpolicy.Policy.pb(return_value) + return_value = orgpolicy.ListCustomConstraintsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_policy(request) + response = client.list_custom_constraints(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_policy_rest_unset_required_fields(): +def test_list_custom_constraints_rest_unset_required_fields(): transport = transports.OrgPolicyRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("policy",))) + unset_fields = transport.list_custom_constraints._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_policy_rest_interceptors(null_interceptor): +def test_list_custom_constraints_rest_interceptors(null_interceptor): transport = transports.OrgPolicyRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.OrgPolicyRestInterceptor(), @@ -4490,13 +7557,15 @@ def test_update_policy_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.OrgPolicyRestInterceptor, "post_update_policy" + transports.OrgPolicyRestInterceptor, "post_list_custom_constraints" ) as post, mock.patch.object( - transports.OrgPolicyRestInterceptor, "pre_update_policy" + transports.OrgPolicyRestInterceptor, "pre_list_custom_constraints" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = orgpolicy.UpdatePolicyRequest.pb(orgpolicy.UpdatePolicyRequest()) + pb_message = orgpolicy.ListCustomConstraintsRequest.pb( + orgpolicy.ListCustomConstraintsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4507,17 +7576,19 @@ def test_update_policy_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = orgpolicy.Policy.to_json(orgpolicy.Policy()) + req.return_value._content = orgpolicy.ListCustomConstraintsResponse.to_json( + orgpolicy.ListCustomConstraintsResponse() + ) - request = orgpolicy.UpdatePolicyRequest() + request = orgpolicy.ListCustomConstraintsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = orgpolicy.Policy() + post.return_value = orgpolicy.ListCustomConstraintsResponse() - client.update_policy( + client.list_custom_constraints( request, metadata=[ ("key", "val"), @@ -4529,8 +7600,8 @@ def test_update_policy_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_policy_rest_bad_request( - transport: str = "rest", request_type=orgpolicy.UpdatePolicyRequest +def test_list_custom_constraints_rest_bad_request( + transport: str = "rest", request_type=orgpolicy.ListCustomConstraintsRequest ): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4538,7 +7609,7 @@ def test_update_policy_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"policy": {"name": "projects/sample1/policies/sample2"}} + request_init = {"parent": "organizations/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -4550,10 +7621,10 @@ def test_update_policy_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_policy(request) + client.list_custom_constraints(request) -def test_update_policy_rest_flattened(): +def test_list_custom_constraints_rest_flattened(): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -4562,14 +7633,14 @@ def test_update_policy_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = orgpolicy.Policy() + return_value = orgpolicy.ListCustomConstraintsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"policy": {"name": "projects/sample1/policies/sample2"}} + sample_request = {"parent": "organizations/sample1"} # get truthy value for each flattened field mock_args = dict( - policy=orgpolicy.Policy(name="name_value"), + parent="parent_value", ) mock_args.update(sample_request) @@ -4577,24 +7648,24 @@ def test_update_policy_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = orgpolicy.Policy.pb(return_value) + return_value = orgpolicy.ListCustomConstraintsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_policy(**mock_args) + client.list_custom_constraints(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{policy.name=projects/*/policies/*}" % client.transport._host, + "%s/v2/{parent=organizations/*}/customConstraints" % client.transport._host, args[1], ) -def test_update_policy_rest_flattened_error(transport: str = "rest"): +def test_list_custom_constraints_rest_flattened_error(transport: str = "rest"): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4603,33 +7674,90 @@ def test_update_policy_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_policy( - orgpolicy.UpdatePolicyRequest(), - policy=orgpolicy.Policy(name="name_value"), + client.list_custom_constraints( + orgpolicy.ListCustomConstraintsRequest(), + parent="parent_value", ) -def test_update_policy_rest_error(): +def test_list_custom_constraints_rest_pager(transport: str = "rest"): client = OrgPolicyClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + orgpolicy.ListCustomConstraintsResponse( + custom_constraints=[ + constraint.CustomConstraint(), + constraint.CustomConstraint(), + constraint.CustomConstraint(), + ], + next_page_token="abc", + ), + orgpolicy.ListCustomConstraintsResponse( + custom_constraints=[], + next_page_token="def", + ), + orgpolicy.ListCustomConstraintsResponse( + custom_constraints=[ + constraint.CustomConstraint(), + ], + next_page_token="ghi", + ), + orgpolicy.ListCustomConstraintsResponse( + custom_constraints=[ + constraint.CustomConstraint(), + constraint.CustomConstraint(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + orgpolicy.ListCustomConstraintsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "organizations/sample1"} + + pager = client.list_custom_constraints(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, constraint.CustomConstraint) for i in results) + + pages = list(client.list_custom_constraints(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - orgpolicy.DeletePolicyRequest, + orgpolicy.DeleteCustomConstraintRequest, dict, ], ) -def test_delete_policy_rest(request_type): +def test_delete_custom_constraint_rest(request_type): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/policies/sample2"} + request_init = {"name": "organizations/sample1/customConstraints/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -4644,13 +7772,15 @@ def test_delete_policy_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_policy(request) + response = client.delete_custom_constraint(request) # Establish that the response is the type that we expect. assert response is None -def test_delete_policy_rest_required_fields(request_type=orgpolicy.DeletePolicyRequest): +def test_delete_custom_constraint_rest_required_fields( + request_type=orgpolicy.DeleteCustomConstraintRequest, +): transport_class = transports.OrgPolicyRestTransport request_init = {} @@ -4669,7 +7799,7 @@ def test_delete_policy_rest_required_fields(request_type=orgpolicy.DeletePolicyR unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_policy._get_unset_required_fields(jsonified_request) + ).delete_custom_constraint._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -4678,7 +7808,7 @@ def test_delete_policy_rest_required_fields(request_type=orgpolicy.DeletePolicyR unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_policy._get_unset_required_fields(jsonified_request) + ).delete_custom_constraint._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -4716,24 +7846,24 @@ def test_delete_policy_rest_required_fields(request_type=orgpolicy.DeletePolicyR response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_policy(request) + response = client.delete_custom_constraint(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_policy_rest_unset_required_fields(): +def test_delete_custom_constraint_rest_unset_required_fields(): transport = transports.OrgPolicyRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_policy._get_unset_required_fields({}) + unset_fields = transport.delete_custom_constraint._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_policy_rest_interceptors(null_interceptor): +def test_delete_custom_constraint_rest_interceptors(null_interceptor): transport = transports.OrgPolicyRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.OrgPolicyRestInterceptor(), @@ -4744,10 +7874,12 @@ def test_delete_policy_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.OrgPolicyRestInterceptor, "pre_delete_policy" + transports.OrgPolicyRestInterceptor, "pre_delete_custom_constraint" ) as pre: pre.assert_not_called() - pb_message = orgpolicy.DeletePolicyRequest.pb(orgpolicy.DeletePolicyRequest()) + pb_message = orgpolicy.DeleteCustomConstraintRequest.pb( + orgpolicy.DeleteCustomConstraintRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4759,14 +7891,14 @@ def test_delete_policy_rest_interceptors(null_interceptor): req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - request = orgpolicy.DeletePolicyRequest() + request = orgpolicy.DeleteCustomConstraintRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.delete_policy( + client.delete_custom_constraint( request, metadata=[ ("key", "val"), @@ -4777,8 +7909,8 @@ def test_delete_policy_rest_interceptors(null_interceptor): pre.assert_called_once() -def test_delete_policy_rest_bad_request( - transport: str = "rest", request_type=orgpolicy.DeletePolicyRequest +def test_delete_custom_constraint_rest_bad_request( + transport: str = "rest", request_type=orgpolicy.DeleteCustomConstraintRequest ): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4786,7 +7918,7 @@ def test_delete_policy_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/policies/sample2"} + request_init = {"name": "organizations/sample1/customConstraints/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -4798,10 +7930,10 @@ def test_delete_policy_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_policy(request) + client.delete_custom_constraint(request) -def test_delete_policy_rest_flattened(): +def test_delete_custom_constraint_rest_flattened(): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -4813,7 +7945,7 @@ def test_delete_policy_rest_flattened(): return_value = None # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/policies/sample2"} + sample_request = {"name": "organizations/sample1/customConstraints/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -4828,18 +7960,19 @@ def test_delete_policy_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_policy(**mock_args) + client.delete_custom_constraint(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v2/{name=projects/*/policies/*}" % client.transport._host, args[1] + "%s/v2/{name=organizations/*/customConstraints/*}" % client.transport._host, + args[1], ) -def test_delete_policy_rest_flattened_error(transport: str = "rest"): +def test_delete_custom_constraint_rest_flattened_error(transport: str = "rest"): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4848,13 +7981,13 @@ def test_delete_policy_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_policy( - orgpolicy.DeletePolicyRequest(), + client.delete_custom_constraint( + orgpolicy.DeleteCustomConstraintRequest(), name="name_value", ) -def test_delete_policy_rest_error(): +def test_delete_custom_constraint_rest_error(): client = OrgPolicyClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -5006,6 +8139,11 @@ def test_org_policy_base_transport(): "create_policy", "update_policy", "delete_policy", + "create_custom_constraint", + "update_custom_constraint", + "get_custom_constraint", + "list_custom_constraints", + "delete_custom_constraint", ) for method in methods: with pytest.raises(NotImplementedError): @@ -5282,6 +8420,21 @@ def test_org_policy_client_transport_session_collision(transport_name): session1 = client1.transport.delete_policy._session session2 = client2.transport.delete_policy._session assert session1 != session2 + session1 = client1.transport.create_custom_constraint._session + session2 = client2.transport.create_custom_constraint._session + assert session1 != session2 + session1 = client1.transport.update_custom_constraint._session + session2 = client2.transport.update_custom_constraint._session + assert session1 != session2 + session1 = client1.transport.get_custom_constraint._session + session2 = client2.transport.get_custom_constraint._session + assert session1 != session2 + session1 = client1.transport.list_custom_constraints._session + session2 = client2.transport.list_custom_constraints._session + assert session1 != session2 + session1 = client1.transport.delete_custom_constraint._session + session2 = client2.transport.delete_custom_constraint._session + assert session1 != session2 def test_org_policy_grpc_transport_channel(): @@ -5425,9 +8578,34 @@ def test_parse_constraint_path(): assert expected == actual +def test_custom_constraint_path(): + organization = "oyster" + custom_constraint = "nudibranch" + expected = ( + "organizations/{organization}/customConstraints/{custom_constraint}".format( + organization=organization, + custom_constraint=custom_constraint, + ) + ) + actual = OrgPolicyClient.custom_constraint_path(organization, custom_constraint) + assert expected == actual + + +def test_parse_custom_constraint_path(): + expected = { + "organization": "cuttlefish", + "custom_constraint": "mussel", + } + path = OrgPolicyClient.custom_constraint_path(**expected) + + # Check that the path construction is reversible. + actual = OrgPolicyClient.parse_custom_constraint_path(path) + assert expected == actual + + def test_policy_path(): - project = "oyster" - policy = "nudibranch" + project = "winkle" + policy = "nautilus" expected = "projects/{project}/policies/{policy}".format( project=project, policy=policy, @@ -5438,8 +8616,8 @@ def test_policy_path(): def test_parse_policy_path(): expected = { - "project": "cuttlefish", - "policy": "mussel", + "project": "scallop", + "policy": "abalone", } path = OrgPolicyClient.policy_path(**expected) @@ -5449,7 +8627,7 @@ def test_parse_policy_path(): def test_common_billing_account_path(): - billing_account = "winkle" + billing_account = "squid" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -5459,7 +8637,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nautilus", + "billing_account": "clam", } path = OrgPolicyClient.common_billing_account_path(**expected) @@ -5469,7 +8647,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "scallop" + folder = "whelk" expected = "folders/{folder}".format( folder=folder, ) @@ -5479,7 +8657,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "abalone", + "folder": "octopus", } path = OrgPolicyClient.common_folder_path(**expected) @@ -5489,7 +8667,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "squid" + organization = "oyster" expected = "organizations/{organization}".format( organization=organization, ) @@ -5499,7 +8677,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "clam", + "organization": "nudibranch", } path = OrgPolicyClient.common_organization_path(**expected) @@ -5509,7 +8687,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "whelk" + project = "cuttlefish" expected = "projects/{project}".format( project=project, ) @@ -5519,7 +8697,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "octopus", + "project": "mussel", } path = OrgPolicyClient.common_project_path(**expected) @@ -5529,8 +8707,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "oyster" - location = "nudibranch" + project = "winkle" + location = "nautilus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -5541,8 +8719,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "cuttlefish", - "location": "mussel", + "project": "scallop", + "location": "abalone", } path = OrgPolicyClient.common_location_path(**expected)