diff --git a/.librarian/generator-input/client-post-processing/remove-unused-imports.yaml b/.librarian/generator-input/client-post-processing/remove-unused-imports.yaml index b34603c55008..3ddb3835e8bb 100644 --- a/.librarian/generator-input/client-post-processing/remove-unused-imports.yaml +++ b/.librarian/generator-input/client-post-processing/remove-unused-imports.yaml @@ -20,6 +20,7 @@ replacements: before: | import google.cloud.gkehub.configmanagement.v1.configmanagement_pb2 as configmanagement_pb2 # type: ignore import google.cloud.gkehub.multiclusteringress.v1.multiclusteringress_pb2 as multiclusteringress_pb2 # type: ignore + import google.cloud.gkehub.rbacrolebindingactuation.v1.rbacrolebindingactuation_pb2 as rbacrolebindingactuation_pb2 # type: ignore after: "" count: 1 - paths: [ diff --git a/.librarian/generator-input/client-post-processing/sub-api-versioned-namespace.yaml b/.librarian/generator-input/client-post-processing/sub-api-versioned-namespace.yaml index 202c0ffa5f3b..abeff4bc7304 100644 --- a/.librarian/generator-input/client-post-processing/sub-api-versioned-namespace.yaml +++ b/.librarian/generator-input/client-post-processing/sub-api-versioned-namespace.yaml @@ -20,9 +20,11 @@ replacements: before: | import google.cloud.gkehub.configmanagement.v1.configmanagement_pb2 as configmanagement_pb2 # type: ignore import google.cloud.gkehub.multiclusteringress.v1.multiclusteringress_pb2 as multiclusteringress_pb2 # type: ignore + import google.cloud.gkehub.rbacrolebindingactuation.v1.rbacrolebindingactuation_pb2 as rbacrolebindingactuation_pb2 # type: ignore after: | from google.cloud.gkehub_v1 import configmanagement_v1 # type: ignore from google.cloud.gkehub_v1 import multiclusteringress_v1 # type: ignore + from google.cloud.gkehub_v1 import rbacrolebindingactuation_v1 # type: ignore count: 1 - paths: [ packages/google-cloud-gke-hub/google/cloud/gkehub_v1/types/feature.py @@ -36,6 +38,12 @@ replacements: before: google.cloud.gkehub.multiclusteringress.v1.multiclusteringress_pb2 after: google.cloud.gkehub_v1.multiclusteringress_v1 count: 1 + - paths: [ + packages/google-cloud-gke-hub/google/cloud/gkehub_v1/types/feature.py + ] + before: google.cloud.gkehub.rbacrolebindingactuation.v1.rbacrolebindingactuation_pb2 + after: google.cloud.gkehub_v1.rbacrolebindingactuation_v1 + count: 1 - paths: [ packages/google-cloud-gke-hub/google/cloud/gkehub_v1/types/feature.py ] @@ -48,6 +56,12 @@ replacements: before: configmanagement_pb2 after: configmanagement_v1 count: 4 + - paths: [ + packages/google-cloud-gke-hub/google/cloud/gkehub_v1/types/feature.py + ] + before: rbacrolebindingactuation_pb2 + after: rbacrolebindingactuation_v1 + count: 2 - paths: [ packages/google-cloud-gke-hub/docs/index.rst ] @@ -70,7 +84,9 @@ replacements: gkehub_v1/configmanagement_v1/services_ gkehub_v1/configmanagement_v1/types_ gkehub_v1/multiclusteringress_v1/services_ - gkehub_v1/multiclusteringress_v1/types_\n + gkehub_v1/multiclusteringress_v1/types_ + gkehub_v1/rbacrolebindingactuation_v1/services_ + gkehub_v1/rbacrolebindingactuation_v1/types_\n count: 1 - paths: [ packages/google-cloud-workflows/docs/index.rst diff --git a/.librarian/state.yaml b/.librarian/state.yaml index 817e0cfafa6c..abe7b02ce56c 100644 --- a/.librarian/state.yaml +++ b/.librarian/state.yaml @@ -1681,7 +1681,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-gke-hub version: 1.20.0 - last_generated_commit: 3322511885371d2b2253f209ccc3aa60d4100cfd + last_generated_commit: 7f62014053cd26b1acb7a1d0bf167104b64e3690 apis: - path: google/cloud/gkehub/v1 service_config: gkehub_v1.yaml @@ -1694,8 +1694,10 @@ libraries: - docs/CHANGELOG.md - docs/gkehub_v1/configmanagement_v1 - docs/gkehub_v1/multiclusteringress_v1 + - docs/gkehub_v1/rbacrolebindingactuation_v1 - google/cloud/gkehub_v1/configmanagement_v1 - google/cloud/gkehub_v1/multiclusteringress_v1 + - google/cloud/gkehub_v1/rbacrolebindingactuation_v1 remove_regex: - packages/google-cloud-gke-hub tag_format: '{id}-v{version}' diff --git a/packages/google-cloud-gke-hub/docs/gkehub_v1/rbacrolebindingactuation_v1/services_.rst b/packages/google-cloud-gke-hub/docs/gkehub_v1/rbacrolebindingactuation_v1/services_.rst new file mode 100644 index 000000000000..27304a7b0097 --- /dev/null +++ b/packages/google-cloud-gke-hub/docs/gkehub_v1/rbacrolebindingactuation_v1/services_.rst @@ -0,0 +1,4 @@ +Services for Google Cloud Gkehub RbacRoleBindingActuation v1 API +================================================================ +.. toctree:: + :maxdepth: 2 diff --git a/packages/google-cloud-gke-hub/docs/gkehub_v1/rbacrolebindingactuation_v1/types_.rst b/packages/google-cloud-gke-hub/docs/gkehub_v1/rbacrolebindingactuation_v1/types_.rst new file mode 100644 index 000000000000..2e2e1e9cfe88 --- /dev/null +++ b/packages/google-cloud-gke-hub/docs/gkehub_v1/rbacrolebindingactuation_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Gkehub RbacRoleBindingActuation v1 API +============================================================= + +.. automodule:: google.cloud.gkehub_v1.rbacrolebindingactuation_v1.types + :members: + :show-inheritance: diff --git a/packages/google-cloud-gke-hub/docs/index.rst b/packages/google-cloud-gke-hub/docs/index.rst index 53c3bfd0782f..386e551de3db 100644 --- a/packages/google-cloud-gke-hub/docs/index.rst +++ b/packages/google-cloud-gke-hub/docs/index.rst @@ -17,6 +17,8 @@ API Reference gkehub_v1/configmanagement_v1/types_ gkehub_v1/multiclusteringress_v1/services_ gkehub_v1/multiclusteringress_v1/types_ + gkehub_v1/rbacrolebindingactuation_v1/services_ + gkehub_v1/rbacrolebindingactuation_v1/types_ API Reference ------------- diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub/__init__.py b/packages/google-cloud-gke-hub/google/cloud/gkehub/__init__.py index 2afceefe8af0..3f93fd66a5f5 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub/__init__.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub/__init__.py @@ -28,6 +28,24 @@ FeatureState, MembershipFeatureSpec, MembershipFeatureState, + ScopeFeatureSpec, + ScopeFeatureState, +) +from google.cloud.gkehub_v1.types.fleet import ( + BinaryAuthorizationConfig, + CompliancePostureConfig, + DefaultClusterConfig, + Fleet, + FleetLifecycleState, + MembershipBinding, + MembershipBindingLifecycleState, + Namespace, + NamespaceLifecycleState, + RBACRoleBinding, + RBACRoleBindingLifecycleState, + Scope, + ScopeLifecycleState, + SecurityPostureConfig, ) from google.cloud.gkehub_v1.types.membership import ( Authority, @@ -44,21 +62,63 @@ from google.cloud.gkehub_v1.types.service import ( ConnectAgentResource, CreateFeatureRequest, + CreateFleetRequest, + CreateMembershipBindingRequest, + CreateMembershipRBACRoleBindingRequest, CreateMembershipRequest, + CreateScopeNamespaceRequest, + CreateScopeRBACRoleBindingRequest, + CreateScopeRequest, DeleteFeatureRequest, + DeleteFleetRequest, + DeleteMembershipBindingRequest, + DeleteMembershipRBACRoleBindingRequest, DeleteMembershipRequest, + DeleteScopeNamespaceRequest, + DeleteScopeRBACRoleBindingRequest, + DeleteScopeRequest, GenerateConnectManifestRequest, GenerateConnectManifestResponse, + GenerateMembershipRBACRoleBindingYAMLRequest, + GenerateMembershipRBACRoleBindingYAMLResponse, GetFeatureRequest, + GetFleetRequest, + GetMembershipBindingRequest, + GetMembershipRBACRoleBindingRequest, GetMembershipRequest, + GetScopeNamespaceRequest, + GetScopeRBACRoleBindingRequest, + GetScopeRequest, + ListBoundMembershipsRequest, + ListBoundMembershipsResponse, ListFeaturesRequest, ListFeaturesResponse, + ListFleetsRequest, + ListFleetsResponse, + ListMembershipBindingsRequest, + ListMembershipBindingsResponse, + ListMembershipRBACRoleBindingsRequest, + ListMembershipRBACRoleBindingsResponse, ListMembershipsRequest, ListMembershipsResponse, + ListPermittedScopesRequest, + ListPermittedScopesResponse, + ListScopeNamespacesRequest, + ListScopeNamespacesResponse, + ListScopeRBACRoleBindingsRequest, + ListScopeRBACRoleBindingsResponse, + ListScopesRequest, + ListScopesResponse, OperationMetadata, TypeMeta, UpdateFeatureRequest, + UpdateFleetRequest, + UpdateMembershipBindingRequest, + UpdateMembershipRBACRoleBindingRequest, UpdateMembershipRequest, + UpdateScopeNamespaceRequest, + UpdateScopeRBACRoleBindingRequest, + UpdateScopeRequest, ) __all__ = ( @@ -71,6 +131,22 @@ "FeatureState", "MembershipFeatureSpec", "MembershipFeatureState", + "ScopeFeatureSpec", + "ScopeFeatureState", + "BinaryAuthorizationConfig", + "CompliancePostureConfig", + "DefaultClusterConfig", + "Fleet", + "FleetLifecycleState", + "MembershipBinding", + "MembershipBindingLifecycleState", + "Namespace", + "NamespaceLifecycleState", + "RBACRoleBinding", + "RBACRoleBindingLifecycleState", + "Scope", + "ScopeLifecycleState", + "SecurityPostureConfig", "Authority", "GkeCluster", "KubernetesMetadata", @@ -83,19 +159,61 @@ "ResourceOptions", "ConnectAgentResource", "CreateFeatureRequest", + "CreateFleetRequest", + "CreateMembershipBindingRequest", + "CreateMembershipRBACRoleBindingRequest", "CreateMembershipRequest", + "CreateScopeNamespaceRequest", + "CreateScopeRBACRoleBindingRequest", + "CreateScopeRequest", "DeleteFeatureRequest", + "DeleteFleetRequest", + "DeleteMembershipBindingRequest", + "DeleteMembershipRBACRoleBindingRequest", "DeleteMembershipRequest", + "DeleteScopeNamespaceRequest", + "DeleteScopeRBACRoleBindingRequest", + "DeleteScopeRequest", "GenerateConnectManifestRequest", "GenerateConnectManifestResponse", + "GenerateMembershipRBACRoleBindingYAMLRequest", + "GenerateMembershipRBACRoleBindingYAMLResponse", "GetFeatureRequest", + "GetFleetRequest", + "GetMembershipBindingRequest", + "GetMembershipRBACRoleBindingRequest", "GetMembershipRequest", + "GetScopeNamespaceRequest", + "GetScopeRBACRoleBindingRequest", + "GetScopeRequest", + "ListBoundMembershipsRequest", + "ListBoundMembershipsResponse", "ListFeaturesRequest", "ListFeaturesResponse", + "ListFleetsRequest", + "ListFleetsResponse", + "ListMembershipBindingsRequest", + "ListMembershipBindingsResponse", + "ListMembershipRBACRoleBindingsRequest", + "ListMembershipRBACRoleBindingsResponse", "ListMembershipsRequest", "ListMembershipsResponse", + "ListPermittedScopesRequest", + "ListPermittedScopesResponse", + "ListScopeNamespacesRequest", + "ListScopeNamespacesResponse", + "ListScopeRBACRoleBindingsRequest", + "ListScopeRBACRoleBindingsResponse", + "ListScopesRequest", + "ListScopesResponse", "OperationMetadata", "TypeMeta", "UpdateFeatureRequest", + "UpdateFleetRequest", + "UpdateMembershipBindingRequest", + "UpdateMembershipRBACRoleBindingRequest", "UpdateMembershipRequest", + "UpdateScopeNamespaceRequest", + "UpdateScopeRBACRoleBindingRequest", + "UpdateScopeRequest", ) diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/__init__.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/__init__.py index 883f723286b0..be91a5db41bb 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/__init__.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/__init__.py @@ -37,6 +37,24 @@ FeatureState, MembershipFeatureSpec, MembershipFeatureState, + ScopeFeatureSpec, + ScopeFeatureState, +) +from .types.fleet import ( + BinaryAuthorizationConfig, + CompliancePostureConfig, + DefaultClusterConfig, + Fleet, + FleetLifecycleState, + MembershipBinding, + MembershipBindingLifecycleState, + Namespace, + NamespaceLifecycleState, + RBACRoleBinding, + RBACRoleBindingLifecycleState, + Scope, + ScopeLifecycleState, + SecurityPostureConfig, ) from .types.membership import ( Authority, @@ -53,21 +71,63 @@ from .types.service import ( ConnectAgentResource, CreateFeatureRequest, + CreateFleetRequest, + CreateMembershipBindingRequest, + CreateMembershipRBACRoleBindingRequest, CreateMembershipRequest, + CreateScopeNamespaceRequest, + CreateScopeRBACRoleBindingRequest, + CreateScopeRequest, DeleteFeatureRequest, + DeleteFleetRequest, + DeleteMembershipBindingRequest, + DeleteMembershipRBACRoleBindingRequest, DeleteMembershipRequest, + DeleteScopeNamespaceRequest, + DeleteScopeRBACRoleBindingRequest, + DeleteScopeRequest, GenerateConnectManifestRequest, GenerateConnectManifestResponse, + GenerateMembershipRBACRoleBindingYAMLRequest, + GenerateMembershipRBACRoleBindingYAMLResponse, GetFeatureRequest, + GetFleetRequest, + GetMembershipBindingRequest, + GetMembershipRBACRoleBindingRequest, GetMembershipRequest, + GetScopeNamespaceRequest, + GetScopeRBACRoleBindingRequest, + GetScopeRequest, + ListBoundMembershipsRequest, + ListBoundMembershipsResponse, ListFeaturesRequest, ListFeaturesResponse, + ListFleetsRequest, + ListFleetsResponse, + ListMembershipBindingsRequest, + ListMembershipBindingsResponse, + ListMembershipRBACRoleBindingsRequest, + ListMembershipRBACRoleBindingsResponse, ListMembershipsRequest, ListMembershipsResponse, + ListPermittedScopesRequest, + ListPermittedScopesResponse, + ListScopeNamespacesRequest, + ListScopeNamespacesResponse, + ListScopeRBACRoleBindingsRequest, + ListScopeRBACRoleBindingsResponse, + ListScopesRequest, + ListScopesResponse, OperationMetadata, TypeMeta, UpdateFeatureRequest, + UpdateFleetRequest, + UpdateMembershipBindingRequest, + UpdateMembershipRBACRoleBindingRequest, UpdateMembershipRequest, + UpdateScopeNamespaceRequest, + UpdateScopeRBACRoleBindingRequest, + UpdateScopeRequest, ) if hasattr(api_core, "check_python_version") and hasattr( @@ -167,38 +227,96 @@ def _get_version(dependency_name): __all__ = ( "GkeHubAsyncClient", "Authority", + "BinaryAuthorizationConfig", "CommonFeatureSpec", "CommonFeatureState", + "CompliancePostureConfig", "ConnectAgentResource", "CreateFeatureRequest", + "CreateFleetRequest", + "CreateMembershipBindingRequest", + "CreateMembershipRBACRoleBindingRequest", "CreateMembershipRequest", + "CreateScopeNamespaceRequest", + "CreateScopeRBACRoleBindingRequest", + "CreateScopeRequest", + "DefaultClusterConfig", "DeleteFeatureRequest", + "DeleteFleetRequest", + "DeleteMembershipBindingRequest", + "DeleteMembershipRBACRoleBindingRequest", "DeleteMembershipRequest", + "DeleteScopeNamespaceRequest", + "DeleteScopeRBACRoleBindingRequest", + "DeleteScopeRequest", "Feature", "FeatureResourceState", "FeatureState", + "Fleet", + "FleetLifecycleState", "GenerateConnectManifestRequest", "GenerateConnectManifestResponse", + "GenerateMembershipRBACRoleBindingYAMLRequest", + "GenerateMembershipRBACRoleBindingYAMLResponse", "GetFeatureRequest", + "GetFleetRequest", + "GetMembershipBindingRequest", + "GetMembershipRBACRoleBindingRequest", "GetMembershipRequest", + "GetScopeNamespaceRequest", + "GetScopeRBACRoleBindingRequest", + "GetScopeRequest", "GkeCluster", "GkeHubClient", "KubernetesMetadata", "KubernetesResource", + "ListBoundMembershipsRequest", + "ListBoundMembershipsResponse", "ListFeaturesRequest", "ListFeaturesResponse", + "ListFleetsRequest", + "ListFleetsResponse", + "ListMembershipBindingsRequest", + "ListMembershipBindingsResponse", + "ListMembershipRBACRoleBindingsRequest", + "ListMembershipRBACRoleBindingsResponse", "ListMembershipsRequest", "ListMembershipsResponse", + "ListPermittedScopesRequest", + "ListPermittedScopesResponse", + "ListScopeNamespacesRequest", + "ListScopeNamespacesResponse", + "ListScopeRBACRoleBindingsRequest", + "ListScopeRBACRoleBindingsResponse", + "ListScopesRequest", + "ListScopesResponse", "Membership", + "MembershipBinding", + "MembershipBindingLifecycleState", "MembershipEndpoint", "MembershipFeatureSpec", "MembershipFeatureState", "MembershipState", "MonitoringConfig", + "Namespace", + "NamespaceLifecycleState", "OperationMetadata", + "RBACRoleBinding", + "RBACRoleBindingLifecycleState", "ResourceManifest", "ResourceOptions", + "Scope", + "ScopeFeatureSpec", + "ScopeFeatureState", + "ScopeLifecycleState", + "SecurityPostureConfig", "TypeMeta", "UpdateFeatureRequest", + "UpdateFleetRequest", + "UpdateMembershipBindingRequest", + "UpdateMembershipRBACRoleBindingRequest", "UpdateMembershipRequest", + "UpdateScopeNamespaceRequest", + "UpdateScopeRBACRoleBindingRequest", + "UpdateScopeRequest", ) diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/gapic_metadata.json b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/gapic_metadata.json index 042eb2e45e32..d123e114feb7 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/gapic_metadata.json +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/gapic_metadata.json @@ -15,55 +15,220 @@ "create_feature" ] }, + "CreateFleet": { + "methods": [ + "create_fleet" + ] + }, "CreateMembership": { "methods": [ "create_membership" ] }, + "CreateMembershipBinding": { + "methods": [ + "create_membership_binding" + ] + }, + "CreateMembershipRBACRoleBinding": { + "methods": [ + "create_membership_rbac_role_binding" + ] + }, + "CreateScope": { + "methods": [ + "create_scope" + ] + }, + "CreateScopeNamespace": { + "methods": [ + "create_scope_namespace" + ] + }, + "CreateScopeRBACRoleBinding": { + "methods": [ + "create_scope_rbac_role_binding" + ] + }, "DeleteFeature": { "methods": [ "delete_feature" ] }, + "DeleteFleet": { + "methods": [ + "delete_fleet" + ] + }, "DeleteMembership": { "methods": [ "delete_membership" ] }, + "DeleteMembershipBinding": { + "methods": [ + "delete_membership_binding" + ] + }, + "DeleteMembershipRBACRoleBinding": { + "methods": [ + "delete_membership_rbac_role_binding" + ] + }, + "DeleteScope": { + "methods": [ + "delete_scope" + ] + }, + "DeleteScopeNamespace": { + "methods": [ + "delete_scope_namespace" + ] + }, + "DeleteScopeRBACRoleBinding": { + "methods": [ + "delete_scope_rbac_role_binding" + ] + }, "GenerateConnectManifest": { "methods": [ "generate_connect_manifest" ] }, + "GenerateMembershipRBACRoleBindingYAML": { + "methods": [ + "generate_membership_rbac_role_binding_yaml" + ] + }, "GetFeature": { "methods": [ "get_feature" ] }, + "GetFleet": { + "methods": [ + "get_fleet" + ] + }, "GetMembership": { "methods": [ "get_membership" ] }, + "GetMembershipBinding": { + "methods": [ + "get_membership_binding" + ] + }, + "GetMembershipRBACRoleBinding": { + "methods": [ + "get_membership_rbac_role_binding" + ] + }, + "GetScope": { + "methods": [ + "get_scope" + ] + }, + "GetScopeNamespace": { + "methods": [ + "get_scope_namespace" + ] + }, + "GetScopeRBACRoleBinding": { + "methods": [ + "get_scope_rbac_role_binding" + ] + }, + "ListBoundMemberships": { + "methods": [ + "list_bound_memberships" + ] + }, "ListFeatures": { "methods": [ "list_features" ] }, + "ListFleets": { + "methods": [ + "list_fleets" + ] + }, + "ListMembershipBindings": { + "methods": [ + "list_membership_bindings" + ] + }, + "ListMembershipRBACRoleBindings": { + "methods": [ + "list_membership_rbac_role_bindings" + ] + }, "ListMemberships": { "methods": [ "list_memberships" ] }, + "ListPermittedScopes": { + "methods": [ + "list_permitted_scopes" + ] + }, + "ListScopeNamespaces": { + "methods": [ + "list_scope_namespaces" + ] + }, + "ListScopeRBACRoleBindings": { + "methods": [ + "list_scope_rbac_role_bindings" + ] + }, + "ListScopes": { + "methods": [ + "list_scopes" + ] + }, "UpdateFeature": { "methods": [ "update_feature" ] }, + "UpdateFleet": { + "methods": [ + "update_fleet" + ] + }, "UpdateMembership": { "methods": [ "update_membership" ] + }, + "UpdateMembershipBinding": { + "methods": [ + "update_membership_binding" + ] + }, + "UpdateMembershipRBACRoleBinding": { + "methods": [ + "update_membership_rbac_role_binding" + ] + }, + "UpdateScope": { + "methods": [ + "update_scope" + ] + }, + "UpdateScopeNamespace": { + "methods": [ + "update_scope_namespace" + ] + }, + "UpdateScopeRBACRoleBinding": { + "methods": [ + "update_scope_rbac_role_binding" + ] } } }, @@ -75,55 +240,220 @@ "create_feature" ] }, + "CreateFleet": { + "methods": [ + "create_fleet" + ] + }, "CreateMembership": { "methods": [ "create_membership" ] }, + "CreateMembershipBinding": { + "methods": [ + "create_membership_binding" + ] + }, + "CreateMembershipRBACRoleBinding": { + "methods": [ + "create_membership_rbac_role_binding" + ] + }, + "CreateScope": { + "methods": [ + "create_scope" + ] + }, + "CreateScopeNamespace": { + "methods": [ + "create_scope_namespace" + ] + }, + "CreateScopeRBACRoleBinding": { + "methods": [ + "create_scope_rbac_role_binding" + ] + }, "DeleteFeature": { "methods": [ "delete_feature" ] }, + "DeleteFleet": { + "methods": [ + "delete_fleet" + ] + }, "DeleteMembership": { "methods": [ "delete_membership" ] }, + "DeleteMembershipBinding": { + "methods": [ + "delete_membership_binding" + ] + }, + "DeleteMembershipRBACRoleBinding": { + "methods": [ + "delete_membership_rbac_role_binding" + ] + }, + "DeleteScope": { + "methods": [ + "delete_scope" + ] + }, + "DeleteScopeNamespace": { + "methods": [ + "delete_scope_namespace" + ] + }, + "DeleteScopeRBACRoleBinding": { + "methods": [ + "delete_scope_rbac_role_binding" + ] + }, "GenerateConnectManifest": { "methods": [ "generate_connect_manifest" ] }, + "GenerateMembershipRBACRoleBindingYAML": { + "methods": [ + "generate_membership_rbac_role_binding_yaml" + ] + }, "GetFeature": { "methods": [ "get_feature" ] }, + "GetFleet": { + "methods": [ + "get_fleet" + ] + }, "GetMembership": { "methods": [ "get_membership" ] }, + "GetMembershipBinding": { + "methods": [ + "get_membership_binding" + ] + }, + "GetMembershipRBACRoleBinding": { + "methods": [ + "get_membership_rbac_role_binding" + ] + }, + "GetScope": { + "methods": [ + "get_scope" + ] + }, + "GetScopeNamespace": { + "methods": [ + "get_scope_namespace" + ] + }, + "GetScopeRBACRoleBinding": { + "methods": [ + "get_scope_rbac_role_binding" + ] + }, + "ListBoundMemberships": { + "methods": [ + "list_bound_memberships" + ] + }, "ListFeatures": { "methods": [ "list_features" ] }, + "ListFleets": { + "methods": [ + "list_fleets" + ] + }, + "ListMembershipBindings": { + "methods": [ + "list_membership_bindings" + ] + }, + "ListMembershipRBACRoleBindings": { + "methods": [ + "list_membership_rbac_role_bindings" + ] + }, "ListMemberships": { "methods": [ "list_memberships" ] }, + "ListPermittedScopes": { + "methods": [ + "list_permitted_scopes" + ] + }, + "ListScopeNamespaces": { + "methods": [ + "list_scope_namespaces" + ] + }, + "ListScopeRBACRoleBindings": { + "methods": [ + "list_scope_rbac_role_bindings" + ] + }, + "ListScopes": { + "methods": [ + "list_scopes" + ] + }, "UpdateFeature": { "methods": [ "update_feature" ] }, + "UpdateFleet": { + "methods": [ + "update_fleet" + ] + }, "UpdateMembership": { "methods": [ "update_membership" ] + }, + "UpdateMembershipBinding": { + "methods": [ + "update_membership_binding" + ] + }, + "UpdateMembershipRBACRoleBinding": { + "methods": [ + "update_membership_rbac_role_binding" + ] + }, + "UpdateScope": { + "methods": [ + "update_scope" + ] + }, + "UpdateScopeNamespace": { + "methods": [ + "update_scope_namespace" + ] + }, + "UpdateScopeRBACRoleBinding": { + "methods": [ + "update_scope_rbac_role_binding" + ] } } }, @@ -135,55 +465,220 @@ "create_feature" ] }, + "CreateFleet": { + "methods": [ + "create_fleet" + ] + }, "CreateMembership": { "methods": [ "create_membership" ] }, + "CreateMembershipBinding": { + "methods": [ + "create_membership_binding" + ] + }, + "CreateMembershipRBACRoleBinding": { + "methods": [ + "create_membership_rbac_role_binding" + ] + }, + "CreateScope": { + "methods": [ + "create_scope" + ] + }, + "CreateScopeNamespace": { + "methods": [ + "create_scope_namespace" + ] + }, + "CreateScopeRBACRoleBinding": { + "methods": [ + "create_scope_rbac_role_binding" + ] + }, "DeleteFeature": { "methods": [ "delete_feature" ] }, + "DeleteFleet": { + "methods": [ + "delete_fleet" + ] + }, "DeleteMembership": { "methods": [ "delete_membership" ] }, + "DeleteMembershipBinding": { + "methods": [ + "delete_membership_binding" + ] + }, + "DeleteMembershipRBACRoleBinding": { + "methods": [ + "delete_membership_rbac_role_binding" + ] + }, + "DeleteScope": { + "methods": [ + "delete_scope" + ] + }, + "DeleteScopeNamespace": { + "methods": [ + "delete_scope_namespace" + ] + }, + "DeleteScopeRBACRoleBinding": { + "methods": [ + "delete_scope_rbac_role_binding" + ] + }, "GenerateConnectManifest": { "methods": [ "generate_connect_manifest" ] }, + "GenerateMembershipRBACRoleBindingYAML": { + "methods": [ + "generate_membership_rbac_role_binding_yaml" + ] + }, "GetFeature": { "methods": [ "get_feature" ] }, + "GetFleet": { + "methods": [ + "get_fleet" + ] + }, "GetMembership": { "methods": [ "get_membership" ] }, + "GetMembershipBinding": { + "methods": [ + "get_membership_binding" + ] + }, + "GetMembershipRBACRoleBinding": { + "methods": [ + "get_membership_rbac_role_binding" + ] + }, + "GetScope": { + "methods": [ + "get_scope" + ] + }, + "GetScopeNamespace": { + "methods": [ + "get_scope_namespace" + ] + }, + "GetScopeRBACRoleBinding": { + "methods": [ + "get_scope_rbac_role_binding" + ] + }, + "ListBoundMemberships": { + "methods": [ + "list_bound_memberships" + ] + }, "ListFeatures": { "methods": [ "list_features" ] }, + "ListFleets": { + "methods": [ + "list_fleets" + ] + }, + "ListMembershipBindings": { + "methods": [ + "list_membership_bindings" + ] + }, + "ListMembershipRBACRoleBindings": { + "methods": [ + "list_membership_rbac_role_bindings" + ] + }, "ListMemberships": { "methods": [ "list_memberships" ] }, + "ListPermittedScopes": { + "methods": [ + "list_permitted_scopes" + ] + }, + "ListScopeNamespaces": { + "methods": [ + "list_scope_namespaces" + ] + }, + "ListScopeRBACRoleBindings": { + "methods": [ + "list_scope_rbac_role_bindings" + ] + }, + "ListScopes": { + "methods": [ + "list_scopes" + ] + }, "UpdateFeature": { "methods": [ "update_feature" ] }, + "UpdateFleet": { + "methods": [ + "update_fleet" + ] + }, "UpdateMembership": { "methods": [ "update_membership" ] + }, + "UpdateMembershipBinding": { + "methods": [ + "update_membership_binding" + ] + }, + "UpdateMembershipRBACRoleBinding": { + "methods": [ + "update_membership_rbac_role_binding" + ] + }, + "UpdateScope": { + "methods": [ + "update_scope" + ] + }, + "UpdateScopeNamespace": { + "methods": [ + "update_scope_namespace" + ] + }, + "UpdateScopeRBACRoleBinding": { + "methods": [ + "update_scope_rbac_role_binding" + ] } } } diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/__init__.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/__init__.py new file mode 100644 index 000000000000..56c3dcebafc5 --- /dev/null +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/__init__.py @@ -0,0 +1,131 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.gkehub_v1 import gapic_version as package_version + +import google.api_core as api_core +import sys + +__version__ = package_version.__version__ + +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + + +from .types.rbacrolebindingactuation import FeatureSpec +from .types.rbacrolebindingactuation import FeatureState + +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.gkehub.rbacrolebindingactuation_v1") # type: ignore + api_core.check_dependency_versions("google.cloud.gkehub.rbacrolebindingactuation_v1") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import warnings + import sys + + _py_version_str = sys.version.split()[0] + _package_label = "google.cloud.gkehub.rbacrolebindingactuation_v1" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + (_version_used, _version_used_string) = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + +__all__ = ( + "FeatureSpec", + "FeatureState", +) diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/gapic_metadata.json b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/gapic_metadata.json new file mode 100644 index 000000000000..18c40bc3cf44 --- /dev/null +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/gapic_metadata.json @@ -0,0 +1,7 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.gkehub.rbacrolebindingactuation_v1", + "protoPackage": "google.cloud.gkehub.rbacrolebindingactuation.v1", + "schema": "1.0" +} diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/gapic_version.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/gapic_version.py new file mode 100644 index 000000000000..20a9cd975b02 --- /dev/null +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/py.typed b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/py.typed new file mode 100644 index 000000000000..3ea33242d4f4 --- /dev/null +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-gkehub-rbacrolebindingactuation package uses inline types. diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/services/__init__.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/services/__init__.py new file mode 100644 index 000000000000..cbf94b283c70 --- /dev/null +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/types/__init__.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/types/__init__.py new file mode 100644 index 000000000000..94a20ffc1bcd --- /dev/null +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/types/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .rbacrolebindingactuation import ( + FeatureSpec, + FeatureState, +) + +__all__ = ( + "FeatureSpec", + "FeatureState", +) diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/types/rbacrolebindingactuation.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/types/rbacrolebindingactuation.py new file mode 100644 index 000000000000..aa36a394cc1d --- /dev/null +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/rbacrolebindingactuation_v1/types/rbacrolebindingactuation.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.gkehub.rbacrolebindingactuation.v1", + manifest={ + "FeatureSpec", + "FeatureState", + }, +) + + +class FeatureSpec(proto.Message): + r"""**RBAC RoleBinding Actuation**: The Hub-wide input for the + RBACRoleBindingActuation feature. + + Attributes: + allowed_custom_roles (MutableSequence[str]): + The list of allowed custom roles + (ClusterRoles). If a ClusterRole is not part of + this list, it cannot be used in a Scope + RBACRoleBinding. If a ClusterRole in this list + is in use, it cannot be removed from the list. + """ + + allowed_custom_roles: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class FeatureState(proto.Message): + r"""**RBAC RoleBinding Actuation**: An empty state left as an example + Hub-wide Feature state. + + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/async_client.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/async_client.py index f0cfa9769d2e..05a9de718b2c 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/async_client.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/async_client.py @@ -51,7 +51,10 @@ import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore from google.cloud.gkehub_v1.services.gke_hub import pagers -from google.cloud.gkehub_v1.types import feature, membership, service +from google.cloud.gkehub_v1.types import feature +from google.cloud.gkehub_v1.types import fleet +from google.cloud.gkehub_v1.types import fleet as gcg_fleet +from google.cloud.gkehub_v1.types import membership, service from .client import GkeHubClient from .transports.base import DEFAULT_CLIENT_INFO, GkeHubTransport @@ -98,8 +101,22 @@ class GkeHubAsyncClient: feature_path = staticmethod(GkeHubClient.feature_path) parse_feature_path = staticmethod(GkeHubClient.parse_feature_path) + fleet_path = staticmethod(GkeHubClient.fleet_path) + parse_fleet_path = staticmethod(GkeHubClient.parse_fleet_path) membership_path = staticmethod(GkeHubClient.membership_path) parse_membership_path = staticmethod(GkeHubClient.parse_membership_path) + membership_binding_path = staticmethod(GkeHubClient.membership_binding_path) + parse_membership_binding_path = staticmethod( + GkeHubClient.parse_membership_binding_path + ) + namespace_path = staticmethod(GkeHubClient.namespace_path) + parse_namespace_path = staticmethod(GkeHubClient.parse_namespace_path) + rbac_role_binding_path = staticmethod(GkeHubClient.rbac_role_binding_path) + parse_rbac_role_binding_path = staticmethod( + GkeHubClient.parse_rbac_role_binding_path + ) + scope_path = staticmethod(GkeHubClient.scope_path) + parse_scope_path = staticmethod(GkeHubClient.parse_scope_path) common_billing_account_path = staticmethod(GkeHubClient.common_billing_account_path) parse_common_billing_account_path = staticmethod( GkeHubClient.parse_common_billing_account_path @@ -428,6 +445,136 @@ async def sample_list_memberships(): # Done; return the response. return response + async def list_bound_memberships( + self, + request: Optional[Union[service.ListBoundMembershipsRequest, dict]] = None, + *, + scope_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBoundMembershipsAsyncPager: + r"""Lists Memberships bound to a Scope. The response + includes relevant Memberships from all regions. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_list_bound_memberships(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.ListBoundMembershipsRequest( + scope_name="scope_name_value", + ) + + # Make the request + page_result = client.list_bound_memberships(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.ListBoundMembershipsRequest, dict]]): + The request object. Request to list Memberships bound to + a Scope. + scope_name (:class:`str`): + Required. Name of the Scope, in the format + ``projects/*/locations/global/scopes/*``, to which the + Memberships are bound. + + This corresponds to the ``scope_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.services.gke_hub.pagers.ListBoundMembershipsAsyncPager: + List of Memberships bound to a Scope. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [scope_name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListBoundMembershipsRequest): + request = service.ListBoundMembershipsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope_name is not None: + request.scope_name = scope_name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_bound_memberships + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("scope_name", request.scope_name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListBoundMembershipsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def list_features( self, request: Optional[Union[service.ListFeaturesRequest, dict]] = None, @@ -719,7 +866,7 @@ async def sample_get_feature(): Returns: google.cloud.gkehub_v1.types.Feature: Feature represents the settings and - status of any Hub Feature. + status of any Fleet Feature. """ # Create or coerce a protobuf request object. @@ -1008,7 +1155,7 @@ async def sample_create_feature(): The result type for the operation will be :class:`google.cloud.gkehub_v1.types.Feature` Feature - represents the settings and status of any Hub Feature. + represents the settings and status of any Fleet Feature. """ # Create or coerce a protobuf request object. @@ -1575,7 +1722,7 @@ async def sample_update_feature(): The result type for the operation will be :class:`google.cloud.gkehub_v1.types.Feature` Feature - represents the settings and status of any Hub Feature. + represents the settings and status of any Fleet Feature. """ # Create or coerce a protobuf request object. @@ -1729,6 +1876,4221 @@ async def sample_generate_connect_manifest(): # Done; return the response. return response + async def create_fleet( + self, + request: Optional[Union[service.CreateFleetRequest, dict]] = None, + *, + parent: Optional[str] = None, + fleet: Optional[gcg_fleet.Fleet] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a fleet. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_create_fleet(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.CreateFleetRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_fleet(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.CreateFleetRequest, dict]]): + The request object. Request message for the ``GkeHub.CreateFleet`` method. + parent (:class:`str`): + Required. The parent (project and location) where the + Fleet will be created. Specified in the format + ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + fleet (:class:`google.cloud.gkehub_v1.types.Fleet`): + Required. The fleet to create. + This corresponds to the ``fleet`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.Fleet` Fleet + contains the Fleet-wide metadata and configuration. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, fleet] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateFleetRequest): + request = service.CreateFleetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if fleet is not None: + request.fleet = fleet + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_fleet + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcg_fleet.Fleet, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_fleet( + self, + request: Optional[Union[service.GetFleetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> fleet.Fleet: + r"""Returns the details of a fleet. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_get_fleet(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.GetFleetRequest( + name="name_value", + ) + + # Make the request + response = await client.get_fleet(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.GetFleetRequest, dict]]): + The request object. Request message for the ``GkeHub.GetFleet`` method. + name (:class:`str`): + Required. The Fleet resource name in the format + ``projects/*/locations/*/fleets/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.types.Fleet: + Fleet contains the Fleet-wide + metadata and configuration. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetFleetRequest): + request = service.GetFleetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_fleet + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_fleet( + self, + request: Optional[Union[service.UpdateFleetRequest, dict]] = None, + *, + fleet: Optional[gcg_fleet.Fleet] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a fleet. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_update_fleet(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.UpdateFleetRequest( + ) + + # Make the request + operation = client.update_fleet(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.UpdateFleetRequest, dict]]): + The request object. Request message for the ``GkeHub.UpdateFleet`` method. + fleet (:class:`google.cloud.gkehub_v1.types.Fleet`): + Required. The Fleet to update. + + The ``name`` field of the Fleet object identifies which + fleet will be updated. + + This corresponds to the ``fleet`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The fields to be updated; + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.Fleet` Fleet + contains the Fleet-wide metadata and configuration. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [fleet, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateFleetRequest): + request = service.UpdateFleetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if fleet is not None: + request.fleet = fleet + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_fleet + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("fleet.name", request.fleet.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcg_fleet.Fleet, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_fleet( + self, + request: Optional[Union[service.DeleteFleetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Removes a Fleet. There must be no memberships + remaining in the Fleet. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_delete_fleet(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteFleetRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_fleet(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.DeleteFleetRequest, dict]]): + The request object. Request message for ``GkeHub.DeleteFleet`` method. + name (:class:`str`): + Required. The Fleet resource name in the format + ``projects/*/locations/*/fleets/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DeleteFleetRequest): + request = service.DeleteFleetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_fleet + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_fleets( + self, + request: Optional[Union[service.ListFleetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListFleetsAsyncPager: + r"""Returns all fleets within an organization or a + project that the caller has access to. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_list_fleets(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.ListFleetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_fleets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.ListFleetsRequest, dict]]): + The request object. Request message for the ``GkeHub.ListFleets`` method. + parent (:class:`str`): + Required. The organization or project to list for Fleets + under, in the format ``organizations/*/locations/*`` or + ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.services.gke_hub.pagers.ListFleetsAsyncPager: + Response message for the GkeHub.ListFleetsResponse + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListFleetsRequest): + request = service.ListFleetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_fleets + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListFleetsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_scope_namespace( + self, + request: Optional[Union[service.GetScopeNamespaceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> fleet.Namespace: + r"""Returns the details of a fleet namespace. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_get_scope_namespace(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.GetScopeNamespaceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_scope_namespace(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.GetScopeNamespaceRequest, dict]]): + The request object. Request message for the ``GkeHub.GetNamespace`` method. + name (:class:`str`): + Required. The Namespace resource name in the format + ``projects/*/locations/*/scopes/*/namespaces/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.types.Namespace: + Namespace represents a namespace + across the Fleet + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetScopeNamespaceRequest): + request = service.GetScopeNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_scope_namespace + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_scope_namespace( + self, + request: Optional[Union[service.CreateScopeNamespaceRequest, dict]] = None, + *, + parent: Optional[str] = None, + scope_namespace: Optional[fleet.Namespace] = None, + scope_namespace_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a fleet namespace. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_create_scope_namespace(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + scope_namespace = gkehub_v1.Namespace() + scope_namespace.scope = "scope_value" + + request = gkehub_v1.CreateScopeNamespaceRequest( + parent="parent_value", + scope_namespace_id="scope_namespace_id_value", + scope_namespace=scope_namespace, + ) + + # Make the request + operation = client.create_scope_namespace(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.CreateScopeNamespaceRequest, dict]]): + The request object. Request to create a fleet namespace. + parent (:class:`str`): + Required. The parent (project and location) where the + Namespace will be created. Specified in the format + ``projects/*/locations/*/scopes/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scope_namespace (:class:`google.cloud.gkehub_v1.types.Namespace`): + Required. The fleet namespace to + create. + + This corresponds to the ``scope_namespace`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scope_namespace_id (:class:`str`): + Required. Client chosen ID for the Namespace. + ``namespace_id`` must be a valid RFC 1123 compliant DNS + label: + + 1. At most 63 characters in length + 2. It must consist of lower case alphanumeric characters + or ``-`` + 3. It must start and end with an alphanumeric character + + Which can be expressed as the regex: + ``[a-z0-9]([-a-z0-9]*[a-z0-9])?``, with a maximum length + of 63 characters. + + This corresponds to the ``scope_namespace_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.Namespace` + Namespace represents a namespace across the Fleet + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, scope_namespace, scope_namespace_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateScopeNamespaceRequest): + request = service.CreateScopeNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if scope_namespace is not None: + request.scope_namespace = scope_namespace + if scope_namespace_id is not None: + request.scope_namespace_id = scope_namespace_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_scope_namespace + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + fleet.Namespace, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_scope_namespace( + self, + request: Optional[Union[service.UpdateScopeNamespaceRequest, dict]] = None, + *, + scope_namespace: Optional[fleet.Namespace] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a fleet namespace. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_update_scope_namespace(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + scope_namespace = gkehub_v1.Namespace() + scope_namespace.scope = "scope_value" + + request = gkehub_v1.UpdateScopeNamespaceRequest( + scope_namespace=scope_namespace, + ) + + # Make the request + operation = client.update_scope_namespace(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.UpdateScopeNamespaceRequest, dict]]): + The request object. Request to update a fleet namespace. + scope_namespace (:class:`google.cloud.gkehub_v1.types.Namespace`): + Required. A namespace with fields updated. The 'name' + field in this namespace is used to identify the resource + to update. Given 'updated' prefix to follow + go/proto-best-practices-checkers#keyword_conflict + + This corresponds to the ``scope_namespace`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.Namespace` + Namespace represents a namespace across the Fleet + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [scope_namespace, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateScopeNamespaceRequest): + request = service.UpdateScopeNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope_namespace is not None: + request.scope_namespace = scope_namespace + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_scope_namespace + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("scope_namespace.name", request.scope_namespace.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + fleet.Namespace, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_scope_namespace( + self, + request: Optional[Union[service.DeleteScopeNamespaceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a fleet namespace. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_delete_scope_namespace(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteScopeNamespaceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_scope_namespace(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.DeleteScopeNamespaceRequest, dict]]): + The request object. Request to delete a fleet namespace. + name (:class:`str`): + Required. The Namespace resource name in the format + ``projects/*/locations/*/scopes/*/namespaces/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DeleteScopeNamespaceRequest): + request = service.DeleteScopeNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_scope_namespace + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_scope_namespaces( + self, + request: Optional[Union[service.ListScopeNamespacesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListScopeNamespacesAsyncPager: + r"""Lists fleet namespaces. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_list_scope_namespaces(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.ListScopeNamespacesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scope_namespaces(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.ListScopeNamespacesRequest, dict]]): + The request object. Request to list fleet namespaces. + parent (:class:`str`): + Required. The parent (project and location) where the + Features will be listed. Specified in the format + ``projects/*/locations/*/scopes/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.services.gke_hub.pagers.ListScopeNamespacesAsyncPager: + List of fleet namespaces. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListScopeNamespacesRequest): + request = service.ListScopeNamespacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_scope_namespaces + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListScopeNamespacesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_scope_rbac_role_binding( + self, + request: Optional[Union[service.GetScopeRBACRoleBindingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> fleet.RBACRoleBinding: + r"""Returns the details of a Scope RBACRoleBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_get_scope_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.GetScopeRBACRoleBindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_scope_rbac_role_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.GetScopeRBACRoleBindingRequest, dict]]): + The request object. Request message for the + ``GkeHub.GetScopeRBACRoleBinding`` method. + name (:class:`str`): + Required. The RBACRoleBinding resource name in the + format + ``projects/*/locations/*/scopes/*/rbacrolebindings/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.types.RBACRoleBinding: + RBACRoleBinding represents a + rbacrolebinding across the Fleet + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetScopeRBACRoleBindingRequest): + request = service.GetScopeRBACRoleBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_scope_rbac_role_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_scope_rbac_role_binding( + self, + request: Optional[ + Union[service.CreateScopeRBACRoleBindingRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + rbacrolebinding: Optional[fleet.RBACRoleBinding] = None, + rbacrolebinding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a Scope RBACRoleBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_create_scope_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + rbacrolebinding = gkehub_v1.RBACRoleBinding() + rbacrolebinding.user = "user_value" + + request = gkehub_v1.CreateScopeRBACRoleBindingRequest( + parent="parent_value", + rbacrolebinding_id="rbacrolebinding_id_value", + rbacrolebinding=rbacrolebinding, + ) + + # Make the request + operation = client.create_scope_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.CreateScopeRBACRoleBindingRequest, dict]]): + The request object. Request to create a rbacrolebindings. + parent (:class:`str`): + Required. The parent (project and location) where the + RBACRoleBinding will be created. Specified in the format + ``projects/*/locations/*/scopes/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rbacrolebinding (:class:`google.cloud.gkehub_v1.types.RBACRoleBinding`): + Required. The rbacrolebindings to + create. + + This corresponds to the ``rbacrolebinding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rbacrolebinding_id (:class:`str`): + Required. Client chosen ID for the RBACRoleBinding. + ``rbacrolebinding_id`` must be a valid RFC 1123 + compliant DNS label: + + 1. At most 63 characters in length + 2. It must consist of lower case alphanumeric characters + or ``-`` + 3. It must start and end with an alphanumeric character + + Which can be expressed as the regex: + ``[a-z0-9]([-a-z0-9]*[a-z0-9])?``, with a maximum length + of 63 characters. + + This corresponds to the ``rbacrolebinding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.RBACRoleBinding` + RBACRoleBinding represents a rbacrolebinding across the + Fleet + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, rbacrolebinding, rbacrolebinding_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateScopeRBACRoleBindingRequest): + request = service.CreateScopeRBACRoleBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if rbacrolebinding is not None: + request.rbacrolebinding = rbacrolebinding + if rbacrolebinding_id is not None: + request.rbacrolebinding_id = rbacrolebinding_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_scope_rbac_role_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + fleet.RBACRoleBinding, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_scope_rbac_role_binding( + self, + request: Optional[ + Union[service.UpdateScopeRBACRoleBindingRequest, dict] + ] = None, + *, + rbacrolebinding: Optional[fleet.RBACRoleBinding] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a Scope RBACRoleBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_update_scope_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + rbacrolebinding = gkehub_v1.RBACRoleBinding() + rbacrolebinding.user = "user_value" + + request = gkehub_v1.UpdateScopeRBACRoleBindingRequest( + rbacrolebinding=rbacrolebinding, + ) + + # Make the request + operation = client.update_scope_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.UpdateScopeRBACRoleBindingRequest, dict]]): + The request object. Request to update a scope + rbacrolebinding. + rbacrolebinding (:class:`google.cloud.gkehub_v1.types.RBACRoleBinding`): + Required. A rbacrolebinding with + fields updated. The 'name' field in this + rbacrolebinding is used to identify the + resource to update. + + This corresponds to the ``rbacrolebinding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.RBACRoleBinding` + RBACRoleBinding represents a rbacrolebinding across the + Fleet + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [rbacrolebinding, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateScopeRBACRoleBindingRequest): + request = service.UpdateScopeRBACRoleBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if rbacrolebinding is not None: + request.rbacrolebinding = rbacrolebinding + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_scope_rbac_role_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("rbacrolebinding.name", request.rbacrolebinding.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + fleet.RBACRoleBinding, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_scope_rbac_role_binding( + self, + request: Optional[ + Union[service.DeleteScopeRBACRoleBindingRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a Scope RBACRoleBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_delete_scope_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteScopeRBACRoleBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_scope_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.DeleteScopeRBACRoleBindingRequest, dict]]): + The request object. Request to delete a Scope + RBACRoleBinding. + name (:class:`str`): + Required. The RBACRoleBinding resource name in the + format + ``projects/*/locations/*/scopes/*/rbacrolebindings/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DeleteScopeRBACRoleBindingRequest): + request = service.DeleteScopeRBACRoleBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_scope_rbac_role_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_scope_rbac_role_bindings( + self, + request: Optional[Union[service.ListScopeRBACRoleBindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListScopeRBACRoleBindingsAsyncPager: + r"""Lists all Scope RBACRoleBindings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_list_scope_rbac_role_bindings(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.ListScopeRBACRoleBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scope_rbac_role_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.ListScopeRBACRoleBindingsRequest, dict]]): + The request object. Request to list Scope + RBACRoleBindings. + parent (:class:`str`): + Required. The parent (project and location) where the + Features will be listed. Specified in the format + ``projects/*/locations/*/scopes/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.services.gke_hub.pagers.ListScopeRBACRoleBindingsAsyncPager: + List of Scope RBACRoleBindings. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListScopeRBACRoleBindingsRequest): + request = service.ListScopeRBACRoleBindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_scope_rbac_role_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListScopeRBACRoleBindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_scope( + self, + request: Optional[Union[service.GetScopeRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> fleet.Scope: + r"""Returns the details of a Scope. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_get_scope(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.GetScopeRequest( + name="name_value", + ) + + # Make the request + response = await client.get_scope(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.GetScopeRequest, dict]]): + The request object. Request message for the ``GkeHub.GetScope`` method. + name (:class:`str`): + Required. The Scope resource name in the format + ``projects/*/locations/*/scopes/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.types.Scope: + Scope represents a Scope in a Fleet. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetScopeRequest): + request = service.GetScopeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_scope + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_scope( + self, + request: Optional[Union[service.CreateScopeRequest, dict]] = None, + *, + parent: Optional[str] = None, + scope: Optional[fleet.Scope] = None, + scope_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a Scope. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_create_scope(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.CreateScopeRequest( + parent="parent_value", + scope_id="scope_id_value", + ) + + # Make the request + operation = client.create_scope(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.CreateScopeRequest, dict]]): + The request object. Request to create a Scope. + parent (:class:`str`): + Required. The parent (project and location) where the + Scope will be created. Specified in the format + ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scope (:class:`google.cloud.gkehub_v1.types.Scope`): + Required. The Scope to create. + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scope_id (:class:`str`): + Required. Client chosen ID for the Scope. ``scope_id`` + must be a ???? + + This corresponds to the ``scope_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.Scope` Scope + represents a Scope in a Fleet. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, scope, scope_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateScopeRequest): + request = service.CreateScopeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if scope is not None: + request.scope = scope + if scope_id is not None: + request.scope_id = scope_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_scope + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + fleet.Scope, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_scope( + self, + request: Optional[Union[service.UpdateScopeRequest, dict]] = None, + *, + scope: Optional[fleet.Scope] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a scopes. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_update_scope(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.UpdateScopeRequest( + ) + + # Make the request + operation = client.update_scope(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.UpdateScopeRequest, dict]]): + The request object. Request to update a Scope. + scope (:class:`google.cloud.gkehub_v1.types.Scope`): + Required. A Scope with fields + updated. The 'name' field in this + namespace is used to identify the + resource to update. + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.Scope` Scope + represents a Scope in a Fleet. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [scope, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateScopeRequest): + request = service.UpdateScopeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope is not None: + request.scope = scope + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_scope + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("scope.name", request.scope.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + fleet.Scope, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_scope( + self, + request: Optional[Union[service.DeleteScopeRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a Scope. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_delete_scope(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteScopeRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_scope(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.DeleteScopeRequest, dict]]): + The request object. Request to delete a Scope. + name (:class:`str`): + Required. The Scope resource name in the format + ``projects/*/locations/*/scopes/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DeleteScopeRequest): + request = service.DeleteScopeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_scope + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_scopes( + self, + request: Optional[Union[service.ListScopesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListScopesAsyncPager: + r"""Lists Scopes. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_list_scopes(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.ListScopesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scopes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.ListScopesRequest, dict]]): + The request object. Request to list Scopes. + parent (:class:`str`): + Required. The parent (project and location) where the + Scope will be listed. Specified in the format + ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.services.gke_hub.pagers.ListScopesAsyncPager: + List of Scopes. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListScopesRequest): + request = service.ListScopesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_scopes + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListScopesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_permitted_scopes( + self, + request: Optional[Union[service.ListPermittedScopesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPermittedScopesAsyncPager: + r"""Lists permitted Scopes. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_list_permitted_scopes(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.ListPermittedScopesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_permitted_scopes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.ListPermittedScopesRequest, dict]]): + The request object. Request to list permitted Scopes. + parent (:class:`str`): + Required. The parent (project and location) where the + Scope will be listed. Specified in the format + ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.services.gke_hub.pagers.ListPermittedScopesAsyncPager: + List of permitted Scopes. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListPermittedScopesRequest): + request = service.ListPermittedScopesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_permitted_scopes + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListPermittedScopesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_membership_binding( + self, + request: Optional[Union[service.GetMembershipBindingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> fleet.MembershipBinding: + r"""Returns the details of a MembershipBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_get_membership_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.GetMembershipBindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_membership_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.GetMembershipBindingRequest, dict]]): + The request object. Request message for the ``GkeHub.GetMembershipBinding`` + method. + name (:class:`str`): + Required. The MembershipBinding resource name in the + format + ``projects/*/locations/*/memberships/*/bindings/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.types.MembershipBinding: + MembershipBinding is a subresource of + a Membership, representing what Fleet + Scopes (or other, future Fleet + resources) a Membership is bound to. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetMembershipBindingRequest): + request = service.GetMembershipBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_membership_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_membership_binding( + self, + request: Optional[Union[service.CreateMembershipBindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + membership_binding: Optional[fleet.MembershipBinding] = None, + membership_binding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a MembershipBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_create_membership_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + membership_binding = gkehub_v1.MembershipBinding() + membership_binding.scope = "scope_value" + + request = gkehub_v1.CreateMembershipBindingRequest( + parent="parent_value", + membership_binding=membership_binding, + membership_binding_id="membership_binding_id_value", + ) + + # Make the request + operation = client.create_membership_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.CreateMembershipBindingRequest, dict]]): + The request object. Request to create a + MembershipBinding. + parent (:class:`str`): + Required. The parent (project and location) where the + MembershipBinding will be created. Specified in the + format ``projects/*/locations/*/memberships/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + membership_binding (:class:`google.cloud.gkehub_v1.types.MembershipBinding`): + Required. The MembershipBinding to + create. + + This corresponds to the ``membership_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + membership_binding_id (:class:`str`): + Required. The ID to use for the + MembershipBinding. + + This corresponds to the ``membership_binding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.gkehub_v1.types.MembershipBinding` MembershipBinding is a subresource of a Membership, representing + what Fleet Scopes (or other, future Fleet resources) + a Membership is bound to. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, membership_binding, membership_binding_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateMembershipBindingRequest): + request = service.CreateMembershipBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if membership_binding is not None: + request.membership_binding = membership_binding + if membership_binding_id is not None: + request.membership_binding_id = membership_binding_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_membership_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + fleet.MembershipBinding, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_membership_binding( + self, + request: Optional[Union[service.UpdateMembershipBindingRequest, dict]] = None, + *, + membership_binding: Optional[fleet.MembershipBinding] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a MembershipBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_update_membership_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + membership_binding = gkehub_v1.MembershipBinding() + membership_binding.scope = "scope_value" + + request = gkehub_v1.UpdateMembershipBindingRequest( + membership_binding=membership_binding, + ) + + # Make the request + operation = client.update_membership_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.UpdateMembershipBindingRequest, dict]]): + The request object. Request to update a + MembershipBinding. + membership_binding (:class:`google.cloud.gkehub_v1.types.MembershipBinding`): + Required. The MembershipBinding + object with fields updated. + + This corresponds to the ``membership_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.gkehub_v1.types.MembershipBinding` MembershipBinding is a subresource of a Membership, representing + what Fleet Scopes (or other, future Fleet resources) + a Membership is bound to. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [membership_binding, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateMembershipBindingRequest): + request = service.UpdateMembershipBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if membership_binding is not None: + request.membership_binding = membership_binding + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_membership_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("membership_binding.name", request.membership_binding.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + fleet.MembershipBinding, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_membership_binding( + self, + request: Optional[Union[service.DeleteMembershipBindingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a MembershipBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_delete_membership_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteMembershipBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_membership_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.DeleteMembershipBindingRequest, dict]]): + The request object. Request to delete a Binding. + name (:class:`str`): + Required. The MembershipBinding resource name in the + format + ``projects/*/locations/*/memberships/*/bindings/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DeleteMembershipBindingRequest): + request = service.DeleteMembershipBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_membership_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_membership_bindings( + self, + request: Optional[Union[service.ListMembershipBindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMembershipBindingsAsyncPager: + r"""Lists MembershipBindings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_list_membership_bindings(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.ListMembershipBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_membership_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.ListMembershipBindingsRequest, dict]]): + The request object. Request to list MembershipBinding. + parent (:class:`str`): + Required. The parent Membership for which the + MembershipBindings will be listed. Specified in the + format ``projects/*/locations/*/memberships/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.services.gke_hub.pagers.ListMembershipBindingsAsyncPager: + List of MembershipBindings. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListMembershipBindingsRequest): + request = service.ListMembershipBindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_membership_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListMembershipBindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_membership_rbac_role_binding( + self, + request: Optional[ + Union[service.GetMembershipRBACRoleBindingRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> fleet.RBACRoleBinding: + r"""Returns the details of a Membership RBACRoleBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_get_membership_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.GetMembershipRBACRoleBindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_membership_rbac_role_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.GetMembershipRBACRoleBindingRequest, dict]]): + The request object. Request message for the + ``GkeHub.GetMembershipRBACRoleBinding`` method. + name (:class:`str`): + Required. The RBACRoleBinding resource name in the + format + ``projects/*/locations/*/memberships/*/rbacrolebindings/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.types.RBACRoleBinding: + RBACRoleBinding represents a + rbacrolebinding across the Fleet + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetMembershipRBACRoleBindingRequest): + request = service.GetMembershipRBACRoleBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_membership_rbac_role_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_membership_rbac_role_binding( + self, + request: Optional[ + Union[service.CreateMembershipRBACRoleBindingRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + rbacrolebinding: Optional[fleet.RBACRoleBinding] = None, + rbacrolebinding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a Membership RBACRoleBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_create_membership_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + rbacrolebinding = gkehub_v1.RBACRoleBinding() + rbacrolebinding.user = "user_value" + + request = gkehub_v1.CreateMembershipRBACRoleBindingRequest( + parent="parent_value", + rbacrolebinding_id="rbacrolebinding_id_value", + rbacrolebinding=rbacrolebinding, + ) + + # Make the request + operation = client.create_membership_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.CreateMembershipRBACRoleBindingRequest, dict]]): + The request object. Request to create a rbacrolebindings. + parent (:class:`str`): + Required. The parent (project and location) where the + RBACRoleBinding will be created. Specified in the format + ``projects/*/locations/*/memberships/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rbacrolebinding (:class:`google.cloud.gkehub_v1.types.RBACRoleBinding`): + Required. The rbacrolebindings to + create. + + This corresponds to the ``rbacrolebinding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rbacrolebinding_id (:class:`str`): + Required. Client chosen ID for the RBACRoleBinding. + ``rbacrolebinding_id`` must be a valid RFC 1123 + compliant DNS label: + + 1. At most 63 characters in length + 2. It must consist of lower case alphanumeric characters + or ``-`` + 3. It must start and end with an alphanumeric character + + Which can be expressed as the regex: + ``[a-z0-9]([-a-z0-9]*[a-z0-9])?``, with a maximum length + of 63 characters. + + This corresponds to the ``rbacrolebinding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.RBACRoleBinding` + RBACRoleBinding represents a rbacrolebinding across the + Fleet + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, rbacrolebinding, rbacrolebinding_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateMembershipRBACRoleBindingRequest): + request = service.CreateMembershipRBACRoleBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if rbacrolebinding is not None: + request.rbacrolebinding = rbacrolebinding + if rbacrolebinding_id is not None: + request.rbacrolebinding_id = rbacrolebinding_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_membership_rbac_role_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + fleet.RBACRoleBinding, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_membership_rbac_role_binding( + self, + request: Optional[ + Union[service.UpdateMembershipRBACRoleBindingRequest, dict] + ] = None, + *, + rbacrolebinding: Optional[fleet.RBACRoleBinding] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a Membership RBACRoleBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_update_membership_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + rbacrolebinding = gkehub_v1.RBACRoleBinding() + rbacrolebinding.user = "user_value" + + request = gkehub_v1.UpdateMembershipRBACRoleBindingRequest( + rbacrolebinding=rbacrolebinding, + ) + + # Make the request + operation = client.update_membership_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.UpdateMembershipRBACRoleBindingRequest, dict]]): + The request object. Request to update a membership + rbacrolebinding. + rbacrolebinding (:class:`google.cloud.gkehub_v1.types.RBACRoleBinding`): + Required. A rbacrolebinding with + fields updated. The 'name' field in this + rbacrolebinding is used to identify the + resource to update. + + This corresponds to the ``rbacrolebinding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.RBACRoleBinding` + RBACRoleBinding represents a rbacrolebinding across the + Fleet + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [rbacrolebinding, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateMembershipRBACRoleBindingRequest): + request = service.UpdateMembershipRBACRoleBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if rbacrolebinding is not None: + request.rbacrolebinding = rbacrolebinding + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_membership_rbac_role_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("rbacrolebinding.name", request.rbacrolebinding.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + fleet.RBACRoleBinding, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_membership_rbac_role_binding( + self, + request: Optional[ + Union[service.DeleteMembershipRBACRoleBindingRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a Membership RBACRoleBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_delete_membership_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteMembershipRBACRoleBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_membership_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.DeleteMembershipRBACRoleBindingRequest, dict]]): + The request object. Request to delete a Membership + RBACRoleBinding. + name (:class:`str`): + Required. The RBACRoleBinding resource name in the + format + ``projects/*/locations/*/memberships/*/rbacrolebindings/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DeleteMembershipRBACRoleBindingRequest): + request = service.DeleteMembershipRBACRoleBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_membership_rbac_role_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_membership_rbac_role_bindings( + self, + request: Optional[ + Union[service.ListMembershipRBACRoleBindingsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMembershipRBACRoleBindingsAsyncPager: + r"""Lists all Membership RBACRoleBindings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_list_membership_rbac_role_bindings(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.ListMembershipRBACRoleBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_membership_rbac_role_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.ListMembershipRBACRoleBindingsRequest, dict]]): + The request object. Request to list Membership + RBACRoleBindings. + parent (:class:`str`): + Required. The parent (project and location) where the + Features will be listed. Specified in the format + ``projects/*/locations/*/memberships/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.services.gke_hub.pagers.ListMembershipRBACRoleBindingsAsyncPager: + List of Membership RBACRoleBindings. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListMembershipRBACRoleBindingsRequest): + request = service.ListMembershipRBACRoleBindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_membership_rbac_role_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListMembershipRBACRoleBindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_membership_rbac_role_binding_yaml( + self, + request: Optional[ + Union[service.GenerateMembershipRBACRoleBindingYAMLRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.GenerateMembershipRBACRoleBindingYAMLResponse: + r"""Generates a YAML of the RBAC policies for the + specified RoleBinding and its associated impersonation + resources. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + async def sample_generate_membership_rbac_role_binding_yaml(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + rbacrolebinding = gkehub_v1.RBACRoleBinding() + rbacrolebinding.user = "user_value" + + request = gkehub_v1.GenerateMembershipRBACRoleBindingYAMLRequest( + parent="parent_value", + rbacrolebinding_id="rbacrolebinding_id_value", + rbacrolebinding=rbacrolebinding, + ) + + # Make the request + response = await client.generate_membership_rbac_role_binding_yaml(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.gkehub_v1.types.GenerateMembershipRBACRoleBindingYAMLRequest, dict]]): + The request object. Request to generate a YAML of the + RBAC policies for the specified + RoleBinding and its associated + impersonation resources. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.types.GenerateMembershipRBACRoleBindingYAMLResponse: + Response for + GenerateRBACRoleBindingYAML. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, service.GenerateMembershipRBACRoleBindingYAMLRequest + ): + request = service.GenerateMembershipRBACRoleBindingYAMLRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.generate_membership_rbac_role_binding_yaml + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def __aenter__(self) -> "GkeHubAsyncClient": return self diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/client.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/client.py index 6d1f1cf9cb82..003bad01ad05 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/client.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/client.py @@ -68,7 +68,10 @@ import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore from google.cloud.gkehub_v1.services.gke_hub import pagers -from google.cloud.gkehub_v1.types import feature, membership, service +from google.cloud.gkehub_v1.types import feature +from google.cloud.gkehub_v1.types import fleet +from google.cloud.gkehub_v1.types import fleet as gcg_fleet +from google.cloud.gkehub_v1.types import membership, service from .transports.base import DEFAULT_CLIENT_INFO, GkeHubTransport from .transports.grpc import GkeHubGrpcTransport @@ -267,6 +270,28 @@ def parse_feature_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def fleet_path( + project: str, + location: str, + fleet: str, + ) -> str: + """Returns a fully-qualified fleet string.""" + return "projects/{project}/locations/{location}/fleets/{fleet}".format( + project=project, + location=location, + fleet=fleet, + ) + + @staticmethod + def parse_fleet_path(path: str) -> Dict[str, str]: + """Parses a fleet path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/fleets/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def membership_path( project: str, @@ -291,6 +316,100 @@ def parse_membership_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def membership_binding_path( + project: str, + location: str, + membership: str, + membershipbinding: str, + ) -> str: + """Returns a fully-qualified membership_binding string.""" + return "projects/{project}/locations/{location}/memberships/{membership}/bindings/{membershipbinding}".format( + project=project, + location=location, + membership=membership, + membershipbinding=membershipbinding, + ) + + @staticmethod + def parse_membership_binding_path(path: str) -> Dict[str, str]: + """Parses a membership_binding path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/memberships/(?P.+?)/bindings/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def namespace_path( + project: str, + location: str, + scope: str, + namespace: str, + ) -> str: + """Returns a fully-qualified namespace string.""" + return "projects/{project}/locations/{location}/scopes/{scope}/namespaces/{namespace}".format( + project=project, + location=location, + scope=scope, + namespace=namespace, + ) + + @staticmethod + def parse_namespace_path(path: str) -> Dict[str, str]: + """Parses a namespace path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/scopes/(?P.+?)/namespaces/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def rbac_role_binding_path( + project: str, + location: str, + scope: str, + rbacrolebinding: str, + ) -> str: + """Returns a fully-qualified rbac_role_binding string.""" + return "projects/{project}/locations/{location}/scopes/{scope}/rbacrolebindings/{rbacrolebinding}".format( + project=project, + location=location, + scope=scope, + rbacrolebinding=rbacrolebinding, + ) + + @staticmethod + def parse_rbac_role_binding_path(path: str) -> Dict[str, str]: + """Parses a rbac_role_binding path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/scopes/(?P.+?)/rbacrolebindings/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def scope_path( + project: str, + location: str, + scope: str, + ) -> str: + """Returns a fully-qualified scope string.""" + return "projects/{project}/locations/{location}/scopes/{scope}".format( + project=project, + location=location, + scope=scope, + ) + + @staticmethod + def parse_scope_path(path: str) -> Dict[str, str]: + """Parses a scope path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/scopes/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path( billing_account: str, @@ -893,6 +1012,133 @@ def sample_list_memberships(): # Done; return the response. return response + def list_bound_memberships( + self, + request: Optional[Union[service.ListBoundMembershipsRequest, dict]] = None, + *, + scope_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListBoundMembershipsPager: + r"""Lists Memberships bound to a Scope. The response + includes relevant Memberships from all regions. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_list_bound_memberships(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.ListBoundMembershipsRequest( + scope_name="scope_name_value", + ) + + # Make the request + page_result = client.list_bound_memberships(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.ListBoundMembershipsRequest, dict]): + The request object. Request to list Memberships bound to + a Scope. + scope_name (str): + Required. Name of the Scope, in the format + ``projects/*/locations/global/scopes/*``, to which the + Memberships are bound. + + This corresponds to the ``scope_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.services.gke_hub.pagers.ListBoundMembershipsPager: + List of Memberships bound to a Scope. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [scope_name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListBoundMembershipsRequest): + request = service.ListBoundMembershipsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope_name is not None: + request.scope_name = scope_name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_bound_memberships] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("scope_name", request.scope_name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListBoundMembershipsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def list_features( self, request: Optional[Union[service.ListFeaturesRequest, dict]] = None, @@ -1178,7 +1424,7 @@ def sample_get_feature(): Returns: google.cloud.gkehub_v1.types.Feature: Feature represents the settings and - status of any Hub Feature. + status of any Fleet Feature. """ # Create or coerce a protobuf request object. @@ -1461,7 +1707,7 @@ def sample_create_feature(): The result type for the operation will be :class:`google.cloud.gkehub_v1.types.Feature` Feature - represents the settings and status of any Hub Feature. + represents the settings and status of any Fleet Feature. """ # Create or coerce a protobuf request object. @@ -2016,7 +2262,7 @@ def sample_update_feature(): The result type for the operation will be :class:`google.cloud.gkehub_v1.types.Feature` Feature - represents the settings and status of any Hub Feature. + represents the settings and status of any Fleet Feature. """ # Create or coerce a protobuf request object. @@ -2167,6 +2413,4154 @@ def sample_generate_connect_manifest(): # Done; return the response. return response + def create_fleet( + self, + request: Optional[Union[service.CreateFleetRequest, dict]] = None, + *, + parent: Optional[str] = None, + fleet: Optional[gcg_fleet.Fleet] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a fleet. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_create_fleet(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.CreateFleetRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_fleet(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.CreateFleetRequest, dict]): + The request object. Request message for the ``GkeHub.CreateFleet`` method. + parent (str): + Required. The parent (project and location) where the + Fleet will be created. Specified in the format + ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + fleet (google.cloud.gkehub_v1.types.Fleet): + Required. The fleet to create. + This corresponds to the ``fleet`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.Fleet` Fleet + contains the Fleet-wide metadata and configuration. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, fleet] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateFleetRequest): + request = service.CreateFleetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if fleet is not None: + request.fleet = fleet + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_fleet] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcg_fleet.Fleet, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_fleet( + self, + request: Optional[Union[service.GetFleetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> fleet.Fleet: + r"""Returns the details of a fleet. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_get_fleet(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.GetFleetRequest( + name="name_value", + ) + + # Make the request + response = client.get_fleet(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.GetFleetRequest, dict]): + The request object. Request message for the ``GkeHub.GetFleet`` method. + name (str): + Required. The Fleet resource name in the format + ``projects/*/locations/*/fleets/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.types.Fleet: + Fleet contains the Fleet-wide + metadata and configuration. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetFleetRequest): + request = service.GetFleetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_fleet] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_fleet( + self, + request: Optional[Union[service.UpdateFleetRequest, dict]] = None, + *, + fleet: Optional[gcg_fleet.Fleet] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates a fleet. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_update_fleet(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.UpdateFleetRequest( + ) + + # Make the request + operation = client.update_fleet(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.UpdateFleetRequest, dict]): + The request object. Request message for the ``GkeHub.UpdateFleet`` method. + fleet (google.cloud.gkehub_v1.types.Fleet): + Required. The Fleet to update. + + The ``name`` field of the Fleet object identifies which + fleet will be updated. + + This corresponds to the ``fleet`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The fields to be updated; + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.Fleet` Fleet + contains the Fleet-wide metadata and configuration. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [fleet, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateFleetRequest): + request = service.UpdateFleetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if fleet is not None: + request.fleet = fleet + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_fleet] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("fleet.name", request.fleet.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcg_fleet.Fleet, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_fleet( + self, + request: Optional[Union[service.DeleteFleetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Removes a Fleet. There must be no memberships + remaining in the Fleet. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_delete_fleet(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteFleetRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_fleet(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.DeleteFleetRequest, dict]): + The request object. Request message for ``GkeHub.DeleteFleet`` method. + name (str): + Required. The Fleet resource name in the format + ``projects/*/locations/*/fleets/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DeleteFleetRequest): + request = service.DeleteFleetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_fleet] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_fleets( + self, + request: Optional[Union[service.ListFleetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListFleetsPager: + r"""Returns all fleets within an organization or a + project that the caller has access to. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_list_fleets(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.ListFleetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_fleets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.ListFleetsRequest, dict]): + The request object. Request message for the ``GkeHub.ListFleets`` method. + parent (str): + Required. The organization or project to list for Fleets + under, in the format ``organizations/*/locations/*`` or + ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.services.gke_hub.pagers.ListFleetsPager: + Response message for the GkeHub.ListFleetsResponse + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListFleetsRequest): + request = service.ListFleetsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_fleets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListFleetsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_scope_namespace( + self, + request: Optional[Union[service.GetScopeNamespaceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> fleet.Namespace: + r"""Returns the details of a fleet namespace. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_get_scope_namespace(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.GetScopeNamespaceRequest( + name="name_value", + ) + + # Make the request + response = client.get_scope_namespace(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.GetScopeNamespaceRequest, dict]): + The request object. Request message for the ``GkeHub.GetNamespace`` method. + name (str): + Required. The Namespace resource name in the format + ``projects/*/locations/*/scopes/*/namespaces/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.types.Namespace: + Namespace represents a namespace + across the Fleet + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetScopeNamespaceRequest): + request = service.GetScopeNamespaceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_scope_namespace] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_scope_namespace( + self, + request: Optional[Union[service.CreateScopeNamespaceRequest, dict]] = None, + *, + parent: Optional[str] = None, + scope_namespace: Optional[fleet.Namespace] = None, + scope_namespace_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a fleet namespace. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_create_scope_namespace(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + scope_namespace = gkehub_v1.Namespace() + scope_namespace.scope = "scope_value" + + request = gkehub_v1.CreateScopeNamespaceRequest( + parent="parent_value", + scope_namespace_id="scope_namespace_id_value", + scope_namespace=scope_namespace, + ) + + # Make the request + operation = client.create_scope_namespace(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.CreateScopeNamespaceRequest, dict]): + The request object. Request to create a fleet namespace. + parent (str): + Required. The parent (project and location) where the + Namespace will be created. Specified in the format + ``projects/*/locations/*/scopes/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scope_namespace (google.cloud.gkehub_v1.types.Namespace): + Required. The fleet namespace to + create. + + This corresponds to the ``scope_namespace`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scope_namespace_id (str): + Required. Client chosen ID for the Namespace. + ``namespace_id`` must be a valid RFC 1123 compliant DNS + label: + + 1. At most 63 characters in length + 2. It must consist of lower case alphanumeric characters + or ``-`` + 3. It must start and end with an alphanumeric character + + Which can be expressed as the regex: + ``[a-z0-9]([-a-z0-9]*[a-z0-9])?``, with a maximum length + of 63 characters. + + This corresponds to the ``scope_namespace_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.Namespace` + Namespace represents a namespace across the Fleet + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, scope_namespace, scope_namespace_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateScopeNamespaceRequest): + request = service.CreateScopeNamespaceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if scope_namespace is not None: + request.scope_namespace = scope_namespace + if scope_namespace_id is not None: + request.scope_namespace_id = scope_namespace_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_scope_namespace] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + fleet.Namespace, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_scope_namespace( + self, + request: Optional[Union[service.UpdateScopeNamespaceRequest, dict]] = None, + *, + scope_namespace: Optional[fleet.Namespace] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates a fleet namespace. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_update_scope_namespace(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + scope_namespace = gkehub_v1.Namespace() + scope_namespace.scope = "scope_value" + + request = gkehub_v1.UpdateScopeNamespaceRequest( + scope_namespace=scope_namespace, + ) + + # Make the request + operation = client.update_scope_namespace(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.UpdateScopeNamespaceRequest, dict]): + The request object. Request to update a fleet namespace. + scope_namespace (google.cloud.gkehub_v1.types.Namespace): + Required. A namespace with fields updated. The 'name' + field in this namespace is used to identify the resource + to update. Given 'updated' prefix to follow + go/proto-best-practices-checkers#keyword_conflict + + This corresponds to the ``scope_namespace`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.Namespace` + Namespace represents a namespace across the Fleet + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [scope_namespace, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateScopeNamespaceRequest): + request = service.UpdateScopeNamespaceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope_namespace is not None: + request.scope_namespace = scope_namespace + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_scope_namespace] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("scope_namespace.name", request.scope_namespace.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + fleet.Namespace, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_scope_namespace( + self, + request: Optional[Union[service.DeleteScopeNamespaceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a fleet namespace. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_delete_scope_namespace(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteScopeNamespaceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_scope_namespace(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.DeleteScopeNamespaceRequest, dict]): + The request object. Request to delete a fleet namespace. + name (str): + Required. The Namespace resource name in the format + ``projects/*/locations/*/scopes/*/namespaces/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DeleteScopeNamespaceRequest): + request = service.DeleteScopeNamespaceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_scope_namespace] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_scope_namespaces( + self, + request: Optional[Union[service.ListScopeNamespacesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListScopeNamespacesPager: + r"""Lists fleet namespaces. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_list_scope_namespaces(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.ListScopeNamespacesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scope_namespaces(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.ListScopeNamespacesRequest, dict]): + The request object. Request to list fleet namespaces. + parent (str): + Required. The parent (project and location) where the + Features will be listed. Specified in the format + ``projects/*/locations/*/scopes/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.services.gke_hub.pagers.ListScopeNamespacesPager: + List of fleet namespaces. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListScopeNamespacesRequest): + request = service.ListScopeNamespacesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_scope_namespaces] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListScopeNamespacesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_scope_rbac_role_binding( + self, + request: Optional[Union[service.GetScopeRBACRoleBindingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> fleet.RBACRoleBinding: + r"""Returns the details of a Scope RBACRoleBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_get_scope_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.GetScopeRBACRoleBindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_scope_rbac_role_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.GetScopeRBACRoleBindingRequest, dict]): + The request object. Request message for the + ``GkeHub.GetScopeRBACRoleBinding`` method. + name (str): + Required. The RBACRoleBinding resource name in the + format + ``projects/*/locations/*/scopes/*/rbacrolebindings/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.types.RBACRoleBinding: + RBACRoleBinding represents a + rbacrolebinding across the Fleet + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetScopeRBACRoleBindingRequest): + request = service.GetScopeRBACRoleBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_scope_rbac_role_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_scope_rbac_role_binding( + self, + request: Optional[ + Union[service.CreateScopeRBACRoleBindingRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + rbacrolebinding: Optional[fleet.RBACRoleBinding] = None, + rbacrolebinding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a Scope RBACRoleBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_create_scope_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + rbacrolebinding = gkehub_v1.RBACRoleBinding() + rbacrolebinding.user = "user_value" + + request = gkehub_v1.CreateScopeRBACRoleBindingRequest( + parent="parent_value", + rbacrolebinding_id="rbacrolebinding_id_value", + rbacrolebinding=rbacrolebinding, + ) + + # Make the request + operation = client.create_scope_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.CreateScopeRBACRoleBindingRequest, dict]): + The request object. Request to create a rbacrolebindings. + parent (str): + Required. The parent (project and location) where the + RBACRoleBinding will be created. Specified in the format + ``projects/*/locations/*/scopes/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rbacrolebinding (google.cloud.gkehub_v1.types.RBACRoleBinding): + Required. The rbacrolebindings to + create. + + This corresponds to the ``rbacrolebinding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rbacrolebinding_id (str): + Required. Client chosen ID for the RBACRoleBinding. + ``rbacrolebinding_id`` must be a valid RFC 1123 + compliant DNS label: + + 1. At most 63 characters in length + 2. It must consist of lower case alphanumeric characters + or ``-`` + 3. It must start and end with an alphanumeric character + + Which can be expressed as the regex: + ``[a-z0-9]([-a-z0-9]*[a-z0-9])?``, with a maximum length + of 63 characters. + + This corresponds to the ``rbacrolebinding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.RBACRoleBinding` + RBACRoleBinding represents a rbacrolebinding across the + Fleet + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, rbacrolebinding, rbacrolebinding_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateScopeRBACRoleBindingRequest): + request = service.CreateScopeRBACRoleBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if rbacrolebinding is not None: + request.rbacrolebinding = rbacrolebinding + if rbacrolebinding_id is not None: + request.rbacrolebinding_id = rbacrolebinding_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_scope_rbac_role_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + fleet.RBACRoleBinding, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_scope_rbac_role_binding( + self, + request: Optional[ + Union[service.UpdateScopeRBACRoleBindingRequest, dict] + ] = None, + *, + rbacrolebinding: Optional[fleet.RBACRoleBinding] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates a Scope RBACRoleBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_update_scope_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + rbacrolebinding = gkehub_v1.RBACRoleBinding() + rbacrolebinding.user = "user_value" + + request = gkehub_v1.UpdateScopeRBACRoleBindingRequest( + rbacrolebinding=rbacrolebinding, + ) + + # Make the request + operation = client.update_scope_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.UpdateScopeRBACRoleBindingRequest, dict]): + The request object. Request to update a scope + rbacrolebinding. + rbacrolebinding (google.cloud.gkehub_v1.types.RBACRoleBinding): + Required. A rbacrolebinding with + fields updated. The 'name' field in this + rbacrolebinding is used to identify the + resource to update. + + This corresponds to the ``rbacrolebinding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.RBACRoleBinding` + RBACRoleBinding represents a rbacrolebinding across the + Fleet + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [rbacrolebinding, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateScopeRBACRoleBindingRequest): + request = service.UpdateScopeRBACRoleBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if rbacrolebinding is not None: + request.rbacrolebinding = rbacrolebinding + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_scope_rbac_role_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("rbacrolebinding.name", request.rbacrolebinding.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + fleet.RBACRoleBinding, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_scope_rbac_role_binding( + self, + request: Optional[ + Union[service.DeleteScopeRBACRoleBindingRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a Scope RBACRoleBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_delete_scope_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteScopeRBACRoleBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_scope_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.DeleteScopeRBACRoleBindingRequest, dict]): + The request object. Request to delete a Scope + RBACRoleBinding. + name (str): + Required. The RBACRoleBinding resource name in the + format + ``projects/*/locations/*/scopes/*/rbacrolebindings/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DeleteScopeRBACRoleBindingRequest): + request = service.DeleteScopeRBACRoleBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_scope_rbac_role_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_scope_rbac_role_bindings( + self, + request: Optional[Union[service.ListScopeRBACRoleBindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListScopeRBACRoleBindingsPager: + r"""Lists all Scope RBACRoleBindings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_list_scope_rbac_role_bindings(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.ListScopeRBACRoleBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scope_rbac_role_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.ListScopeRBACRoleBindingsRequest, dict]): + The request object. Request to list Scope + RBACRoleBindings. + parent (str): + Required. The parent (project and location) where the + Features will be listed. Specified in the format + ``projects/*/locations/*/scopes/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.services.gke_hub.pagers.ListScopeRBACRoleBindingsPager: + List of Scope RBACRoleBindings. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListScopeRBACRoleBindingsRequest): + request = service.ListScopeRBACRoleBindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_scope_rbac_role_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListScopeRBACRoleBindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_scope( + self, + request: Optional[Union[service.GetScopeRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> fleet.Scope: + r"""Returns the details of a Scope. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_get_scope(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.GetScopeRequest( + name="name_value", + ) + + # Make the request + response = client.get_scope(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.GetScopeRequest, dict]): + The request object. Request message for the ``GkeHub.GetScope`` method. + name (str): + Required. The Scope resource name in the format + ``projects/*/locations/*/scopes/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.types.Scope: + Scope represents a Scope in a Fleet. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetScopeRequest): + request = service.GetScopeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_scope] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_scope( + self, + request: Optional[Union[service.CreateScopeRequest, dict]] = None, + *, + parent: Optional[str] = None, + scope: Optional[fleet.Scope] = None, + scope_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a Scope. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_create_scope(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.CreateScopeRequest( + parent="parent_value", + scope_id="scope_id_value", + ) + + # Make the request + operation = client.create_scope(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.CreateScopeRequest, dict]): + The request object. Request to create a Scope. + parent (str): + Required. The parent (project and location) where the + Scope will be created. Specified in the format + ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scope (google.cloud.gkehub_v1.types.Scope): + Required. The Scope to create. + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scope_id (str): + Required. Client chosen ID for the Scope. ``scope_id`` + must be a ???? + + This corresponds to the ``scope_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.Scope` Scope + represents a Scope in a Fleet. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, scope, scope_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateScopeRequest): + request = service.CreateScopeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if scope is not None: + request.scope = scope + if scope_id is not None: + request.scope_id = scope_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_scope] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + fleet.Scope, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_scope( + self, + request: Optional[Union[service.UpdateScopeRequest, dict]] = None, + *, + scope: Optional[fleet.Scope] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates a scopes. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_update_scope(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.UpdateScopeRequest( + ) + + # Make the request + operation = client.update_scope(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.UpdateScopeRequest, dict]): + The request object. Request to update a Scope. + scope (google.cloud.gkehub_v1.types.Scope): + Required. A Scope with fields + updated. The 'name' field in this + namespace is used to identify the + resource to update. + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.Scope` Scope + represents a Scope in a Fleet. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [scope, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateScopeRequest): + request = service.UpdateScopeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope is not None: + request.scope = scope + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_scope] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("scope.name", request.scope.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + fleet.Scope, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_scope( + self, + request: Optional[Union[service.DeleteScopeRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a Scope. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_delete_scope(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteScopeRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_scope(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.DeleteScopeRequest, dict]): + The request object. Request to delete a Scope. + name (str): + Required. The Scope resource name in the format + ``projects/*/locations/*/scopes/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DeleteScopeRequest): + request = service.DeleteScopeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_scope] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_scopes( + self, + request: Optional[Union[service.ListScopesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListScopesPager: + r"""Lists Scopes. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_list_scopes(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.ListScopesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scopes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.ListScopesRequest, dict]): + The request object. Request to list Scopes. + parent (str): + Required. The parent (project and location) where the + Scope will be listed. Specified in the format + ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.services.gke_hub.pagers.ListScopesPager: + List of Scopes. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListScopesRequest): + request = service.ListScopesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_scopes] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListScopesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_permitted_scopes( + self, + request: Optional[Union[service.ListPermittedScopesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPermittedScopesPager: + r"""Lists permitted Scopes. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_list_permitted_scopes(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.ListPermittedScopesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_permitted_scopes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.ListPermittedScopesRequest, dict]): + The request object. Request to list permitted Scopes. + parent (str): + Required. The parent (project and location) where the + Scope will be listed. Specified in the format + ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.services.gke_hub.pagers.ListPermittedScopesPager: + List of permitted Scopes. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListPermittedScopesRequest): + request = service.ListPermittedScopesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_permitted_scopes] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListPermittedScopesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_membership_binding( + self, + request: Optional[Union[service.GetMembershipBindingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> fleet.MembershipBinding: + r"""Returns the details of a MembershipBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_get_membership_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.GetMembershipBindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_membership_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.GetMembershipBindingRequest, dict]): + The request object. Request message for the ``GkeHub.GetMembershipBinding`` + method. + name (str): + Required. The MembershipBinding resource name in the + format + ``projects/*/locations/*/memberships/*/bindings/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.types.MembershipBinding: + MembershipBinding is a subresource of + a Membership, representing what Fleet + Scopes (or other, future Fleet + resources) a Membership is bound to. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetMembershipBindingRequest): + request = service.GetMembershipBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_membership_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_membership_binding( + self, + request: Optional[Union[service.CreateMembershipBindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + membership_binding: Optional[fleet.MembershipBinding] = None, + membership_binding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a MembershipBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_create_membership_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + membership_binding = gkehub_v1.MembershipBinding() + membership_binding.scope = "scope_value" + + request = gkehub_v1.CreateMembershipBindingRequest( + parent="parent_value", + membership_binding=membership_binding, + membership_binding_id="membership_binding_id_value", + ) + + # Make the request + operation = client.create_membership_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.CreateMembershipBindingRequest, dict]): + The request object. Request to create a + MembershipBinding. + parent (str): + Required. The parent (project and location) where the + MembershipBinding will be created. Specified in the + format ``projects/*/locations/*/memberships/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + membership_binding (google.cloud.gkehub_v1.types.MembershipBinding): + Required. The MembershipBinding to + create. + + This corresponds to the ``membership_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + membership_binding_id (str): + Required. The ID to use for the + MembershipBinding. + + This corresponds to the ``membership_binding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.gkehub_v1.types.MembershipBinding` MembershipBinding is a subresource of a Membership, representing + what Fleet Scopes (or other, future Fleet resources) + a Membership is bound to. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, membership_binding, membership_binding_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateMembershipBindingRequest): + request = service.CreateMembershipBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if membership_binding is not None: + request.membership_binding = membership_binding + if membership_binding_id is not None: + request.membership_binding_id = membership_binding_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_membership_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + fleet.MembershipBinding, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_membership_binding( + self, + request: Optional[Union[service.UpdateMembershipBindingRequest, dict]] = None, + *, + membership_binding: Optional[fleet.MembershipBinding] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates a MembershipBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_update_membership_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + membership_binding = gkehub_v1.MembershipBinding() + membership_binding.scope = "scope_value" + + request = gkehub_v1.UpdateMembershipBindingRequest( + membership_binding=membership_binding, + ) + + # Make the request + operation = client.update_membership_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.UpdateMembershipBindingRequest, dict]): + The request object. Request to update a + MembershipBinding. + membership_binding (google.cloud.gkehub_v1.types.MembershipBinding): + Required. The MembershipBinding + object with fields updated. + + This corresponds to the ``membership_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.gkehub_v1.types.MembershipBinding` MembershipBinding is a subresource of a Membership, representing + what Fleet Scopes (or other, future Fleet resources) + a Membership is bound to. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [membership_binding, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateMembershipBindingRequest): + request = service.UpdateMembershipBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if membership_binding is not None: + request.membership_binding = membership_binding + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_membership_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("membership_binding.name", request.membership_binding.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + fleet.MembershipBinding, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_membership_binding( + self, + request: Optional[Union[service.DeleteMembershipBindingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a MembershipBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_delete_membership_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteMembershipBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_membership_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.DeleteMembershipBindingRequest, dict]): + The request object. Request to delete a Binding. + name (str): + Required. The MembershipBinding resource name in the + format + ``projects/*/locations/*/memberships/*/bindings/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DeleteMembershipBindingRequest): + request = service.DeleteMembershipBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_membership_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_membership_bindings( + self, + request: Optional[Union[service.ListMembershipBindingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMembershipBindingsPager: + r"""Lists MembershipBindings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_list_membership_bindings(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.ListMembershipBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_membership_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.ListMembershipBindingsRequest, dict]): + The request object. Request to list MembershipBinding. + parent (str): + Required. The parent Membership for which the + MembershipBindings will be listed. Specified in the + format ``projects/*/locations/*/memberships/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.services.gke_hub.pagers.ListMembershipBindingsPager: + List of MembershipBindings. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListMembershipBindingsRequest): + request = service.ListMembershipBindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_membership_bindings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListMembershipBindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_membership_rbac_role_binding( + self, + request: Optional[ + Union[service.GetMembershipRBACRoleBindingRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> fleet.RBACRoleBinding: + r"""Returns the details of a Membership RBACRoleBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_get_membership_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.GetMembershipRBACRoleBindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_membership_rbac_role_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.GetMembershipRBACRoleBindingRequest, dict]): + The request object. Request message for the + ``GkeHub.GetMembershipRBACRoleBinding`` method. + name (str): + Required. The RBACRoleBinding resource name in the + format + ``projects/*/locations/*/memberships/*/rbacrolebindings/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.types.RBACRoleBinding: + RBACRoleBinding represents a + rbacrolebinding across the Fleet + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetMembershipRBACRoleBindingRequest): + request = service.GetMembershipRBACRoleBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_membership_rbac_role_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_membership_rbac_role_binding( + self, + request: Optional[ + Union[service.CreateMembershipRBACRoleBindingRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + rbacrolebinding: Optional[fleet.RBACRoleBinding] = None, + rbacrolebinding_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a Membership RBACRoleBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_create_membership_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + rbacrolebinding = gkehub_v1.RBACRoleBinding() + rbacrolebinding.user = "user_value" + + request = gkehub_v1.CreateMembershipRBACRoleBindingRequest( + parent="parent_value", + rbacrolebinding_id="rbacrolebinding_id_value", + rbacrolebinding=rbacrolebinding, + ) + + # Make the request + operation = client.create_membership_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.CreateMembershipRBACRoleBindingRequest, dict]): + The request object. Request to create a rbacrolebindings. + parent (str): + Required. The parent (project and location) where the + RBACRoleBinding will be created. Specified in the format + ``projects/*/locations/*/memberships/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rbacrolebinding (google.cloud.gkehub_v1.types.RBACRoleBinding): + Required. The rbacrolebindings to + create. + + This corresponds to the ``rbacrolebinding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rbacrolebinding_id (str): + Required. Client chosen ID for the RBACRoleBinding. + ``rbacrolebinding_id`` must be a valid RFC 1123 + compliant DNS label: + + 1. At most 63 characters in length + 2. It must consist of lower case alphanumeric characters + or ``-`` + 3. It must start and end with an alphanumeric character + + Which can be expressed as the regex: + ``[a-z0-9]([-a-z0-9]*[a-z0-9])?``, with a maximum length + of 63 characters. + + This corresponds to the ``rbacrolebinding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.RBACRoleBinding` + RBACRoleBinding represents a rbacrolebinding across the + Fleet + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, rbacrolebinding, rbacrolebinding_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateMembershipRBACRoleBindingRequest): + request = service.CreateMembershipRBACRoleBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if rbacrolebinding is not None: + request.rbacrolebinding = rbacrolebinding + if rbacrolebinding_id is not None: + request.rbacrolebinding_id = rbacrolebinding_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_membership_rbac_role_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + fleet.RBACRoleBinding, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_membership_rbac_role_binding( + self, + request: Optional[ + Union[service.UpdateMembershipRBACRoleBindingRequest, dict] + ] = None, + *, + rbacrolebinding: Optional[fleet.RBACRoleBinding] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Updates a Membership RBACRoleBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_update_membership_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + rbacrolebinding = gkehub_v1.RBACRoleBinding() + rbacrolebinding.user = "user_value" + + request = gkehub_v1.UpdateMembershipRBACRoleBindingRequest( + rbacrolebinding=rbacrolebinding, + ) + + # Make the request + operation = client.update_membership_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.UpdateMembershipRBACRoleBindingRequest, dict]): + The request object. Request to update a membership + rbacrolebinding. + rbacrolebinding (google.cloud.gkehub_v1.types.RBACRoleBinding): + Required. A rbacrolebinding with + fields updated. The 'name' field in this + rbacrolebinding is used to identify the + resource to update. + + This corresponds to the ``rbacrolebinding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The fields to be updated. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.gkehub_v1.types.RBACRoleBinding` + RBACRoleBinding represents a rbacrolebinding across the + Fleet + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [rbacrolebinding, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateMembershipRBACRoleBindingRequest): + request = service.UpdateMembershipRBACRoleBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if rbacrolebinding is not None: + request.rbacrolebinding = rbacrolebinding + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_membership_rbac_role_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("rbacrolebinding.name", request.rbacrolebinding.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + fleet.RBACRoleBinding, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_membership_rbac_role_binding( + self, + request: Optional[ + Union[service.DeleteMembershipRBACRoleBindingRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a Membership RBACRoleBinding. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_delete_membership_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteMembershipRBACRoleBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_membership_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.DeleteMembershipRBACRoleBindingRequest, dict]): + The request object. Request to delete a Membership + RBACRoleBinding. + name (str): + Required. The RBACRoleBinding resource name in the + format + ``projects/*/locations/*/memberships/*/rbacrolebindings/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DeleteMembershipRBACRoleBindingRequest): + request = service.DeleteMembershipRBACRoleBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + 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_membership_rbac_role_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_membership_rbac_role_bindings( + self, + request: Optional[ + Union[service.ListMembershipRBACRoleBindingsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListMembershipRBACRoleBindingsPager: + r"""Lists all Membership RBACRoleBindings. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_list_membership_rbac_role_bindings(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.ListMembershipRBACRoleBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_membership_rbac_role_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.ListMembershipRBACRoleBindingsRequest, dict]): + The request object. Request to list Membership + RBACRoleBindings. + parent (str): + Required. The parent (project and location) where the + Features will be listed. Specified in the format + ``projects/*/locations/*/memberships/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.services.gke_hub.pagers.ListMembershipRBACRoleBindingsPager: + List of Membership RBACRoleBindings. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListMembershipRBACRoleBindingsRequest): + request = service.ListMembershipRBACRoleBindingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + 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_membership_rbac_role_bindings + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListMembershipRBACRoleBindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_membership_rbac_role_binding_yaml( + self, + request: Optional[ + Union[service.GenerateMembershipRBACRoleBindingYAMLRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.GenerateMembershipRBACRoleBindingYAMLResponse: + r"""Generates a YAML of the RBAC policies for the + specified RoleBinding and its associated impersonation + resources. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import gkehub_v1 + + def sample_generate_membership_rbac_role_binding_yaml(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + rbacrolebinding = gkehub_v1.RBACRoleBinding() + rbacrolebinding.user = "user_value" + + request = gkehub_v1.GenerateMembershipRBACRoleBindingYAMLRequest( + parent="parent_value", + rbacrolebinding_id="rbacrolebinding_id_value", + rbacrolebinding=rbacrolebinding, + ) + + # Make the request + response = client.generate_membership_rbac_role_binding_yaml(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.gkehub_v1.types.GenerateMembershipRBACRoleBindingYAMLRequest, dict]): + The request object. Request to generate a YAML of the + RBAC policies for the specified + RoleBinding and its associated + impersonation resources. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.gkehub_v1.types.GenerateMembershipRBACRoleBindingYAMLResponse: + Response for + GenerateRBACRoleBindingYAML. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, service.GenerateMembershipRBACRoleBindingYAMLRequest + ): + request = service.GenerateMembershipRBACRoleBindingYAMLRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.generate_membership_rbac_role_binding_yaml + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "GkeHubClient": return self diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/pagers.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/pagers.py index d8b04a53b175..7151c981f692 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/pagers.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/pagers.py @@ -38,7 +38,7 @@ OptionalRetry = Union[retries.Retry, object, None] # type: ignore OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore -from google.cloud.gkehub_v1.types import feature, membership, service +from google.cloud.gkehub_v1.types import feature, fleet, membership, service class ListMembershipsPager: @@ -197,6 +197,162 @@ def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) +class ListBoundMembershipsPager: + """A pager for iterating through ``list_bound_memberships`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1.types.ListBoundMembershipsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``memberships`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBoundMemberships`` requests and continue to iterate + through the ``memberships`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1.types.ListBoundMembershipsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., service.ListBoundMembershipsResponse], + request: service.ListBoundMembershipsRequest, + response: service.ListBoundMembershipsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gkehub_v1.types.ListBoundMembershipsRequest): + The initial request object. + response (google.cloud.gkehub_v1.types.ListBoundMembershipsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListBoundMembershipsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListBoundMembershipsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[membership.Membership]: + for page in self.pages: + yield from page.memberships + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBoundMembershipsAsyncPager: + """A pager for iterating through ``list_bound_memberships`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1.types.ListBoundMembershipsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``memberships`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBoundMemberships`` requests and continue to iterate + through the ``memberships`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1.types.ListBoundMembershipsResponse` + attributes are available on the 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[service.ListBoundMembershipsResponse]], + request: service.ListBoundMembershipsRequest, + response: service.ListBoundMembershipsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gkehub_v1.types.ListBoundMembershipsRequest): + The initial request object. + response (google.cloud.gkehub_v1.types.ListBoundMembershipsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListBoundMembershipsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListBoundMembershipsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[membership.Membership]: + async def async_generator(): + async for page in self.pages: + for response in page.memberships: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class ListFeaturesPager: """A pager for iterating through ``list_features`` requests. @@ -351,3 +507,1099 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListFleetsPager: + """A pager for iterating through ``list_fleets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1.types.ListFleetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``fleets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFleets`` requests and continue to iterate + through the ``fleets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1.types.ListFleetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., service.ListFleetsResponse], + request: service.ListFleetsRequest, + response: service.ListFleetsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gkehub_v1.types.ListFleetsRequest): + The initial request object. + response (google.cloud.gkehub_v1.types.ListFleetsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListFleetsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListFleetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[fleet.Fleet]: + for page in self.pages: + yield from page.fleets + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListFleetsAsyncPager: + """A pager for iterating through ``list_fleets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1.types.ListFleetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``fleets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFleets`` requests and continue to iterate + through the ``fleets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1.types.ListFleetsResponse` + attributes are available on the 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[service.ListFleetsResponse]], + request: service.ListFleetsRequest, + response: service.ListFleetsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gkehub_v1.types.ListFleetsRequest): + The initial request object. + response (google.cloud.gkehub_v1.types.ListFleetsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListFleetsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListFleetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[fleet.Fleet]: + async def async_generator(): + async for page in self.pages: + for response in page.fleets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListScopeNamespacesPager: + """A pager for iterating through ``list_scope_namespaces`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1.types.ListScopeNamespacesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``scope_namespaces`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListScopeNamespaces`` requests and continue to iterate + through the ``scope_namespaces`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1.types.ListScopeNamespacesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., service.ListScopeNamespacesResponse], + request: service.ListScopeNamespacesRequest, + response: service.ListScopeNamespacesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gkehub_v1.types.ListScopeNamespacesRequest): + The initial request object. + response (google.cloud.gkehub_v1.types.ListScopeNamespacesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListScopeNamespacesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListScopeNamespacesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[fleet.Namespace]: + for page in self.pages: + yield from page.scope_namespaces + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListScopeNamespacesAsyncPager: + """A pager for iterating through ``list_scope_namespaces`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1.types.ListScopeNamespacesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``scope_namespaces`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListScopeNamespaces`` requests and continue to iterate + through the ``scope_namespaces`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1.types.ListScopeNamespacesResponse` + attributes are available on the 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[service.ListScopeNamespacesResponse]], + request: service.ListScopeNamespacesRequest, + response: service.ListScopeNamespacesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gkehub_v1.types.ListScopeNamespacesRequest): + The initial request object. + response (google.cloud.gkehub_v1.types.ListScopeNamespacesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListScopeNamespacesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListScopeNamespacesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[fleet.Namespace]: + async def async_generator(): + async for page in self.pages: + for response in page.scope_namespaces: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListScopeRBACRoleBindingsPager: + """A pager for iterating through ``list_scope_rbac_role_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1.types.ListScopeRBACRoleBindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``rbacrolebindings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListScopeRBACRoleBindings`` requests and continue to iterate + through the ``rbacrolebindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1.types.ListScopeRBACRoleBindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., service.ListScopeRBACRoleBindingsResponse], + request: service.ListScopeRBACRoleBindingsRequest, + response: service.ListScopeRBACRoleBindingsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gkehub_v1.types.ListScopeRBACRoleBindingsRequest): + The initial request object. + response (google.cloud.gkehub_v1.types.ListScopeRBACRoleBindingsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListScopeRBACRoleBindingsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListScopeRBACRoleBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[fleet.RBACRoleBinding]: + for page in self.pages: + yield from page.rbacrolebindings + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListScopeRBACRoleBindingsAsyncPager: + """A pager for iterating through ``list_scope_rbac_role_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1.types.ListScopeRBACRoleBindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``rbacrolebindings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListScopeRBACRoleBindings`` requests and continue to iterate + through the ``rbacrolebindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1.types.ListScopeRBACRoleBindingsResponse` + attributes are available on the 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[service.ListScopeRBACRoleBindingsResponse]], + request: service.ListScopeRBACRoleBindingsRequest, + response: service.ListScopeRBACRoleBindingsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gkehub_v1.types.ListScopeRBACRoleBindingsRequest): + The initial request object. + response (google.cloud.gkehub_v1.types.ListScopeRBACRoleBindingsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListScopeRBACRoleBindingsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListScopeRBACRoleBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[fleet.RBACRoleBinding]: + async def async_generator(): + async for page in self.pages: + for response in page.rbacrolebindings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListScopesPager: + """A pager for iterating through ``list_scopes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1.types.ListScopesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``scopes`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListScopes`` requests and continue to iterate + through the ``scopes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1.types.ListScopesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., service.ListScopesResponse], + request: service.ListScopesRequest, + response: service.ListScopesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gkehub_v1.types.ListScopesRequest): + The initial request object. + response (google.cloud.gkehub_v1.types.ListScopesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListScopesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListScopesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[fleet.Scope]: + for page in self.pages: + yield from page.scopes + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListScopesAsyncPager: + """A pager for iterating through ``list_scopes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1.types.ListScopesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``scopes`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListScopes`` requests and continue to iterate + through the ``scopes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1.types.ListScopesResponse` + attributes are available on the 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[service.ListScopesResponse]], + request: service.ListScopesRequest, + response: service.ListScopesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gkehub_v1.types.ListScopesRequest): + The initial request object. + response (google.cloud.gkehub_v1.types.ListScopesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListScopesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListScopesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[fleet.Scope]: + async def async_generator(): + async for page in self.pages: + for response in page.scopes: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListPermittedScopesPager: + """A pager for iterating through ``list_permitted_scopes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1.types.ListPermittedScopesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``scopes`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPermittedScopes`` requests and continue to iterate + through the ``scopes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1.types.ListPermittedScopesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., service.ListPermittedScopesResponse], + request: service.ListPermittedScopesRequest, + response: service.ListPermittedScopesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gkehub_v1.types.ListPermittedScopesRequest): + The initial request object. + response (google.cloud.gkehub_v1.types.ListPermittedScopesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListPermittedScopesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListPermittedScopesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[fleet.Scope]: + for page in self.pages: + yield from page.scopes + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListPermittedScopesAsyncPager: + """A pager for iterating through ``list_permitted_scopes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1.types.ListPermittedScopesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``scopes`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPermittedScopes`` requests and continue to iterate + through the ``scopes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1.types.ListPermittedScopesResponse` + attributes are available on the 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[service.ListPermittedScopesResponse]], + request: service.ListPermittedScopesRequest, + response: service.ListPermittedScopesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gkehub_v1.types.ListPermittedScopesRequest): + The initial request object. + response (google.cloud.gkehub_v1.types.ListPermittedScopesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListPermittedScopesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListPermittedScopesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[fleet.Scope]: + async def async_generator(): + async for page in self.pages: + for response in page.scopes: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMembershipBindingsPager: + """A pager for iterating through ``list_membership_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1.types.ListMembershipBindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``membership_bindings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMembershipBindings`` requests and continue to iterate + through the ``membership_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1.types.ListMembershipBindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., service.ListMembershipBindingsResponse], + request: service.ListMembershipBindingsRequest, + response: service.ListMembershipBindingsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gkehub_v1.types.ListMembershipBindingsRequest): + The initial request object. + response (google.cloud.gkehub_v1.types.ListMembershipBindingsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListMembershipBindingsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListMembershipBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[fleet.MembershipBinding]: + for page in self.pages: + yield from page.membership_bindings + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMembershipBindingsAsyncPager: + """A pager for iterating through ``list_membership_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1.types.ListMembershipBindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``membership_bindings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMembershipBindings`` requests and continue to iterate + through the ``membership_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1.types.ListMembershipBindingsResponse` + attributes are available on the 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[service.ListMembershipBindingsResponse]], + request: service.ListMembershipBindingsRequest, + response: service.ListMembershipBindingsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gkehub_v1.types.ListMembershipBindingsRequest): + The initial request object. + response (google.cloud.gkehub_v1.types.ListMembershipBindingsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListMembershipBindingsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListMembershipBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[fleet.MembershipBinding]: + async def async_generator(): + async for page in self.pages: + for response in page.membership_bindings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMembershipRBACRoleBindingsPager: + """A pager for iterating through ``list_membership_rbac_role_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1.types.ListMembershipRBACRoleBindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``rbacrolebindings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMembershipRBACRoleBindings`` requests and continue to iterate + through the ``rbacrolebindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1.types.ListMembershipRBACRoleBindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., service.ListMembershipRBACRoleBindingsResponse], + request: service.ListMembershipRBACRoleBindingsRequest, + response: service.ListMembershipRBACRoleBindingsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gkehub_v1.types.ListMembershipRBACRoleBindingsRequest): + The initial request object. + response (google.cloud.gkehub_v1.types.ListMembershipRBACRoleBindingsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListMembershipRBACRoleBindingsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListMembershipRBACRoleBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[fleet.RBACRoleBinding]: + for page in self.pages: + yield from page.rbacrolebindings + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListMembershipRBACRoleBindingsAsyncPager: + """A pager for iterating through ``list_membership_rbac_role_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.gkehub_v1.types.ListMembershipRBACRoleBindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``rbacrolebindings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMembershipRBACRoleBindings`` requests and continue to iterate + through the ``rbacrolebindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.gkehub_v1.types.ListMembershipRBACRoleBindingsResponse` + attributes are available on the 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[service.ListMembershipRBACRoleBindingsResponse] + ], + request: service.ListMembershipRBACRoleBindingsRequest, + response: service.ListMembershipRBACRoleBindingsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.gkehub_v1.types.ListMembershipRBACRoleBindingsRequest): + The initial request object. + response (google.cloud.gkehub_v1.types.ListMembershipRBACRoleBindingsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = service.ListMembershipRBACRoleBindingsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[service.ListMembershipRBACRoleBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[fleet.RBACRoleBinding]: + async def async_generator(): + async for page in self.pages: + for response in page.rbacrolebindings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/base.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/base.py index f85b084e0b99..be99acde66ad 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/base.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/base.py @@ -27,7 +27,7 @@ import google.protobuf from google.cloud.gkehub_v1 import gapic_version as package_version -from google.cloud.gkehub_v1.types import feature, membership, service +from google.cloud.gkehub_v1.types import feature, fleet, membership, service DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ @@ -142,6 +142,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.list_bound_memberships: gapic_v1.method.wrap_method( + self.list_bound_memberships, + default_timeout=None, + client_info=client_info, + ), self.list_features: gapic_v1.method.wrap_method( self.list_features, default_timeout=None, @@ -192,6 +197,166 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.create_fleet: gapic_v1.method.wrap_method( + self.create_fleet, + default_timeout=None, + client_info=client_info, + ), + self.get_fleet: gapic_v1.method.wrap_method( + self.get_fleet, + default_timeout=None, + client_info=client_info, + ), + self.update_fleet: gapic_v1.method.wrap_method( + self.update_fleet, + default_timeout=None, + client_info=client_info, + ), + self.delete_fleet: gapic_v1.method.wrap_method( + self.delete_fleet, + default_timeout=None, + client_info=client_info, + ), + self.list_fleets: gapic_v1.method.wrap_method( + self.list_fleets, + default_timeout=None, + client_info=client_info, + ), + self.get_scope_namespace: gapic_v1.method.wrap_method( + self.get_scope_namespace, + default_timeout=None, + client_info=client_info, + ), + self.create_scope_namespace: gapic_v1.method.wrap_method( + self.create_scope_namespace, + default_timeout=None, + client_info=client_info, + ), + self.update_scope_namespace: gapic_v1.method.wrap_method( + self.update_scope_namespace, + default_timeout=None, + client_info=client_info, + ), + self.delete_scope_namespace: gapic_v1.method.wrap_method( + self.delete_scope_namespace, + default_timeout=None, + client_info=client_info, + ), + self.list_scope_namespaces: gapic_v1.method.wrap_method( + self.list_scope_namespaces, + default_timeout=None, + client_info=client_info, + ), + self.get_scope_rbac_role_binding: gapic_v1.method.wrap_method( + self.get_scope_rbac_role_binding, + default_timeout=None, + client_info=client_info, + ), + self.create_scope_rbac_role_binding: gapic_v1.method.wrap_method( + self.create_scope_rbac_role_binding, + default_timeout=None, + client_info=client_info, + ), + self.update_scope_rbac_role_binding: gapic_v1.method.wrap_method( + self.update_scope_rbac_role_binding, + default_timeout=None, + client_info=client_info, + ), + self.delete_scope_rbac_role_binding: gapic_v1.method.wrap_method( + self.delete_scope_rbac_role_binding, + default_timeout=None, + client_info=client_info, + ), + self.list_scope_rbac_role_bindings: gapic_v1.method.wrap_method( + self.list_scope_rbac_role_bindings, + default_timeout=None, + client_info=client_info, + ), + self.get_scope: gapic_v1.method.wrap_method( + self.get_scope, + default_timeout=None, + client_info=client_info, + ), + self.create_scope: gapic_v1.method.wrap_method( + self.create_scope, + default_timeout=None, + client_info=client_info, + ), + self.update_scope: gapic_v1.method.wrap_method( + self.update_scope, + default_timeout=None, + client_info=client_info, + ), + self.delete_scope: gapic_v1.method.wrap_method( + self.delete_scope, + default_timeout=None, + client_info=client_info, + ), + self.list_scopes: gapic_v1.method.wrap_method( + self.list_scopes, + default_timeout=None, + client_info=client_info, + ), + self.list_permitted_scopes: gapic_v1.method.wrap_method( + self.list_permitted_scopes, + default_timeout=None, + client_info=client_info, + ), + self.get_membership_binding: gapic_v1.method.wrap_method( + self.get_membership_binding, + default_timeout=None, + client_info=client_info, + ), + self.create_membership_binding: gapic_v1.method.wrap_method( + self.create_membership_binding, + default_timeout=None, + client_info=client_info, + ), + self.update_membership_binding: gapic_v1.method.wrap_method( + self.update_membership_binding, + default_timeout=None, + client_info=client_info, + ), + self.delete_membership_binding: gapic_v1.method.wrap_method( + self.delete_membership_binding, + default_timeout=None, + client_info=client_info, + ), + self.list_membership_bindings: gapic_v1.method.wrap_method( + self.list_membership_bindings, + default_timeout=None, + client_info=client_info, + ), + self.get_membership_rbac_role_binding: gapic_v1.method.wrap_method( + self.get_membership_rbac_role_binding, + default_timeout=None, + client_info=client_info, + ), + self.create_membership_rbac_role_binding: gapic_v1.method.wrap_method( + self.create_membership_rbac_role_binding, + default_timeout=None, + client_info=client_info, + ), + self.update_membership_rbac_role_binding: gapic_v1.method.wrap_method( + self.update_membership_rbac_role_binding, + default_timeout=None, + client_info=client_info, + ), + self.delete_membership_rbac_role_binding: gapic_v1.method.wrap_method( + self.delete_membership_rbac_role_binding, + default_timeout=None, + client_info=client_info, + ), + self.list_membership_rbac_role_bindings: gapic_v1.method.wrap_method( + self.list_membership_rbac_role_bindings, + default_timeout=None, + client_info=client_info, + ), + self.generate_membership_rbac_role_binding_yaml: gapic_v1.method.wrap_method( + self.generate_membership_rbac_role_binding_yaml, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -219,6 +384,18 @@ def list_memberships( ]: raise NotImplementedError() + @property + def list_bound_memberships( + self, + ) -> Callable[ + [service.ListBoundMembershipsRequest], + Union[ + service.ListBoundMembershipsResponse, + Awaitable[service.ListBoundMembershipsResponse], + ], + ]: + raise NotImplementedError() + @property def list_features( self, @@ -311,6 +488,310 @@ def generate_connect_manifest( ]: raise NotImplementedError() + @property + def create_fleet( + self, + ) -> Callable[ + [service.CreateFleetRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_fleet( + self, + ) -> Callable[ + [service.GetFleetRequest], Union[fleet.Fleet, Awaitable[fleet.Fleet]] + ]: + raise NotImplementedError() + + @property + def update_fleet( + self, + ) -> Callable[ + [service.UpdateFleetRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_fleet( + self, + ) -> Callable[ + [service.DeleteFleetRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_fleets( + self, + ) -> Callable[ + [service.ListFleetsRequest], + Union[service.ListFleetsResponse, Awaitable[service.ListFleetsResponse]], + ]: + raise NotImplementedError() + + @property + def get_scope_namespace( + self, + ) -> Callable[ + [service.GetScopeNamespaceRequest], + Union[fleet.Namespace, Awaitable[fleet.Namespace]], + ]: + raise NotImplementedError() + + @property + def create_scope_namespace( + self, + ) -> Callable[ + [service.CreateScopeNamespaceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_scope_namespace( + self, + ) -> Callable[ + [service.UpdateScopeNamespaceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_scope_namespace( + self, + ) -> Callable[ + [service.DeleteScopeNamespaceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_scope_namespaces( + self, + ) -> Callable[ + [service.ListScopeNamespacesRequest], + Union[ + service.ListScopeNamespacesResponse, + Awaitable[service.ListScopeNamespacesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_scope_rbac_role_binding( + self, + ) -> Callable[ + [service.GetScopeRBACRoleBindingRequest], + Union[fleet.RBACRoleBinding, Awaitable[fleet.RBACRoleBinding]], + ]: + raise NotImplementedError() + + @property + def create_scope_rbac_role_binding( + self, + ) -> Callable[ + [service.CreateScopeRBACRoleBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_scope_rbac_role_binding( + self, + ) -> Callable[ + [service.UpdateScopeRBACRoleBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_scope_rbac_role_binding( + self, + ) -> Callable[ + [service.DeleteScopeRBACRoleBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_scope_rbac_role_bindings( + self, + ) -> Callable[ + [service.ListScopeRBACRoleBindingsRequest], + Union[ + service.ListScopeRBACRoleBindingsResponse, + Awaitable[service.ListScopeRBACRoleBindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_scope( + self, + ) -> Callable[ + [service.GetScopeRequest], Union[fleet.Scope, Awaitable[fleet.Scope]] + ]: + raise NotImplementedError() + + @property + def create_scope( + self, + ) -> Callable[ + [service.CreateScopeRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_scope( + self, + ) -> Callable[ + [service.UpdateScopeRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_scope( + self, + ) -> Callable[ + [service.DeleteScopeRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_scopes( + self, + ) -> Callable[ + [service.ListScopesRequest], + Union[service.ListScopesResponse, Awaitable[service.ListScopesResponse]], + ]: + raise NotImplementedError() + + @property + def list_permitted_scopes( + self, + ) -> Callable[ + [service.ListPermittedScopesRequest], + Union[ + service.ListPermittedScopesResponse, + Awaitable[service.ListPermittedScopesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_membership_binding( + self, + ) -> Callable[ + [service.GetMembershipBindingRequest], + Union[fleet.MembershipBinding, Awaitable[fleet.MembershipBinding]], + ]: + raise NotImplementedError() + + @property + def create_membership_binding( + self, + ) -> Callable[ + [service.CreateMembershipBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_membership_binding( + self, + ) -> Callable[ + [service.UpdateMembershipBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_membership_binding( + self, + ) -> Callable[ + [service.DeleteMembershipBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_membership_bindings( + self, + ) -> Callable[ + [service.ListMembershipBindingsRequest], + Union[ + service.ListMembershipBindingsResponse, + Awaitable[service.ListMembershipBindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_membership_rbac_role_binding( + self, + ) -> Callable[ + [service.GetMembershipRBACRoleBindingRequest], + Union[fleet.RBACRoleBinding, Awaitable[fleet.RBACRoleBinding]], + ]: + raise NotImplementedError() + + @property + def create_membership_rbac_role_binding( + self, + ) -> Callable[ + [service.CreateMembershipRBACRoleBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_membership_rbac_role_binding( + self, + ) -> Callable[ + [service.UpdateMembershipRBACRoleBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_membership_rbac_role_binding( + self, + ) -> Callable[ + [service.DeleteMembershipRBACRoleBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_membership_rbac_role_bindings( + self, + ) -> Callable[ + [service.ListMembershipRBACRoleBindingsRequest], + Union[ + service.ListMembershipRBACRoleBindingsResponse, + Awaitable[service.ListMembershipRBACRoleBindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def generate_membership_rbac_role_binding_yaml( + self, + ) -> Callable[ + [service.GenerateMembershipRBACRoleBindingYAMLRequest], + Union[ + service.GenerateMembershipRBACRoleBindingYAMLResponse, + Awaitable[service.GenerateMembershipRBACRoleBindingYAMLResponse], + ], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/grpc.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/grpc.py index f610545add23..3183b0d94162 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/grpc.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/grpc.py @@ -29,7 +29,7 @@ import grpc # type: ignore import proto # type: ignore -from google.cloud.gkehub_v1.types import feature, membership, service +from google.cloud.gkehub_v1.types import feature, fleet, membership, service from .base import DEFAULT_CLIENT_INFO, GkeHubTransport @@ -381,6 +381,35 @@ def list_memberships( ) return self._stubs["list_memberships"] + @property + def list_bound_memberships( + self, + ) -> Callable[ + [service.ListBoundMembershipsRequest], service.ListBoundMembershipsResponse + ]: + r"""Return a callable for the list bound memberships method over gRPC. + + Lists Memberships bound to a Scope. The response + includes relevant Memberships from all regions. + + Returns: + Callable[[~.ListBoundMembershipsRequest], + ~.ListBoundMembershipsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_bound_memberships" not in self._stubs: + self._stubs["list_bound_memberships"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/ListBoundMemberships", + request_serializer=service.ListBoundMembershipsRequest.serialize, + response_deserializer=service.ListBoundMembershipsResponse.deserialize, + ) + return self._stubs["list_bound_memberships"] + @property def list_features( self, @@ -654,6 +683,893 @@ def generate_connect_manifest( ) return self._stubs["generate_connect_manifest"] + @property + def create_fleet( + self, + ) -> Callable[[service.CreateFleetRequest], operations_pb2.Operation]: + r"""Return a callable for the create fleet method over gRPC. + + Creates a fleet. + + Returns: + Callable[[~.CreateFleetRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_fleet" not in self._stubs: + self._stubs["create_fleet"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/CreateFleet", + request_serializer=service.CreateFleetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_fleet"] + + @property + def get_fleet(self) -> Callable[[service.GetFleetRequest], fleet.Fleet]: + r"""Return a callable for the get fleet method over gRPC. + + Returns the details of a fleet. + + Returns: + Callable[[~.GetFleetRequest], + ~.Fleet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_fleet" not in self._stubs: + self._stubs["get_fleet"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/GetFleet", + request_serializer=service.GetFleetRequest.serialize, + response_deserializer=fleet.Fleet.deserialize, + ) + return self._stubs["get_fleet"] + + @property + def update_fleet( + self, + ) -> Callable[[service.UpdateFleetRequest], operations_pb2.Operation]: + r"""Return a callable for the update fleet method over gRPC. + + Updates a fleet. + + Returns: + Callable[[~.UpdateFleetRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_fleet" not in self._stubs: + self._stubs["update_fleet"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/UpdateFleet", + request_serializer=service.UpdateFleetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_fleet"] + + @property + def delete_fleet( + self, + ) -> Callable[[service.DeleteFleetRequest], operations_pb2.Operation]: + r"""Return a callable for the delete fleet method over gRPC. + + Removes a Fleet. There must be no memberships + remaining in the Fleet. + + Returns: + Callable[[~.DeleteFleetRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_fleet" not in self._stubs: + self._stubs["delete_fleet"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/DeleteFleet", + request_serializer=service.DeleteFleetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_fleet"] + + @property + def list_fleets( + self, + ) -> Callable[[service.ListFleetsRequest], service.ListFleetsResponse]: + r"""Return a callable for the list fleets method over gRPC. + + Returns all fleets within an organization or a + project that the caller has access to. + + Returns: + Callable[[~.ListFleetsRequest], + ~.ListFleetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_fleets" not in self._stubs: + self._stubs["list_fleets"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/ListFleets", + request_serializer=service.ListFleetsRequest.serialize, + response_deserializer=service.ListFleetsResponse.deserialize, + ) + return self._stubs["list_fleets"] + + @property + def get_scope_namespace( + self, + ) -> Callable[[service.GetScopeNamespaceRequest], fleet.Namespace]: + r"""Return a callable for the get scope namespace method over gRPC. + + Returns the details of a fleet namespace. + + Returns: + Callable[[~.GetScopeNamespaceRequest], + ~.Namespace]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_scope_namespace" not in self._stubs: + self._stubs["get_scope_namespace"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/GetScopeNamespace", + request_serializer=service.GetScopeNamespaceRequest.serialize, + response_deserializer=fleet.Namespace.deserialize, + ) + return self._stubs["get_scope_namespace"] + + @property + def create_scope_namespace( + self, + ) -> Callable[[service.CreateScopeNamespaceRequest], operations_pb2.Operation]: + r"""Return a callable for the create scope namespace method over gRPC. + + Creates a fleet namespace. + + Returns: + Callable[[~.CreateScopeNamespaceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_scope_namespace" not in self._stubs: + self._stubs["create_scope_namespace"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/CreateScopeNamespace", + request_serializer=service.CreateScopeNamespaceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_scope_namespace"] + + @property + def update_scope_namespace( + self, + ) -> Callable[[service.UpdateScopeNamespaceRequest], operations_pb2.Operation]: + r"""Return a callable for the update scope namespace method over gRPC. + + Updates a fleet namespace. + + Returns: + Callable[[~.UpdateScopeNamespaceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_scope_namespace" not in self._stubs: + self._stubs["update_scope_namespace"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/UpdateScopeNamespace", + request_serializer=service.UpdateScopeNamespaceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_scope_namespace"] + + @property + def delete_scope_namespace( + self, + ) -> Callable[[service.DeleteScopeNamespaceRequest], operations_pb2.Operation]: + r"""Return a callable for the delete scope namespace method over gRPC. + + Deletes a fleet namespace. + + Returns: + Callable[[~.DeleteScopeNamespaceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_scope_namespace" not in self._stubs: + self._stubs["delete_scope_namespace"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/DeleteScopeNamespace", + request_serializer=service.DeleteScopeNamespaceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_scope_namespace"] + + @property + def list_scope_namespaces( + self, + ) -> Callable[ + [service.ListScopeNamespacesRequest], service.ListScopeNamespacesResponse + ]: + r"""Return a callable for the list scope namespaces method over gRPC. + + Lists fleet namespaces. + + Returns: + Callable[[~.ListScopeNamespacesRequest], + ~.ListScopeNamespacesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_scope_namespaces" not in self._stubs: + self._stubs["list_scope_namespaces"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/ListScopeNamespaces", + request_serializer=service.ListScopeNamespacesRequest.serialize, + response_deserializer=service.ListScopeNamespacesResponse.deserialize, + ) + return self._stubs["list_scope_namespaces"] + + @property + def get_scope_rbac_role_binding( + self, + ) -> Callable[[service.GetScopeRBACRoleBindingRequest], fleet.RBACRoleBinding]: + r"""Return a callable for the get scope rbac role binding method over gRPC. + + Returns the details of a Scope RBACRoleBinding. + + Returns: + Callable[[~.GetScopeRBACRoleBindingRequest], + ~.RBACRoleBinding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_scope_rbac_role_binding" not in self._stubs: + self._stubs[ + "get_scope_rbac_role_binding" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/GetScopeRBACRoleBinding", + request_serializer=service.GetScopeRBACRoleBindingRequest.serialize, + response_deserializer=fleet.RBACRoleBinding.deserialize, + ) + return self._stubs["get_scope_rbac_role_binding"] + + @property + def create_scope_rbac_role_binding( + self, + ) -> Callable[ + [service.CreateScopeRBACRoleBindingRequest], operations_pb2.Operation + ]: + r"""Return a callable for the create scope rbac role binding method over gRPC. + + Creates a Scope RBACRoleBinding. + + Returns: + Callable[[~.CreateScopeRBACRoleBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_scope_rbac_role_binding" not in self._stubs: + self._stubs[ + "create_scope_rbac_role_binding" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/CreateScopeRBACRoleBinding", + request_serializer=service.CreateScopeRBACRoleBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_scope_rbac_role_binding"] + + @property + def update_scope_rbac_role_binding( + self, + ) -> Callable[ + [service.UpdateScopeRBACRoleBindingRequest], operations_pb2.Operation + ]: + r"""Return a callable for the update scope rbac role binding method over gRPC. + + Updates a Scope RBACRoleBinding. + + Returns: + Callable[[~.UpdateScopeRBACRoleBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_scope_rbac_role_binding" not in self._stubs: + self._stubs[ + "update_scope_rbac_role_binding" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/UpdateScopeRBACRoleBinding", + request_serializer=service.UpdateScopeRBACRoleBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_scope_rbac_role_binding"] + + @property + def delete_scope_rbac_role_binding( + self, + ) -> Callable[ + [service.DeleteScopeRBACRoleBindingRequest], operations_pb2.Operation + ]: + r"""Return a callable for the delete scope rbac role binding method over gRPC. + + Deletes a Scope RBACRoleBinding. + + Returns: + Callable[[~.DeleteScopeRBACRoleBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_scope_rbac_role_binding" not in self._stubs: + self._stubs[ + "delete_scope_rbac_role_binding" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/DeleteScopeRBACRoleBinding", + request_serializer=service.DeleteScopeRBACRoleBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_scope_rbac_role_binding"] + + @property + def list_scope_rbac_role_bindings( + self, + ) -> Callable[ + [service.ListScopeRBACRoleBindingsRequest], + service.ListScopeRBACRoleBindingsResponse, + ]: + r"""Return a callable for the list scope rbac role bindings method over gRPC. + + Lists all Scope RBACRoleBindings. + + Returns: + Callable[[~.ListScopeRBACRoleBindingsRequest], + ~.ListScopeRBACRoleBindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_scope_rbac_role_bindings" not in self._stubs: + self._stubs[ + "list_scope_rbac_role_bindings" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/ListScopeRBACRoleBindings", + request_serializer=service.ListScopeRBACRoleBindingsRequest.serialize, + response_deserializer=service.ListScopeRBACRoleBindingsResponse.deserialize, + ) + return self._stubs["list_scope_rbac_role_bindings"] + + @property + def get_scope(self) -> Callable[[service.GetScopeRequest], fleet.Scope]: + r"""Return a callable for the get scope method over gRPC. + + Returns the details of a Scope. + + Returns: + Callable[[~.GetScopeRequest], + ~.Scope]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_scope" not in self._stubs: + self._stubs["get_scope"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/GetScope", + request_serializer=service.GetScopeRequest.serialize, + response_deserializer=fleet.Scope.deserialize, + ) + return self._stubs["get_scope"] + + @property + def create_scope( + self, + ) -> Callable[[service.CreateScopeRequest], operations_pb2.Operation]: + r"""Return a callable for the create scope method over gRPC. + + Creates a Scope. + + Returns: + Callable[[~.CreateScopeRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_scope" not in self._stubs: + self._stubs["create_scope"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/CreateScope", + request_serializer=service.CreateScopeRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_scope"] + + @property + def update_scope( + self, + ) -> Callable[[service.UpdateScopeRequest], operations_pb2.Operation]: + r"""Return a callable for the update scope method over gRPC. + + Updates a scopes. + + Returns: + Callable[[~.UpdateScopeRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_scope" not in self._stubs: + self._stubs["update_scope"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/UpdateScope", + request_serializer=service.UpdateScopeRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_scope"] + + @property + def delete_scope( + self, + ) -> Callable[[service.DeleteScopeRequest], operations_pb2.Operation]: + r"""Return a callable for the delete scope method over gRPC. + + Deletes a Scope. + + Returns: + Callable[[~.DeleteScopeRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_scope" not in self._stubs: + self._stubs["delete_scope"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/DeleteScope", + request_serializer=service.DeleteScopeRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_scope"] + + @property + def list_scopes( + self, + ) -> Callable[[service.ListScopesRequest], service.ListScopesResponse]: + r"""Return a callable for the list scopes method over gRPC. + + Lists Scopes. + + Returns: + Callable[[~.ListScopesRequest], + ~.ListScopesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_scopes" not in self._stubs: + self._stubs["list_scopes"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/ListScopes", + request_serializer=service.ListScopesRequest.serialize, + response_deserializer=service.ListScopesResponse.deserialize, + ) + return self._stubs["list_scopes"] + + @property + def list_permitted_scopes( + self, + ) -> Callable[ + [service.ListPermittedScopesRequest], service.ListPermittedScopesResponse + ]: + r"""Return a callable for the list permitted scopes method over gRPC. + + Lists permitted Scopes. + + Returns: + Callable[[~.ListPermittedScopesRequest], + ~.ListPermittedScopesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_permitted_scopes" not in self._stubs: + self._stubs["list_permitted_scopes"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/ListPermittedScopes", + request_serializer=service.ListPermittedScopesRequest.serialize, + response_deserializer=service.ListPermittedScopesResponse.deserialize, + ) + return self._stubs["list_permitted_scopes"] + + @property + def get_membership_binding( + self, + ) -> Callable[[service.GetMembershipBindingRequest], fleet.MembershipBinding]: + r"""Return a callable for the get membership binding method over gRPC. + + Returns the details of a MembershipBinding. + + Returns: + Callable[[~.GetMembershipBindingRequest], + ~.MembershipBinding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_membership_binding" not in self._stubs: + self._stubs["get_membership_binding"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/GetMembershipBinding", + request_serializer=service.GetMembershipBindingRequest.serialize, + response_deserializer=fleet.MembershipBinding.deserialize, + ) + return self._stubs["get_membership_binding"] + + @property + def create_membership_binding( + self, + ) -> Callable[[service.CreateMembershipBindingRequest], operations_pb2.Operation]: + r"""Return a callable for the create membership binding method over gRPC. + + Creates a MembershipBinding. + + Returns: + Callable[[~.CreateMembershipBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_membership_binding" not in self._stubs: + self._stubs["create_membership_binding"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/CreateMembershipBinding", + request_serializer=service.CreateMembershipBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_membership_binding"] + + @property + def update_membership_binding( + self, + ) -> Callable[[service.UpdateMembershipBindingRequest], operations_pb2.Operation]: + r"""Return a callable for the update membership binding method over gRPC. + + Updates a MembershipBinding. + + Returns: + Callable[[~.UpdateMembershipBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_membership_binding" not in self._stubs: + self._stubs["update_membership_binding"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/UpdateMembershipBinding", + request_serializer=service.UpdateMembershipBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_membership_binding"] + + @property + def delete_membership_binding( + self, + ) -> Callable[[service.DeleteMembershipBindingRequest], operations_pb2.Operation]: + r"""Return a callable for the delete membership binding method over gRPC. + + Deletes a MembershipBinding. + + Returns: + Callable[[~.DeleteMembershipBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_membership_binding" not in self._stubs: + self._stubs["delete_membership_binding"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/DeleteMembershipBinding", + request_serializer=service.DeleteMembershipBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_membership_binding"] + + @property + def list_membership_bindings( + self, + ) -> Callable[ + [service.ListMembershipBindingsRequest], service.ListMembershipBindingsResponse + ]: + r"""Return a callable for the list membership bindings method over gRPC. + + Lists MembershipBindings. + + Returns: + Callable[[~.ListMembershipBindingsRequest], + ~.ListMembershipBindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_membership_bindings" not in self._stubs: + self._stubs["list_membership_bindings"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/ListMembershipBindings", + request_serializer=service.ListMembershipBindingsRequest.serialize, + response_deserializer=service.ListMembershipBindingsResponse.deserialize, + ) + return self._stubs["list_membership_bindings"] + + @property + def get_membership_rbac_role_binding( + self, + ) -> Callable[[service.GetMembershipRBACRoleBindingRequest], fleet.RBACRoleBinding]: + r"""Return a callable for the get membership rbac role + binding method over gRPC. + + Returns the details of a Membership RBACRoleBinding. + + Returns: + Callable[[~.GetMembershipRBACRoleBindingRequest], + ~.RBACRoleBinding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_membership_rbac_role_binding" not in self._stubs: + self._stubs[ + "get_membership_rbac_role_binding" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/GetMembershipRBACRoleBinding", + request_serializer=service.GetMembershipRBACRoleBindingRequest.serialize, + response_deserializer=fleet.RBACRoleBinding.deserialize, + ) + return self._stubs["get_membership_rbac_role_binding"] + + @property + def create_membership_rbac_role_binding( + self, + ) -> Callable[ + [service.CreateMembershipRBACRoleBindingRequest], operations_pb2.Operation + ]: + r"""Return a callable for the create membership rbac role + binding method over gRPC. + + Creates a Membership RBACRoleBinding. + + Returns: + Callable[[~.CreateMembershipRBACRoleBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_membership_rbac_role_binding" not in self._stubs: + self._stubs[ + "create_membership_rbac_role_binding" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/CreateMembershipRBACRoleBinding", + request_serializer=service.CreateMembershipRBACRoleBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_membership_rbac_role_binding"] + + @property + def update_membership_rbac_role_binding( + self, + ) -> Callable[ + [service.UpdateMembershipRBACRoleBindingRequest], operations_pb2.Operation + ]: + r"""Return a callable for the update membership rbac role + binding method over gRPC. + + Updates a Membership RBACRoleBinding. + + Returns: + Callable[[~.UpdateMembershipRBACRoleBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_membership_rbac_role_binding" not in self._stubs: + self._stubs[ + "update_membership_rbac_role_binding" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/UpdateMembershipRBACRoleBinding", + request_serializer=service.UpdateMembershipRBACRoleBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_membership_rbac_role_binding"] + + @property + def delete_membership_rbac_role_binding( + self, + ) -> Callable[ + [service.DeleteMembershipRBACRoleBindingRequest], operations_pb2.Operation + ]: + r"""Return a callable for the delete membership rbac role + binding method over gRPC. + + Deletes a Membership RBACRoleBinding. + + Returns: + Callable[[~.DeleteMembershipRBACRoleBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_membership_rbac_role_binding" not in self._stubs: + self._stubs[ + "delete_membership_rbac_role_binding" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/DeleteMembershipRBACRoleBinding", + request_serializer=service.DeleteMembershipRBACRoleBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_membership_rbac_role_binding"] + + @property + def list_membership_rbac_role_bindings( + self, + ) -> Callable[ + [service.ListMembershipRBACRoleBindingsRequest], + service.ListMembershipRBACRoleBindingsResponse, + ]: + r"""Return a callable for the list membership rbac role + bindings method over gRPC. + + Lists all Membership RBACRoleBindings. + + Returns: + Callable[[~.ListMembershipRBACRoleBindingsRequest], + ~.ListMembershipRBACRoleBindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_membership_rbac_role_bindings" not in self._stubs: + self._stubs[ + "list_membership_rbac_role_bindings" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/ListMembershipRBACRoleBindings", + request_serializer=service.ListMembershipRBACRoleBindingsRequest.serialize, + response_deserializer=service.ListMembershipRBACRoleBindingsResponse.deserialize, + ) + return self._stubs["list_membership_rbac_role_bindings"] + + @property + def generate_membership_rbac_role_binding_yaml( + self, + ) -> Callable[ + [service.GenerateMembershipRBACRoleBindingYAMLRequest], + service.GenerateMembershipRBACRoleBindingYAMLResponse, + ]: + r"""Return a callable for the generate membership rbac role + binding yaml method over gRPC. + + Generates a YAML of the RBAC policies for the + specified RoleBinding and its associated impersonation + resources. + + Returns: + Callable[[~.GenerateMembershipRBACRoleBindingYAMLRequest], + ~.GenerateMembershipRBACRoleBindingYAMLResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_membership_rbac_role_binding_yaml" not in self._stubs: + self._stubs[ + "generate_membership_rbac_role_binding_yaml" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/GenerateMembershipRBACRoleBindingYAML", + request_serializer=service.GenerateMembershipRBACRoleBindingYAMLRequest.serialize, + response_deserializer=service.GenerateMembershipRBACRoleBindingYAMLResponse.deserialize, + ) + return self._stubs["generate_membership_rbac_role_binding_yaml"] + def close(self): self._logged_channel.close() diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/grpc_asyncio.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/grpc_asyncio.py index 2b6e7ff4578e..1c087a21d2db 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/grpc_asyncio.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/grpc_asyncio.py @@ -32,7 +32,7 @@ from grpc.experimental import aio # type: ignore import proto # type: ignore -from google.cloud.gkehub_v1.types import feature, membership, service +from google.cloud.gkehub_v1.types import feature, fleet, membership, service from .base import DEFAULT_CLIENT_INFO, GkeHubTransport from .grpc import GkeHubGrpcTransport @@ -391,6 +391,36 @@ def list_memberships( ) return self._stubs["list_memberships"] + @property + def list_bound_memberships( + self, + ) -> Callable[ + [service.ListBoundMembershipsRequest], + Awaitable[service.ListBoundMembershipsResponse], + ]: + r"""Return a callable for the list bound memberships method over gRPC. + + Lists Memberships bound to a Scope. The response + includes relevant Memberships from all regions. + + Returns: + Callable[[~.ListBoundMembershipsRequest], + Awaitable[~.ListBoundMembershipsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_bound_memberships" not in self._stubs: + self._stubs["list_bound_memberships"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/ListBoundMemberships", + request_serializer=service.ListBoundMembershipsRequest.serialize, + response_deserializer=service.ListBoundMembershipsResponse.deserialize, + ) + return self._stubs["list_bound_memberships"] + @property def list_features( self, @@ -674,61 +704,1137 @@ def generate_connect_manifest( ) return self._stubs["generate_connect_manifest"] - def _prep_wrapped_messages(self, client_info): - """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.list_memberships: self._wrap_method( - self.list_memberships, - default_timeout=None, - client_info=client_info, - ), - self.list_features: self._wrap_method( - self.list_features, - default_timeout=None, - client_info=client_info, - ), - self.get_membership: self._wrap_method( - self.get_membership, - default_timeout=None, - client_info=client_info, - ), - self.get_feature: self._wrap_method( - self.get_feature, - default_timeout=None, - client_info=client_info, - ), - self.create_membership: self._wrap_method( - self.create_membership, - default_timeout=None, - client_info=client_info, - ), - self.create_feature: self._wrap_method( - self.create_feature, - default_timeout=None, - client_info=client_info, - ), - self.delete_membership: self._wrap_method( - self.delete_membership, - default_timeout=None, - client_info=client_info, - ), - self.delete_feature: self._wrap_method( - self.delete_feature, - default_timeout=None, - client_info=client_info, - ), - self.update_membership: self._wrap_method( - self.update_membership, - default_timeout=None, - client_info=client_info, - ), - self.update_feature: self._wrap_method( - self.update_feature, - default_timeout=None, - client_info=client_info, - ), - self.generate_connect_manifest: self._wrap_method( - self.generate_connect_manifest, + @property + def create_fleet( + self, + ) -> Callable[[service.CreateFleetRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create fleet method over gRPC. + + Creates a fleet. + + Returns: + Callable[[~.CreateFleetRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_fleet" not in self._stubs: + self._stubs["create_fleet"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/CreateFleet", + request_serializer=service.CreateFleetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_fleet"] + + @property + def get_fleet(self) -> Callable[[service.GetFleetRequest], Awaitable[fleet.Fleet]]: + r"""Return a callable for the get fleet method over gRPC. + + Returns the details of a fleet. + + Returns: + Callable[[~.GetFleetRequest], + Awaitable[~.Fleet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_fleet" not in self._stubs: + self._stubs["get_fleet"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/GetFleet", + request_serializer=service.GetFleetRequest.serialize, + response_deserializer=fleet.Fleet.deserialize, + ) + return self._stubs["get_fleet"] + + @property + def update_fleet( + self, + ) -> Callable[[service.UpdateFleetRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update fleet method over gRPC. + + Updates a fleet. + + Returns: + Callable[[~.UpdateFleetRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_fleet" not in self._stubs: + self._stubs["update_fleet"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/UpdateFleet", + request_serializer=service.UpdateFleetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_fleet"] + + @property + def delete_fleet( + self, + ) -> Callable[[service.DeleteFleetRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete fleet method over gRPC. + + Removes a Fleet. There must be no memberships + remaining in the Fleet. + + Returns: + Callable[[~.DeleteFleetRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_fleet" not in self._stubs: + self._stubs["delete_fleet"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/DeleteFleet", + request_serializer=service.DeleteFleetRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_fleet"] + + @property + def list_fleets( + self, + ) -> Callable[[service.ListFleetsRequest], Awaitable[service.ListFleetsResponse]]: + r"""Return a callable for the list fleets method over gRPC. + + Returns all fleets within an organization or a + project that the caller has access to. + + Returns: + Callable[[~.ListFleetsRequest], + Awaitable[~.ListFleetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_fleets" not in self._stubs: + self._stubs["list_fleets"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/ListFleets", + request_serializer=service.ListFleetsRequest.serialize, + response_deserializer=service.ListFleetsResponse.deserialize, + ) + return self._stubs["list_fleets"] + + @property + def get_scope_namespace( + self, + ) -> Callable[[service.GetScopeNamespaceRequest], Awaitable[fleet.Namespace]]: + r"""Return a callable for the get scope namespace method over gRPC. + + Returns the details of a fleet namespace. + + Returns: + Callable[[~.GetScopeNamespaceRequest], + Awaitable[~.Namespace]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_scope_namespace" not in self._stubs: + self._stubs["get_scope_namespace"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/GetScopeNamespace", + request_serializer=service.GetScopeNamespaceRequest.serialize, + response_deserializer=fleet.Namespace.deserialize, + ) + return self._stubs["get_scope_namespace"] + + @property + def create_scope_namespace( + self, + ) -> Callable[ + [service.CreateScopeNamespaceRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create scope namespace method over gRPC. + + Creates a fleet namespace. + + Returns: + Callable[[~.CreateScopeNamespaceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_scope_namespace" not in self._stubs: + self._stubs["create_scope_namespace"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/CreateScopeNamespace", + request_serializer=service.CreateScopeNamespaceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_scope_namespace"] + + @property + def update_scope_namespace( + self, + ) -> Callable[ + [service.UpdateScopeNamespaceRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update scope namespace method over gRPC. + + Updates a fleet namespace. + + Returns: + Callable[[~.UpdateScopeNamespaceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_scope_namespace" not in self._stubs: + self._stubs["update_scope_namespace"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/UpdateScopeNamespace", + request_serializer=service.UpdateScopeNamespaceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_scope_namespace"] + + @property + def delete_scope_namespace( + self, + ) -> Callable[ + [service.DeleteScopeNamespaceRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete scope namespace method over gRPC. + + Deletes a fleet namespace. + + Returns: + Callable[[~.DeleteScopeNamespaceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_scope_namespace" not in self._stubs: + self._stubs["delete_scope_namespace"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/DeleteScopeNamespace", + request_serializer=service.DeleteScopeNamespaceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_scope_namespace"] + + @property + def list_scope_namespaces( + self, + ) -> Callable[ + [service.ListScopeNamespacesRequest], + Awaitable[service.ListScopeNamespacesResponse], + ]: + r"""Return a callable for the list scope namespaces method over gRPC. + + Lists fleet namespaces. + + Returns: + Callable[[~.ListScopeNamespacesRequest], + Awaitable[~.ListScopeNamespacesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_scope_namespaces" not in self._stubs: + self._stubs["list_scope_namespaces"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/ListScopeNamespaces", + request_serializer=service.ListScopeNamespacesRequest.serialize, + response_deserializer=service.ListScopeNamespacesResponse.deserialize, + ) + return self._stubs["list_scope_namespaces"] + + @property + def get_scope_rbac_role_binding( + self, + ) -> Callable[ + [service.GetScopeRBACRoleBindingRequest], Awaitable[fleet.RBACRoleBinding] + ]: + r"""Return a callable for the get scope rbac role binding method over gRPC. + + Returns the details of a Scope RBACRoleBinding. + + Returns: + Callable[[~.GetScopeRBACRoleBindingRequest], + Awaitable[~.RBACRoleBinding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_scope_rbac_role_binding" not in self._stubs: + self._stubs[ + "get_scope_rbac_role_binding" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/GetScopeRBACRoleBinding", + request_serializer=service.GetScopeRBACRoleBindingRequest.serialize, + response_deserializer=fleet.RBACRoleBinding.deserialize, + ) + return self._stubs["get_scope_rbac_role_binding"] + + @property + def create_scope_rbac_role_binding( + self, + ) -> Callable[ + [service.CreateScopeRBACRoleBindingRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create scope rbac role binding method over gRPC. + + Creates a Scope RBACRoleBinding. + + Returns: + Callable[[~.CreateScopeRBACRoleBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_scope_rbac_role_binding" not in self._stubs: + self._stubs[ + "create_scope_rbac_role_binding" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/CreateScopeRBACRoleBinding", + request_serializer=service.CreateScopeRBACRoleBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_scope_rbac_role_binding"] + + @property + def update_scope_rbac_role_binding( + self, + ) -> Callable[ + [service.UpdateScopeRBACRoleBindingRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update scope rbac role binding method over gRPC. + + Updates a Scope RBACRoleBinding. + + Returns: + Callable[[~.UpdateScopeRBACRoleBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_scope_rbac_role_binding" not in self._stubs: + self._stubs[ + "update_scope_rbac_role_binding" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/UpdateScopeRBACRoleBinding", + request_serializer=service.UpdateScopeRBACRoleBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_scope_rbac_role_binding"] + + @property + def delete_scope_rbac_role_binding( + self, + ) -> Callable[ + [service.DeleteScopeRBACRoleBindingRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete scope rbac role binding method over gRPC. + + Deletes a Scope RBACRoleBinding. + + Returns: + Callable[[~.DeleteScopeRBACRoleBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_scope_rbac_role_binding" not in self._stubs: + self._stubs[ + "delete_scope_rbac_role_binding" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/DeleteScopeRBACRoleBinding", + request_serializer=service.DeleteScopeRBACRoleBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_scope_rbac_role_binding"] + + @property + def list_scope_rbac_role_bindings( + self, + ) -> Callable[ + [service.ListScopeRBACRoleBindingsRequest], + Awaitable[service.ListScopeRBACRoleBindingsResponse], + ]: + r"""Return a callable for the list scope rbac role bindings method over gRPC. + + Lists all Scope RBACRoleBindings. + + Returns: + Callable[[~.ListScopeRBACRoleBindingsRequest], + Awaitable[~.ListScopeRBACRoleBindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_scope_rbac_role_bindings" not in self._stubs: + self._stubs[ + "list_scope_rbac_role_bindings" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/ListScopeRBACRoleBindings", + request_serializer=service.ListScopeRBACRoleBindingsRequest.serialize, + response_deserializer=service.ListScopeRBACRoleBindingsResponse.deserialize, + ) + return self._stubs["list_scope_rbac_role_bindings"] + + @property + def get_scope(self) -> Callable[[service.GetScopeRequest], Awaitable[fleet.Scope]]: + r"""Return a callable for the get scope method over gRPC. + + Returns the details of a Scope. + + Returns: + Callable[[~.GetScopeRequest], + Awaitable[~.Scope]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_scope" not in self._stubs: + self._stubs["get_scope"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/GetScope", + request_serializer=service.GetScopeRequest.serialize, + response_deserializer=fleet.Scope.deserialize, + ) + return self._stubs["get_scope"] + + @property + def create_scope( + self, + ) -> Callable[[service.CreateScopeRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create scope method over gRPC. + + Creates a Scope. + + Returns: + Callable[[~.CreateScopeRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_scope" not in self._stubs: + self._stubs["create_scope"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/CreateScope", + request_serializer=service.CreateScopeRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_scope"] + + @property + def update_scope( + self, + ) -> Callable[[service.UpdateScopeRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update scope method over gRPC. + + Updates a scopes. + + Returns: + Callable[[~.UpdateScopeRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_scope" not in self._stubs: + self._stubs["update_scope"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/UpdateScope", + request_serializer=service.UpdateScopeRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_scope"] + + @property + def delete_scope( + self, + ) -> Callable[[service.DeleteScopeRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete scope method over gRPC. + + Deletes a Scope. + + Returns: + Callable[[~.DeleteScopeRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_scope" not in self._stubs: + self._stubs["delete_scope"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/DeleteScope", + request_serializer=service.DeleteScopeRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_scope"] + + @property + def list_scopes( + self, + ) -> Callable[[service.ListScopesRequest], Awaitable[service.ListScopesResponse]]: + r"""Return a callable for the list scopes method over gRPC. + + Lists Scopes. + + Returns: + Callable[[~.ListScopesRequest], + Awaitable[~.ListScopesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_scopes" not in self._stubs: + self._stubs["list_scopes"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/ListScopes", + request_serializer=service.ListScopesRequest.serialize, + response_deserializer=service.ListScopesResponse.deserialize, + ) + return self._stubs["list_scopes"] + + @property + def list_permitted_scopes( + self, + ) -> Callable[ + [service.ListPermittedScopesRequest], + Awaitable[service.ListPermittedScopesResponse], + ]: + r"""Return a callable for the list permitted scopes method over gRPC. + + Lists permitted Scopes. + + Returns: + Callable[[~.ListPermittedScopesRequest], + Awaitable[~.ListPermittedScopesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_permitted_scopes" not in self._stubs: + self._stubs["list_permitted_scopes"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/ListPermittedScopes", + request_serializer=service.ListPermittedScopesRequest.serialize, + response_deserializer=service.ListPermittedScopesResponse.deserialize, + ) + return self._stubs["list_permitted_scopes"] + + @property + def get_membership_binding( + self, + ) -> Callable[ + [service.GetMembershipBindingRequest], Awaitable[fleet.MembershipBinding] + ]: + r"""Return a callable for the get membership binding method over gRPC. + + Returns the details of a MembershipBinding. + + Returns: + Callable[[~.GetMembershipBindingRequest], + Awaitable[~.MembershipBinding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_membership_binding" not in self._stubs: + self._stubs["get_membership_binding"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/GetMembershipBinding", + request_serializer=service.GetMembershipBindingRequest.serialize, + response_deserializer=fleet.MembershipBinding.deserialize, + ) + return self._stubs["get_membership_binding"] + + @property + def create_membership_binding( + self, + ) -> Callable[ + [service.CreateMembershipBindingRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create membership binding method over gRPC. + + Creates a MembershipBinding. + + Returns: + Callable[[~.CreateMembershipBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_membership_binding" not in self._stubs: + self._stubs["create_membership_binding"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/CreateMembershipBinding", + request_serializer=service.CreateMembershipBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_membership_binding"] + + @property + def update_membership_binding( + self, + ) -> Callable[ + [service.UpdateMembershipBindingRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the update membership binding method over gRPC. + + Updates a MembershipBinding. + + Returns: + Callable[[~.UpdateMembershipBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_membership_binding" not in self._stubs: + self._stubs["update_membership_binding"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/UpdateMembershipBinding", + request_serializer=service.UpdateMembershipBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_membership_binding"] + + @property + def delete_membership_binding( + self, + ) -> Callable[ + [service.DeleteMembershipBindingRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete membership binding method over gRPC. + + Deletes a MembershipBinding. + + Returns: + Callable[[~.DeleteMembershipBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_membership_binding" not in self._stubs: + self._stubs["delete_membership_binding"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/DeleteMembershipBinding", + request_serializer=service.DeleteMembershipBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_membership_binding"] + + @property + def list_membership_bindings( + self, + ) -> Callable[ + [service.ListMembershipBindingsRequest], + Awaitable[service.ListMembershipBindingsResponse], + ]: + r"""Return a callable for the list membership bindings method over gRPC. + + Lists MembershipBindings. + + Returns: + Callable[[~.ListMembershipBindingsRequest], + Awaitable[~.ListMembershipBindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_membership_bindings" not in self._stubs: + self._stubs["list_membership_bindings"] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/ListMembershipBindings", + request_serializer=service.ListMembershipBindingsRequest.serialize, + response_deserializer=service.ListMembershipBindingsResponse.deserialize, + ) + return self._stubs["list_membership_bindings"] + + @property + def get_membership_rbac_role_binding( + self, + ) -> Callable[ + [service.GetMembershipRBACRoleBindingRequest], Awaitable[fleet.RBACRoleBinding] + ]: + r"""Return a callable for the get membership rbac role + binding method over gRPC. + + Returns the details of a Membership RBACRoleBinding. + + Returns: + Callable[[~.GetMembershipRBACRoleBindingRequest], + Awaitable[~.RBACRoleBinding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_membership_rbac_role_binding" not in self._stubs: + self._stubs[ + "get_membership_rbac_role_binding" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/GetMembershipRBACRoleBinding", + request_serializer=service.GetMembershipRBACRoleBindingRequest.serialize, + response_deserializer=fleet.RBACRoleBinding.deserialize, + ) + return self._stubs["get_membership_rbac_role_binding"] + + @property + def create_membership_rbac_role_binding( + self, + ) -> Callable[ + [service.CreateMembershipRBACRoleBindingRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create membership rbac role + binding method over gRPC. + + Creates a Membership RBACRoleBinding. + + Returns: + Callable[[~.CreateMembershipRBACRoleBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_membership_rbac_role_binding" not in self._stubs: + self._stubs[ + "create_membership_rbac_role_binding" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/CreateMembershipRBACRoleBinding", + request_serializer=service.CreateMembershipRBACRoleBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_membership_rbac_role_binding"] + + @property + def update_membership_rbac_role_binding( + self, + ) -> Callable[ + [service.UpdateMembershipRBACRoleBindingRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the update membership rbac role + binding method over gRPC. + + Updates a Membership RBACRoleBinding. + + Returns: + Callable[[~.UpdateMembershipRBACRoleBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_membership_rbac_role_binding" not in self._stubs: + self._stubs[ + "update_membership_rbac_role_binding" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/UpdateMembershipRBACRoleBinding", + request_serializer=service.UpdateMembershipRBACRoleBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_membership_rbac_role_binding"] + + @property + def delete_membership_rbac_role_binding( + self, + ) -> Callable[ + [service.DeleteMembershipRBACRoleBindingRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete membership rbac role + binding method over gRPC. + + Deletes a Membership RBACRoleBinding. + + Returns: + Callable[[~.DeleteMembershipRBACRoleBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_membership_rbac_role_binding" not in self._stubs: + self._stubs[ + "delete_membership_rbac_role_binding" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/DeleteMembershipRBACRoleBinding", + request_serializer=service.DeleteMembershipRBACRoleBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_membership_rbac_role_binding"] + + @property + def list_membership_rbac_role_bindings( + self, + ) -> Callable[ + [service.ListMembershipRBACRoleBindingsRequest], + Awaitable[service.ListMembershipRBACRoleBindingsResponse], + ]: + r"""Return a callable for the list membership rbac role + bindings method over gRPC. + + Lists all Membership RBACRoleBindings. + + Returns: + Callable[[~.ListMembershipRBACRoleBindingsRequest], + Awaitable[~.ListMembershipRBACRoleBindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_membership_rbac_role_bindings" not in self._stubs: + self._stubs[ + "list_membership_rbac_role_bindings" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/ListMembershipRBACRoleBindings", + request_serializer=service.ListMembershipRBACRoleBindingsRequest.serialize, + response_deserializer=service.ListMembershipRBACRoleBindingsResponse.deserialize, + ) + return self._stubs["list_membership_rbac_role_bindings"] + + @property + def generate_membership_rbac_role_binding_yaml( + self, + ) -> Callable[ + [service.GenerateMembershipRBACRoleBindingYAMLRequest], + Awaitable[service.GenerateMembershipRBACRoleBindingYAMLResponse], + ]: + r"""Return a callable for the generate membership rbac role + binding yaml method over gRPC. + + Generates a YAML of the RBAC policies for the + specified RoleBinding and its associated impersonation + resources. + + Returns: + Callable[[~.GenerateMembershipRBACRoleBindingYAMLRequest], + Awaitable[~.GenerateMembershipRBACRoleBindingYAMLResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_membership_rbac_role_binding_yaml" not in self._stubs: + self._stubs[ + "generate_membership_rbac_role_binding_yaml" + ] = self._logged_channel.unary_unary( + "/google.cloud.gkehub.v1.GkeHub/GenerateMembershipRBACRoleBindingYAML", + request_serializer=service.GenerateMembershipRBACRoleBindingYAMLRequest.serialize, + response_deserializer=service.GenerateMembershipRBACRoleBindingYAMLResponse.deserialize, + ) + return self._stubs["generate_membership_rbac_role_binding_yaml"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_memberships: self._wrap_method( + self.list_memberships, + default_timeout=None, + client_info=client_info, + ), + self.list_bound_memberships: self._wrap_method( + self.list_bound_memberships, + default_timeout=None, + client_info=client_info, + ), + self.list_features: self._wrap_method( + self.list_features, + default_timeout=None, + client_info=client_info, + ), + self.get_membership: self._wrap_method( + self.get_membership, + default_timeout=None, + client_info=client_info, + ), + self.get_feature: self._wrap_method( + self.get_feature, + default_timeout=None, + client_info=client_info, + ), + self.create_membership: self._wrap_method( + self.create_membership, + default_timeout=None, + client_info=client_info, + ), + self.create_feature: self._wrap_method( + self.create_feature, + default_timeout=None, + client_info=client_info, + ), + self.delete_membership: self._wrap_method( + self.delete_membership, + default_timeout=None, + client_info=client_info, + ), + self.delete_feature: self._wrap_method( + self.delete_feature, + default_timeout=None, + client_info=client_info, + ), + self.update_membership: self._wrap_method( + self.update_membership, + default_timeout=None, + client_info=client_info, + ), + self.update_feature: self._wrap_method( + self.update_feature, + default_timeout=None, + client_info=client_info, + ), + self.generate_connect_manifest: self._wrap_method( + self.generate_connect_manifest, + default_timeout=None, + client_info=client_info, + ), + self.create_fleet: self._wrap_method( + self.create_fleet, + default_timeout=None, + client_info=client_info, + ), + self.get_fleet: self._wrap_method( + self.get_fleet, + default_timeout=None, + client_info=client_info, + ), + self.update_fleet: self._wrap_method( + self.update_fleet, + default_timeout=None, + client_info=client_info, + ), + self.delete_fleet: self._wrap_method( + self.delete_fleet, + default_timeout=None, + client_info=client_info, + ), + self.list_fleets: self._wrap_method( + self.list_fleets, + default_timeout=None, + client_info=client_info, + ), + self.get_scope_namespace: self._wrap_method( + self.get_scope_namespace, + default_timeout=None, + client_info=client_info, + ), + self.create_scope_namespace: self._wrap_method( + self.create_scope_namespace, + default_timeout=None, + client_info=client_info, + ), + self.update_scope_namespace: self._wrap_method( + self.update_scope_namespace, + default_timeout=None, + client_info=client_info, + ), + self.delete_scope_namespace: self._wrap_method( + self.delete_scope_namespace, + default_timeout=None, + client_info=client_info, + ), + self.list_scope_namespaces: self._wrap_method( + self.list_scope_namespaces, + default_timeout=None, + client_info=client_info, + ), + self.get_scope_rbac_role_binding: self._wrap_method( + self.get_scope_rbac_role_binding, + default_timeout=None, + client_info=client_info, + ), + self.create_scope_rbac_role_binding: self._wrap_method( + self.create_scope_rbac_role_binding, + default_timeout=None, + client_info=client_info, + ), + self.update_scope_rbac_role_binding: self._wrap_method( + self.update_scope_rbac_role_binding, + default_timeout=None, + client_info=client_info, + ), + self.delete_scope_rbac_role_binding: self._wrap_method( + self.delete_scope_rbac_role_binding, + default_timeout=None, + client_info=client_info, + ), + self.list_scope_rbac_role_bindings: self._wrap_method( + self.list_scope_rbac_role_bindings, + default_timeout=None, + client_info=client_info, + ), + self.get_scope: self._wrap_method( + self.get_scope, + default_timeout=None, + client_info=client_info, + ), + self.create_scope: self._wrap_method( + self.create_scope, + default_timeout=None, + client_info=client_info, + ), + self.update_scope: self._wrap_method( + self.update_scope, + default_timeout=None, + client_info=client_info, + ), + self.delete_scope: self._wrap_method( + self.delete_scope, + default_timeout=None, + client_info=client_info, + ), + self.list_scopes: self._wrap_method( + self.list_scopes, + default_timeout=None, + client_info=client_info, + ), + self.list_permitted_scopes: self._wrap_method( + self.list_permitted_scopes, + default_timeout=None, + client_info=client_info, + ), + self.get_membership_binding: self._wrap_method( + self.get_membership_binding, + default_timeout=None, + client_info=client_info, + ), + self.create_membership_binding: self._wrap_method( + self.create_membership_binding, + default_timeout=None, + client_info=client_info, + ), + self.update_membership_binding: self._wrap_method( + self.update_membership_binding, + default_timeout=None, + client_info=client_info, + ), + self.delete_membership_binding: self._wrap_method( + self.delete_membership_binding, + default_timeout=None, + client_info=client_info, + ), + self.list_membership_bindings: self._wrap_method( + self.list_membership_bindings, + default_timeout=None, + client_info=client_info, + ), + self.get_membership_rbac_role_binding: self._wrap_method( + self.get_membership_rbac_role_binding, + default_timeout=None, + client_info=client_info, + ), + self.create_membership_rbac_role_binding: self._wrap_method( + self.create_membership_rbac_role_binding, + default_timeout=None, + client_info=client_info, + ), + self.update_membership_rbac_role_binding: self._wrap_method( + self.update_membership_rbac_role_binding, + default_timeout=None, + client_info=client_info, + ), + self.delete_membership_rbac_role_binding: self._wrap_method( + self.delete_membership_rbac_role_binding, + default_timeout=None, + client_info=client_info, + ), + self.list_membership_rbac_role_bindings: self._wrap_method( + self.list_membership_rbac_role_bindings, + default_timeout=None, + client_info=client_info, + ), + self.generate_membership_rbac_role_binding_yaml: self._wrap_method( + self.generate_membership_rbac_role_binding_yaml, default_timeout=None, client_info=client_info, ), diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/rest.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/rest.py index b0e3ca247b59..27bde04407ae 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/rest.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/rest.py @@ -29,7 +29,7 @@ from google.protobuf import json_format from requests import __version__ as requests_version -from google.cloud.gkehub_v1.types import feature, membership, service +from google.cloud.gkehub_v1.types import feature, fleet, membership, service from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO from .rest_base import _BaseGkeHubRestTransport @@ -81,6 +81,14 @@ def post_create_feature(self, response): logging.log(f"Received response: {response}") return response + def pre_create_fleet(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_fleet(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_membership(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -89,6 +97,46 @@ def post_create_membership(self, response): logging.log(f"Received response: {response}") return response + def pre_create_membership_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_membership_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_membership_rbac_role_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_membership_rbac_role_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_scope(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_scope(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_scope_namespace(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_scope_namespace(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_scope_rbac_role_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_scope_rbac_role_binding(self, response): + logging.log(f"Received response: {response}") + return response + def pre_delete_feature(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -97,6 +145,14 @@ def post_delete_feature(self, response): logging.log(f"Received response: {response}") return response + def pre_delete_fleet(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_fleet(self, response): + logging.log(f"Received response: {response}") + return response + def pre_delete_membership(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -105,6 +161,46 @@ def post_delete_membership(self, response): logging.log(f"Received response: {response}") return response + def pre_delete_membership_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_membership_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_membership_rbac_role_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_membership_rbac_role_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_scope(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_scope(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_scope_namespace(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_scope_namespace(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_scope_rbac_role_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_scope_rbac_role_binding(self, response): + logging.log(f"Received response: {response}") + return response + def pre_generate_connect_manifest(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -113,6 +209,14 @@ def post_generate_connect_manifest(self, response): logging.log(f"Received response: {response}") return response + def pre_generate_membership_rbac_role_binding_yaml(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_membership_rbac_role_binding_yaml(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_feature(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -121,6 +225,14 @@ def post_get_feature(self, response): logging.log(f"Received response: {response}") return response + def pre_get_fleet(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_fleet(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_membership(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -129,6 +241,54 @@ def post_get_membership(self, response): logging.log(f"Received response: {response}") return response + def pre_get_membership_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_membership_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_membership_rbac_role_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_membership_rbac_role_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_scope(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_scope(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_scope_namespace(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_scope_namespace(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_scope_rbac_role_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_scope_rbac_role_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_bound_memberships(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_bound_memberships(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_features(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -137,6 +297,30 @@ def post_list_features(self, response): logging.log(f"Received response: {response}") return response + def pre_list_fleets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_fleets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_membership_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_membership_bindings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_membership_rbac_role_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_membership_rbac_role_bindings(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_memberships(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -145,6 +329,38 @@ def post_list_memberships(self, response): logging.log(f"Received response: {response}") return response + def pre_list_permitted_scopes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_permitted_scopes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_scope_namespaces(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_scope_namespaces(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_scope_rbac_role_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_scope_rbac_role_bindings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_scopes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_scopes(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_feature(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -153,6 +369,14 @@ def post_update_feature(self, response): logging.log(f"Received response: {response}") return response + def pre_update_fleet(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_fleet(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_membership(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -161,6 +385,46 @@ def post_update_membership(self, response): logging.log(f"Received response: {response}") return response + def pre_update_membership_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_membership_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_membership_rbac_role_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_membership_rbac_role_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_scope(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_scope(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_scope_namespace(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_scope_namespace(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_scope_rbac_role_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_scope_rbac_role_binding(self, response): + logging.log(f"Received response: {response}") + return response + transport = GkeHubRestTransport(interceptor=MyCustomGkeHubInterceptor()) client = GkeHubClient(transport=transport) @@ -213,6 +477,52 @@ def post_create_feature_with_metadata( """ return response, metadata + def pre_create_fleet( + self, + request: service.CreateFleetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.CreateFleetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_fleet + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_create_fleet( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_fleet + + DEPRECATED. Please use the `post_create_fleet_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_create_fleet` interceptor runs + before the `post_create_fleet_with_metadata` interceptor. + """ + return response + + def post_create_fleet_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_fleet + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_create_fleet_with_metadata` + interceptor in new development instead of the `post_create_fleet` interceptor. + When both interceptors are used, this `post_create_fleet_with_metadata` interceptor runs after the + `post_create_fleet` interceptor. The (possibly modified) response returned by + `post_create_fleet` will be passed to + `post_create_fleet_with_metadata`. + """ + return response, metadata + def pre_create_membership( self, request: service.CreateMembershipRequest, @@ -261,589 +571,7118 @@ def post_create_membership_with_metadata( """ return response, metadata - def pre_delete_feature( + def pre_create_membership_binding( self, - request: service.DeleteFeatureRequest, + request: service.CreateMembershipBindingRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[service.DeleteFeatureRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_feature + ) -> Tuple[ + service.CreateMembershipBindingRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_membership_binding Override in a subclass to manipulate the request or metadata before they are sent to the GkeHub server. """ return request, metadata - def post_delete_feature( + def post_create_membership_binding( self, response: operations_pb2.Operation ) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_feature + """Post-rpc interceptor for create_membership_binding - DEPRECATED. Please use the `post_delete_feature_with_metadata` + DEPRECATED. Please use the `post_create_membership_binding_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the GkeHub server but before - it is returned to user code. This `post_delete_feature` interceptor runs - before the `post_delete_feature_with_metadata` interceptor. + it is returned to user code. This `post_create_membership_binding` interceptor runs + before the `post_create_membership_binding_with_metadata` interceptor. """ return response - def post_delete_feature_with_metadata( + def post_create_membership_binding_with_metadata( self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for delete_feature + """Post-rpc interceptor for create_membership_binding Override in a subclass to read or manipulate the response or metadata after it is returned by the GkeHub server but before it is returned to user code. - We recommend only using this `post_delete_feature_with_metadata` - interceptor in new development instead of the `post_delete_feature` interceptor. - When both interceptors are used, this `post_delete_feature_with_metadata` interceptor runs after the - `post_delete_feature` interceptor. The (possibly modified) response returned by - `post_delete_feature` will be passed to - `post_delete_feature_with_metadata`. + We recommend only using this `post_create_membership_binding_with_metadata` + interceptor in new development instead of the `post_create_membership_binding` interceptor. + When both interceptors are used, this `post_create_membership_binding_with_metadata` interceptor runs after the + `post_create_membership_binding` interceptor. The (possibly modified) response returned by + `post_create_membership_binding` will be passed to + `post_create_membership_binding_with_metadata`. """ return response, metadata - def pre_delete_membership( + def pre_create_membership_rbac_role_binding( self, - request: service.DeleteMembershipRequest, + request: service.CreateMembershipRBACRoleBindingRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - service.DeleteMembershipRequest, Sequence[Tuple[str, Union[str, bytes]]] + service.CreateMembershipRBACRoleBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for delete_membership + """Pre-rpc interceptor for create_membership_rbac_role_binding Override in a subclass to manipulate the request or metadata before they are sent to the GkeHub server. """ return request, metadata - def post_delete_membership( + def post_create_membership_rbac_role_binding( self, response: operations_pb2.Operation ) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_membership + """Post-rpc interceptor for create_membership_rbac_role_binding - DEPRECATED. Please use the `post_delete_membership_with_metadata` + DEPRECATED. Please use the `post_create_membership_rbac_role_binding_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the GkeHub server but before - it is returned to user code. This `post_delete_membership` interceptor runs - before the `post_delete_membership_with_metadata` interceptor. + it is returned to user code. This `post_create_membership_rbac_role_binding` interceptor runs + before the `post_create_membership_rbac_role_binding_with_metadata` interceptor. """ return response - def post_delete_membership_with_metadata( + def post_create_membership_rbac_role_binding_with_metadata( self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for delete_membership + """Post-rpc interceptor for create_membership_rbac_role_binding Override in a subclass to read or manipulate the response or metadata after it is returned by the GkeHub server but before it is returned to user code. - We recommend only using this `post_delete_membership_with_metadata` - interceptor in new development instead of the `post_delete_membership` interceptor. - When both interceptors are used, this `post_delete_membership_with_metadata` interceptor runs after the - `post_delete_membership` interceptor. The (possibly modified) response returned by - `post_delete_membership` will be passed to - `post_delete_membership_with_metadata`. + We recommend only using this `post_create_membership_rbac_role_binding_with_metadata` + interceptor in new development instead of the `post_create_membership_rbac_role_binding` interceptor. + When both interceptors are used, this `post_create_membership_rbac_role_binding_with_metadata` interceptor runs after the + `post_create_membership_rbac_role_binding` interceptor. The (possibly modified) response returned by + `post_create_membership_rbac_role_binding` will be passed to + `post_create_membership_rbac_role_binding_with_metadata`. """ return response, metadata - def pre_generate_connect_manifest( + def pre_create_scope( self, - request: service.GenerateConnectManifestRequest, + request: service.CreateScopeRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - service.GenerateConnectManifestRequest, Sequence[Tuple[str, Union[str, bytes]]] - ]: - """Pre-rpc interceptor for generate_connect_manifest + ) -> Tuple[service.CreateScopeRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_scope Override in a subclass to manipulate the request or metadata before they are sent to the GkeHub server. """ return request, metadata - def post_generate_connect_manifest( - self, response: service.GenerateConnectManifestResponse - ) -> service.GenerateConnectManifestResponse: - """Post-rpc interceptor for generate_connect_manifest + def post_create_scope( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_scope - DEPRECATED. Please use the `post_generate_connect_manifest_with_metadata` + DEPRECATED. Please use the `post_create_scope_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the GkeHub server but before - it is returned to user code. This `post_generate_connect_manifest` interceptor runs - before the `post_generate_connect_manifest_with_metadata` interceptor. + it is returned to user code. This `post_create_scope` interceptor runs + before the `post_create_scope_with_metadata` interceptor. """ return response - def post_generate_connect_manifest_with_metadata( + def post_create_scope_with_metadata( self, - response: service.GenerateConnectManifestResponse, + response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - service.GenerateConnectManifestResponse, Sequence[Tuple[str, Union[str, bytes]]] - ]: - """Post-rpc interceptor for generate_connect_manifest + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_scope Override in a subclass to read or manipulate the response or metadata after it is returned by the GkeHub server but before it is returned to user code. - We recommend only using this `post_generate_connect_manifest_with_metadata` - interceptor in new development instead of the `post_generate_connect_manifest` interceptor. - When both interceptors are used, this `post_generate_connect_manifest_with_metadata` interceptor runs after the - `post_generate_connect_manifest` interceptor. The (possibly modified) response returned by - `post_generate_connect_manifest` will be passed to - `post_generate_connect_manifest_with_metadata`. + We recommend only using this `post_create_scope_with_metadata` + interceptor in new development instead of the `post_create_scope` interceptor. + When both interceptors are used, this `post_create_scope_with_metadata` interceptor runs after the + `post_create_scope` interceptor. The (possibly modified) response returned by + `post_create_scope` will be passed to + `post_create_scope_with_metadata`. """ return response, metadata - def pre_get_feature( + def pre_create_scope_namespace( self, - request: service.GetFeatureRequest, + request: service.CreateScopeNamespaceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[service.GetFeatureRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_feature + ) -> Tuple[ + service.CreateScopeNamespaceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_scope_namespace Override in a subclass to manipulate the request or metadata before they are sent to the GkeHub server. """ return request, metadata - def post_get_feature(self, response: feature.Feature) -> feature.Feature: - """Post-rpc interceptor for get_feature + def post_create_scope_namespace( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_scope_namespace - DEPRECATED. Please use the `post_get_feature_with_metadata` + DEPRECATED. Please use the `post_create_scope_namespace_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the GkeHub server but before - it is returned to user code. This `post_get_feature` interceptor runs - before the `post_get_feature_with_metadata` interceptor. + it is returned to user code. This `post_create_scope_namespace` interceptor runs + before the `post_create_scope_namespace_with_metadata` interceptor. """ return response - def post_get_feature_with_metadata( + def post_create_scope_namespace_with_metadata( self, - response: feature.Feature, + response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[feature.Feature, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_feature + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_scope_namespace Override in a subclass to read or manipulate the response or metadata after it is returned by the GkeHub server but before it is returned to user code. - We recommend only using this `post_get_feature_with_metadata` - interceptor in new development instead of the `post_get_feature` interceptor. - When both interceptors are used, this `post_get_feature_with_metadata` interceptor runs after the - `post_get_feature` interceptor. The (possibly modified) response returned by - `post_get_feature` will be passed to - `post_get_feature_with_metadata`. + We recommend only using this `post_create_scope_namespace_with_metadata` + interceptor in new development instead of the `post_create_scope_namespace` interceptor. + When both interceptors are used, this `post_create_scope_namespace_with_metadata` interceptor runs after the + `post_create_scope_namespace` interceptor. The (possibly modified) response returned by + `post_create_scope_namespace` will be passed to + `post_create_scope_namespace_with_metadata`. """ return response, metadata - def pre_get_membership( + def pre_create_scope_rbac_role_binding( self, - request: service.GetMembershipRequest, + request: service.CreateScopeRBACRoleBindingRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[service.GetMembershipRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_membership + ) -> Tuple[ + service.CreateScopeRBACRoleBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_scope_rbac_role_binding Override in a subclass to manipulate the request or metadata before they are sent to the GkeHub server. """ return request, metadata - def post_get_membership( - self, response: membership.Membership - ) -> membership.Membership: - """Post-rpc interceptor for get_membership + def post_create_scope_rbac_role_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_scope_rbac_role_binding - DEPRECATED. Please use the `post_get_membership_with_metadata` + DEPRECATED. Please use the `post_create_scope_rbac_role_binding_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the GkeHub server but before - it is returned to user code. This `post_get_membership` interceptor runs - before the `post_get_membership_with_metadata` interceptor. + it is returned to user code. This `post_create_scope_rbac_role_binding` interceptor runs + before the `post_create_scope_rbac_role_binding_with_metadata` interceptor. """ return response - def post_get_membership_with_metadata( + def post_create_scope_rbac_role_binding_with_metadata( self, - response: membership.Membership, + response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[membership.Membership, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_membership + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_scope_rbac_role_binding Override in a subclass to read or manipulate the response or metadata after it is returned by the GkeHub server but before it is returned to user code. - We recommend only using this `post_get_membership_with_metadata` - interceptor in new development instead of the `post_get_membership` interceptor. - When both interceptors are used, this `post_get_membership_with_metadata` interceptor runs after the - `post_get_membership` interceptor. The (possibly modified) response returned by - `post_get_membership` will be passed to - `post_get_membership_with_metadata`. + We recommend only using this `post_create_scope_rbac_role_binding_with_metadata` + interceptor in new development instead of the `post_create_scope_rbac_role_binding` interceptor. + When both interceptors are used, this `post_create_scope_rbac_role_binding_with_metadata` interceptor runs after the + `post_create_scope_rbac_role_binding` interceptor. The (possibly modified) response returned by + `post_create_scope_rbac_role_binding` will be passed to + `post_create_scope_rbac_role_binding_with_metadata`. """ return response, metadata - def pre_list_features( + def pre_delete_feature( self, - request: service.ListFeaturesRequest, + request: service.DeleteFeatureRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[service.ListFeaturesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_features + ) -> Tuple[service.DeleteFeatureRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_feature Override in a subclass to manipulate the request or metadata before they are sent to the GkeHub server. """ return request, metadata - def post_list_features( - self, response: service.ListFeaturesResponse - ) -> service.ListFeaturesResponse: - """Post-rpc interceptor for list_features + def post_delete_feature( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_feature - DEPRECATED. Please use the `post_list_features_with_metadata` + DEPRECATED. Please use the `post_delete_feature_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the GkeHub server but before - it is returned to user code. This `post_list_features` interceptor runs - before the `post_list_features_with_metadata` interceptor. + it is returned to user code. This `post_delete_feature` interceptor runs + before the `post_delete_feature_with_metadata` interceptor. """ return response - def post_list_features_with_metadata( + def post_delete_feature_with_metadata( self, - response: service.ListFeaturesResponse, + response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[service.ListFeaturesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_features + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_feature Override in a subclass to read or manipulate the response or metadata after it is returned by the GkeHub server but before it is returned to user code. - We recommend only using this `post_list_features_with_metadata` - interceptor in new development instead of the `post_list_features` interceptor. - When both interceptors are used, this `post_list_features_with_metadata` interceptor runs after the - `post_list_features` interceptor. The (possibly modified) response returned by - `post_list_features` will be passed to - `post_list_features_with_metadata`. + We recommend only using this `post_delete_feature_with_metadata` + interceptor in new development instead of the `post_delete_feature` interceptor. + When both interceptors are used, this `post_delete_feature_with_metadata` interceptor runs after the + `post_delete_feature` interceptor. The (possibly modified) response returned by + `post_delete_feature` will be passed to + `post_delete_feature_with_metadata`. """ return response, metadata - def pre_list_memberships( + def pre_delete_fleet( self, - request: service.ListMembershipsRequest, + request: service.DeleteFleetRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[service.ListMembershipsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_memberships + ) -> Tuple[service.DeleteFleetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_fleet Override in a subclass to manipulate the request or metadata before they are sent to the GkeHub server. """ return request, metadata - def post_list_memberships( - self, response: service.ListMembershipsResponse - ) -> service.ListMembershipsResponse: - """Post-rpc interceptor for list_memberships + def post_delete_fleet( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_fleet - DEPRECATED. Please use the `post_list_memberships_with_metadata` + DEPRECATED. Please use the `post_delete_fleet_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the GkeHub server but before - it is returned to user code. This `post_list_memberships` interceptor runs - before the `post_list_memberships_with_metadata` interceptor. + it is returned to user code. This `post_delete_fleet` interceptor runs + before the `post_delete_fleet_with_metadata` interceptor. """ return response - def post_list_memberships_with_metadata( + def post_delete_fleet_with_metadata( self, - response: service.ListMembershipsResponse, + response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - service.ListMembershipsResponse, Sequence[Tuple[str, Union[str, bytes]]] - ]: - """Post-rpc interceptor for list_memberships + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_fleet Override in a subclass to read or manipulate the response or metadata after it is returned by the GkeHub server but before it is returned to user code. - We recommend only using this `post_list_memberships_with_metadata` - interceptor in new development instead of the `post_list_memberships` interceptor. - When both interceptors are used, this `post_list_memberships_with_metadata` interceptor runs after the - `post_list_memberships` interceptor. The (possibly modified) response returned by - `post_list_memberships` will be passed to - `post_list_memberships_with_metadata`. + We recommend only using this `post_delete_fleet_with_metadata` + interceptor in new development instead of the `post_delete_fleet` interceptor. + When both interceptors are used, this `post_delete_fleet_with_metadata` interceptor runs after the + `post_delete_fleet` interceptor. The (possibly modified) response returned by + `post_delete_fleet` will be passed to + `post_delete_fleet_with_metadata`. """ return response, metadata - def pre_update_feature( + def pre_delete_membership( self, - request: service.UpdateFeatureRequest, + request: service.DeleteMembershipRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[service.UpdateFeatureRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_feature + ) -> Tuple[ + service.DeleteMembershipRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_membership Override in a subclass to manipulate the request or metadata before they are sent to the GkeHub server. """ return request, metadata - def post_update_feature( + def post_delete_membership( self, response: operations_pb2.Operation ) -> operations_pb2.Operation: - """Post-rpc interceptor for update_feature + """Post-rpc interceptor for delete_membership - DEPRECATED. Please use the `post_update_feature_with_metadata` + DEPRECATED. Please use the `post_delete_membership_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the GkeHub server but before - it is returned to user code. This `post_update_feature` interceptor runs - before the `post_update_feature_with_metadata` interceptor. + it is returned to user code. This `post_delete_membership` interceptor runs + before the `post_delete_membership_with_metadata` interceptor. """ return response - def post_update_feature_with_metadata( + def post_delete_membership_with_metadata( self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_feature + """Post-rpc interceptor for delete_membership Override in a subclass to read or manipulate the response or metadata after it is returned by the GkeHub server but before it is returned to user code. - We recommend only using this `post_update_feature_with_metadata` - interceptor in new development instead of the `post_update_feature` interceptor. - When both interceptors are used, this `post_update_feature_with_metadata` interceptor runs after the - `post_update_feature` interceptor. The (possibly modified) response returned by - `post_update_feature` will be passed to - `post_update_feature_with_metadata`. + We recommend only using this `post_delete_membership_with_metadata` + interceptor in new development instead of the `post_delete_membership` interceptor. + When both interceptors are used, this `post_delete_membership_with_metadata` interceptor runs after the + `post_delete_membership` interceptor. The (possibly modified) response returned by + `post_delete_membership` will be passed to + `post_delete_membership_with_metadata`. """ return response, metadata - def pre_update_membership( + def pre_delete_membership_binding( self, - request: service.UpdateMembershipRequest, + request: service.DeleteMembershipBindingRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - service.UpdateMembershipRequest, Sequence[Tuple[str, Union[str, bytes]]] + service.DeleteMembershipBindingRequest, Sequence[Tuple[str, Union[str, bytes]]] ]: - """Pre-rpc interceptor for update_membership + """Pre-rpc interceptor for delete_membership_binding Override in a subclass to manipulate the request or metadata before they are sent to the GkeHub server. """ return request, metadata - def post_update_membership( + def post_delete_membership_binding( self, response: operations_pb2.Operation ) -> operations_pb2.Operation: - """Post-rpc interceptor for update_membership + """Post-rpc interceptor for delete_membership_binding - DEPRECATED. Please use the `post_update_membership_with_metadata` + DEPRECATED. Please use the `post_delete_membership_binding_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the GkeHub server but before - it is returned to user code. This `post_update_membership` interceptor runs - before the `post_update_membership_with_metadata` interceptor. + it is returned to user code. This `post_delete_membership_binding` interceptor runs + before the `post_delete_membership_binding_with_metadata` interceptor. """ return response - def post_update_membership_with_metadata( + def post_delete_membership_binding_with_metadata( self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_membership + """Post-rpc interceptor for delete_membership_binding Override in a subclass to read or manipulate the response or metadata after it is returned by the GkeHub server but before it is returned to user code. - We recommend only using this `post_update_membership_with_metadata` - interceptor in new development instead of the `post_update_membership` interceptor. - When both interceptors are used, this `post_update_membership_with_metadata` interceptor runs after the - `post_update_membership` interceptor. The (possibly modified) response returned by - `post_update_membership` will be passed to - `post_update_membership_with_metadata`. + We recommend only using this `post_delete_membership_binding_with_metadata` + interceptor in new development instead of the `post_delete_membership_binding` interceptor. + When both interceptors are used, this `post_delete_membership_binding_with_metadata` interceptor runs after the + `post_delete_membership_binding` interceptor. The (possibly modified) response returned by + `post_delete_membership_binding` will be passed to + `post_delete_membership_binding_with_metadata`. """ return response, metadata + def pre_delete_membership_rbac_role_binding( + self, + request: service.DeleteMembershipRBACRoleBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.DeleteMembershipRBACRoleBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_membership_rbac_role_binding -@dataclasses.dataclass -class GkeHubRestStub: - _session: AuthorizedSession - _host: str - _interceptor: GkeHubRestInterceptor + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + def post_delete_membership_rbac_role_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_membership_rbac_role_binding -class GkeHubRestTransport(_BaseGkeHubRestTransport): - """REST backend synchronous transport for GkeHub. + DEPRECATED. Please use the `post_delete_membership_rbac_role_binding_with_metadata` + interceptor instead. - The GKE Hub service handles the registration of many Kubernetes - clusters to Google Cloud, and the management of multi-cluster - features over those clusters. + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_delete_membership_rbac_role_binding` interceptor runs + before the `post_delete_membership_rbac_role_binding_with_metadata` interceptor. + """ + return response - The GKE Hub service operates on the following resources: + def post_delete_membership_rbac_role_binding_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_membership_rbac_role_binding - - [Membership][google.cloud.gkehub.v1.Membership] - - [Feature][google.cloud.gkehub.v1.Feature] + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. - GKE Hub is currently available in the global region and all regions - in https://cloud.google.com/compute/docs/regions-zones. Feature is - only available in global region while membership is global region - and all the regions. + We recommend only using this `post_delete_membership_rbac_role_binding_with_metadata` + interceptor in new development instead of the `post_delete_membership_rbac_role_binding` interceptor. + When both interceptors are used, this `post_delete_membership_rbac_role_binding_with_metadata` interceptor runs after the + `post_delete_membership_rbac_role_binding` interceptor. The (possibly modified) response returned by + `post_delete_membership_rbac_role_binding` will be passed to + `post_delete_membership_rbac_role_binding_with_metadata`. + """ + return response, metadata - **Membership management may be non-trivial:** it is recommended to - use one of the Google-provided client libraries or tools where - possible when working with Membership resources. + def pre_delete_scope( + self, + request: service.DeleteScopeRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.DeleteScopeRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_scope - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata - It sends JSON representations of protocol buffers over HTTP/1.1 - """ + def post_delete_scope( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_scope - def __init__( + DEPRECATED. Please use the `post_delete_scope_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_delete_scope` interceptor runs + before the `post_delete_scope_with_metadata` interceptor. + """ + return response + + def post_delete_scope_with_metadata( self, - *, - host: str = "gkehub.googleapis.com", - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = "https", - interceptor: Optional[GkeHubRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_scope - Args: - host (Optional[str]): - The hostname to connect to (default: 'gkehub.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. - credentials_file (Optional[str]): Deprecated. A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. This argument will be - removed in the next major version of this library. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. + We recommend only using this `post_delete_scope_with_metadata` + interceptor in new development instead of the `post_delete_scope` interceptor. + When both interceptors are used, this `post_delete_scope_with_metadata` interceptor runs after the + `post_delete_scope` interceptor. The (possibly modified) response returned by + `post_delete_scope` will be passed to + `post_delete_scope_with_metadata`. """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - url_scheme=url_scheme, - api_audience=api_audience, - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST - ) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or GkeHubRestInterceptor() - self._prep_wrapped_messages(client_info) + return response, metadata - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. + def pre_delete_scope_namespace( + self, + request: service.DeleteScopeNamespaceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.DeleteScopeNamespaceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_scope_namespace - This property caches on the instance; repeated calls return the same - client. + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - "google.longrunning.Operations.CancelOperation": [ - { - "method": "post", - "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", - "body": "*", - }, - ], - "google.longrunning.Operations.DeleteOperation": [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", - }, - ], - "google.longrunning.Operations.GetOperation": [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", - }, - ], - "google.longrunning.Operations.ListOperations": [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*}/operations", - }, - ], - } + return request, metadata + + def post_delete_scope_namespace( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_scope_namespace + + DEPRECATED. Please use the `post_delete_scope_namespace_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_delete_scope_namespace` interceptor runs + before the `post_delete_scope_namespace_with_metadata` interceptor. + """ + return response + + def post_delete_scope_namespace_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_scope_namespace + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_delete_scope_namespace_with_metadata` + interceptor in new development instead of the `post_delete_scope_namespace` interceptor. + When both interceptors are used, this `post_delete_scope_namespace_with_metadata` interceptor runs after the + `post_delete_scope_namespace` interceptor. The (possibly modified) response returned by + `post_delete_scope_namespace` will be passed to + `post_delete_scope_namespace_with_metadata`. + """ + return response, metadata + + def pre_delete_scope_rbac_role_binding( + self, + request: service.DeleteScopeRBACRoleBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.DeleteScopeRBACRoleBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_scope_rbac_role_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_delete_scope_rbac_role_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_scope_rbac_role_binding + + DEPRECATED. Please use the `post_delete_scope_rbac_role_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_delete_scope_rbac_role_binding` interceptor runs + before the `post_delete_scope_rbac_role_binding_with_metadata` interceptor. + """ + return response + + def post_delete_scope_rbac_role_binding_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_scope_rbac_role_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_delete_scope_rbac_role_binding_with_metadata` + interceptor in new development instead of the `post_delete_scope_rbac_role_binding` interceptor. + When both interceptors are used, this `post_delete_scope_rbac_role_binding_with_metadata` interceptor runs after the + `post_delete_scope_rbac_role_binding` interceptor. The (possibly modified) response returned by + `post_delete_scope_rbac_role_binding` will be passed to + `post_delete_scope_rbac_role_binding_with_metadata`. + """ + return response, metadata + + def pre_generate_connect_manifest( + self, + request: service.GenerateConnectManifestRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.GenerateConnectManifestRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for generate_connect_manifest + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_generate_connect_manifest( + self, response: service.GenerateConnectManifestResponse + ) -> service.GenerateConnectManifestResponse: + """Post-rpc interceptor for generate_connect_manifest + + DEPRECATED. Please use the `post_generate_connect_manifest_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_generate_connect_manifest` interceptor runs + before the `post_generate_connect_manifest_with_metadata` interceptor. + """ + return response + + def post_generate_connect_manifest_with_metadata( + self, + response: service.GenerateConnectManifestResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.GenerateConnectManifestResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for generate_connect_manifest + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_generate_connect_manifest_with_metadata` + interceptor in new development instead of the `post_generate_connect_manifest` interceptor. + When both interceptors are used, this `post_generate_connect_manifest_with_metadata` interceptor runs after the + `post_generate_connect_manifest` interceptor. The (possibly modified) response returned by + `post_generate_connect_manifest` will be passed to + `post_generate_connect_manifest_with_metadata`. + """ + return response, metadata + + def pre_generate_membership_rbac_role_binding_yaml( + self, + request: service.GenerateMembershipRBACRoleBindingYAMLRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.GenerateMembershipRBACRoleBindingYAMLRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for generate_membership_rbac_role_binding_yaml + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_generate_membership_rbac_role_binding_yaml( + self, response: service.GenerateMembershipRBACRoleBindingYAMLResponse + ) -> service.GenerateMembershipRBACRoleBindingYAMLResponse: + """Post-rpc interceptor for generate_membership_rbac_role_binding_yaml + + DEPRECATED. Please use the `post_generate_membership_rbac_role_binding_yaml_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_generate_membership_rbac_role_binding_yaml` interceptor runs + before the `post_generate_membership_rbac_role_binding_yaml_with_metadata` interceptor. + """ + return response + + def post_generate_membership_rbac_role_binding_yaml_with_metadata( + self, + response: service.GenerateMembershipRBACRoleBindingYAMLResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.GenerateMembershipRBACRoleBindingYAMLResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for generate_membership_rbac_role_binding_yaml + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_generate_membership_rbac_role_binding_yaml_with_metadata` + interceptor in new development instead of the `post_generate_membership_rbac_role_binding_yaml` interceptor. + When both interceptors are used, this `post_generate_membership_rbac_role_binding_yaml_with_metadata` interceptor runs after the + `post_generate_membership_rbac_role_binding_yaml` interceptor. The (possibly modified) response returned by + `post_generate_membership_rbac_role_binding_yaml` will be passed to + `post_generate_membership_rbac_role_binding_yaml_with_metadata`. + """ + return response, metadata + + def pre_get_feature( + self, + request: service.GetFeatureRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.GetFeatureRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_feature + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_get_feature(self, response: feature.Feature) -> feature.Feature: + """Post-rpc interceptor for get_feature + + DEPRECATED. Please use the `post_get_feature_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_get_feature` interceptor runs + before the `post_get_feature_with_metadata` interceptor. + """ + return response + + def post_get_feature_with_metadata( + self, + response: feature.Feature, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[feature.Feature, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_feature + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_get_feature_with_metadata` + interceptor in new development instead of the `post_get_feature` interceptor. + When both interceptors are used, this `post_get_feature_with_metadata` interceptor runs after the + `post_get_feature` interceptor. The (possibly modified) response returned by + `post_get_feature` will be passed to + `post_get_feature_with_metadata`. + """ + return response, metadata + + def pre_get_fleet( + self, + request: service.GetFleetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.GetFleetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_fleet + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_get_fleet(self, response: fleet.Fleet) -> fleet.Fleet: + """Post-rpc interceptor for get_fleet + + DEPRECATED. Please use the `post_get_fleet_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_get_fleet` interceptor runs + before the `post_get_fleet_with_metadata` interceptor. + """ + return response + + def post_get_fleet_with_metadata( + self, response: fleet.Fleet, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[fleet.Fleet, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_fleet + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_get_fleet_with_metadata` + interceptor in new development instead of the `post_get_fleet` interceptor. + When both interceptors are used, this `post_get_fleet_with_metadata` interceptor runs after the + `post_get_fleet` interceptor. The (possibly modified) response returned by + `post_get_fleet` will be passed to + `post_get_fleet_with_metadata`. + """ + return response, metadata + + def pre_get_membership( + self, + request: service.GetMembershipRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.GetMembershipRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_get_membership( + self, response: membership.Membership + ) -> membership.Membership: + """Post-rpc interceptor for get_membership + + DEPRECATED. Please use the `post_get_membership_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_get_membership` interceptor runs + before the `post_get_membership_with_metadata` interceptor. + """ + return response + + def post_get_membership_with_metadata( + self, + response: membership.Membership, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[membership.Membership, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_membership + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_get_membership_with_metadata` + interceptor in new development instead of the `post_get_membership` interceptor. + When both interceptors are used, this `post_get_membership_with_metadata` interceptor runs after the + `post_get_membership` interceptor. The (possibly modified) response returned by + `post_get_membership` will be passed to + `post_get_membership_with_metadata`. + """ + return response, metadata + + def pre_get_membership_binding( + self, + request: service.GetMembershipBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.GetMembershipBindingRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_membership_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_get_membership_binding( + self, response: fleet.MembershipBinding + ) -> fleet.MembershipBinding: + """Post-rpc interceptor for get_membership_binding + + DEPRECATED. Please use the `post_get_membership_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_get_membership_binding` interceptor runs + before the `post_get_membership_binding_with_metadata` interceptor. + """ + return response + + def post_get_membership_binding_with_metadata( + self, + response: fleet.MembershipBinding, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[fleet.MembershipBinding, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_membership_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_get_membership_binding_with_metadata` + interceptor in new development instead of the `post_get_membership_binding` interceptor. + When both interceptors are used, this `post_get_membership_binding_with_metadata` interceptor runs after the + `post_get_membership_binding` interceptor. The (possibly modified) response returned by + `post_get_membership_binding` will be passed to + `post_get_membership_binding_with_metadata`. + """ + return response, metadata + + def pre_get_membership_rbac_role_binding( + self, + request: service.GetMembershipRBACRoleBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.GetMembershipRBACRoleBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_membership_rbac_role_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_get_membership_rbac_role_binding( + self, response: fleet.RBACRoleBinding + ) -> fleet.RBACRoleBinding: + """Post-rpc interceptor for get_membership_rbac_role_binding + + DEPRECATED. Please use the `post_get_membership_rbac_role_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_get_membership_rbac_role_binding` interceptor runs + before the `post_get_membership_rbac_role_binding_with_metadata` interceptor. + """ + return response + + def post_get_membership_rbac_role_binding_with_metadata( + self, + response: fleet.RBACRoleBinding, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[fleet.RBACRoleBinding, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_membership_rbac_role_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_get_membership_rbac_role_binding_with_metadata` + interceptor in new development instead of the `post_get_membership_rbac_role_binding` interceptor. + When both interceptors are used, this `post_get_membership_rbac_role_binding_with_metadata` interceptor runs after the + `post_get_membership_rbac_role_binding` interceptor. The (possibly modified) response returned by + `post_get_membership_rbac_role_binding` will be passed to + `post_get_membership_rbac_role_binding_with_metadata`. + """ + return response, metadata + + def pre_get_scope( + self, + request: service.GetScopeRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.GetScopeRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_scope + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_get_scope(self, response: fleet.Scope) -> fleet.Scope: + """Post-rpc interceptor for get_scope + + DEPRECATED. Please use the `post_get_scope_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_get_scope` interceptor runs + before the `post_get_scope_with_metadata` interceptor. + """ + return response + + def post_get_scope_with_metadata( + self, response: fleet.Scope, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[fleet.Scope, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_scope + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_get_scope_with_metadata` + interceptor in new development instead of the `post_get_scope` interceptor. + When both interceptors are used, this `post_get_scope_with_metadata` interceptor runs after the + `post_get_scope` interceptor. The (possibly modified) response returned by + `post_get_scope` will be passed to + `post_get_scope_with_metadata`. + """ + return response, metadata + + def pre_get_scope_namespace( + self, + request: service.GetScopeNamespaceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.GetScopeNamespaceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_scope_namespace + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_get_scope_namespace(self, response: fleet.Namespace) -> fleet.Namespace: + """Post-rpc interceptor for get_scope_namespace + + DEPRECATED. Please use the `post_get_scope_namespace_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_get_scope_namespace` interceptor runs + before the `post_get_scope_namespace_with_metadata` interceptor. + """ + return response + + def post_get_scope_namespace_with_metadata( + self, + response: fleet.Namespace, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[fleet.Namespace, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_scope_namespace + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_get_scope_namespace_with_metadata` + interceptor in new development instead of the `post_get_scope_namespace` interceptor. + When both interceptors are used, this `post_get_scope_namespace_with_metadata` interceptor runs after the + `post_get_scope_namespace` interceptor. The (possibly modified) response returned by + `post_get_scope_namespace` will be passed to + `post_get_scope_namespace_with_metadata`. + """ + return response, metadata + + def pre_get_scope_rbac_role_binding( + self, + request: service.GetScopeRBACRoleBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.GetScopeRBACRoleBindingRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_scope_rbac_role_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_get_scope_rbac_role_binding( + self, response: fleet.RBACRoleBinding + ) -> fleet.RBACRoleBinding: + """Post-rpc interceptor for get_scope_rbac_role_binding + + DEPRECATED. Please use the `post_get_scope_rbac_role_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_get_scope_rbac_role_binding` interceptor runs + before the `post_get_scope_rbac_role_binding_with_metadata` interceptor. + """ + return response + + def post_get_scope_rbac_role_binding_with_metadata( + self, + response: fleet.RBACRoleBinding, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[fleet.RBACRoleBinding, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_scope_rbac_role_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_get_scope_rbac_role_binding_with_metadata` + interceptor in new development instead of the `post_get_scope_rbac_role_binding` interceptor. + When both interceptors are used, this `post_get_scope_rbac_role_binding_with_metadata` interceptor runs after the + `post_get_scope_rbac_role_binding` interceptor. The (possibly modified) response returned by + `post_get_scope_rbac_role_binding` will be passed to + `post_get_scope_rbac_role_binding_with_metadata`. + """ + return response, metadata + + def pre_list_bound_memberships( + self, + request: service.ListBoundMembershipsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.ListBoundMembershipsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_bound_memberships + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_list_bound_memberships( + self, response: service.ListBoundMembershipsResponse + ) -> service.ListBoundMembershipsResponse: + """Post-rpc interceptor for list_bound_memberships + + DEPRECATED. Please use the `post_list_bound_memberships_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_list_bound_memberships` interceptor runs + before the `post_list_bound_memberships_with_metadata` interceptor. + """ + return response + + def post_list_bound_memberships_with_metadata( + self, + response: service.ListBoundMembershipsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.ListBoundMembershipsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_bound_memberships + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_list_bound_memberships_with_metadata` + interceptor in new development instead of the `post_list_bound_memberships` interceptor. + When both interceptors are used, this `post_list_bound_memberships_with_metadata` interceptor runs after the + `post_list_bound_memberships` interceptor. The (possibly modified) response returned by + `post_list_bound_memberships` will be passed to + `post_list_bound_memberships_with_metadata`. + """ + return response, metadata + + def pre_list_features( + self, + request: service.ListFeaturesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.ListFeaturesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_features + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_list_features( + self, response: service.ListFeaturesResponse + ) -> service.ListFeaturesResponse: + """Post-rpc interceptor for list_features + + DEPRECATED. Please use the `post_list_features_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_list_features` interceptor runs + before the `post_list_features_with_metadata` interceptor. + """ + return response + + def post_list_features_with_metadata( + self, + response: service.ListFeaturesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.ListFeaturesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_features + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_list_features_with_metadata` + interceptor in new development instead of the `post_list_features` interceptor. + When both interceptors are used, this `post_list_features_with_metadata` interceptor runs after the + `post_list_features` interceptor. The (possibly modified) response returned by + `post_list_features` will be passed to + `post_list_features_with_metadata`. + """ + return response, metadata + + def pre_list_fleets( + self, + request: service.ListFleetsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.ListFleetsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_fleets + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_list_fleets( + self, response: service.ListFleetsResponse + ) -> service.ListFleetsResponse: + """Post-rpc interceptor for list_fleets + + DEPRECATED. Please use the `post_list_fleets_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_list_fleets` interceptor runs + before the `post_list_fleets_with_metadata` interceptor. + """ + return response + + def post_list_fleets_with_metadata( + self, + response: service.ListFleetsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.ListFleetsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_fleets + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_list_fleets_with_metadata` + interceptor in new development instead of the `post_list_fleets` interceptor. + When both interceptors are used, this `post_list_fleets_with_metadata` interceptor runs after the + `post_list_fleets` interceptor. The (possibly modified) response returned by + `post_list_fleets` will be passed to + `post_list_fleets_with_metadata`. + """ + return response, metadata + + def pre_list_membership_bindings( + self, + request: service.ListMembershipBindingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.ListMembershipBindingsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_membership_bindings + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_list_membership_bindings( + self, response: service.ListMembershipBindingsResponse + ) -> service.ListMembershipBindingsResponse: + """Post-rpc interceptor for list_membership_bindings + + DEPRECATED. Please use the `post_list_membership_bindings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_list_membership_bindings` interceptor runs + before the `post_list_membership_bindings_with_metadata` interceptor. + """ + return response + + def post_list_membership_bindings_with_metadata( + self, + response: service.ListMembershipBindingsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.ListMembershipBindingsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_membership_bindings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_list_membership_bindings_with_metadata` + interceptor in new development instead of the `post_list_membership_bindings` interceptor. + When both interceptors are used, this `post_list_membership_bindings_with_metadata` interceptor runs after the + `post_list_membership_bindings` interceptor. The (possibly modified) response returned by + `post_list_membership_bindings` will be passed to + `post_list_membership_bindings_with_metadata`. + """ + return response, metadata + + def pre_list_membership_rbac_role_bindings( + self, + request: service.ListMembershipRBACRoleBindingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.ListMembershipRBACRoleBindingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_membership_rbac_role_bindings + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_list_membership_rbac_role_bindings( + self, response: service.ListMembershipRBACRoleBindingsResponse + ) -> service.ListMembershipRBACRoleBindingsResponse: + """Post-rpc interceptor for list_membership_rbac_role_bindings + + DEPRECATED. Please use the `post_list_membership_rbac_role_bindings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_list_membership_rbac_role_bindings` interceptor runs + before the `post_list_membership_rbac_role_bindings_with_metadata` interceptor. + """ + return response + + def post_list_membership_rbac_role_bindings_with_metadata( + self, + response: service.ListMembershipRBACRoleBindingsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.ListMembershipRBACRoleBindingsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_membership_rbac_role_bindings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_list_membership_rbac_role_bindings_with_metadata` + interceptor in new development instead of the `post_list_membership_rbac_role_bindings` interceptor. + When both interceptors are used, this `post_list_membership_rbac_role_bindings_with_metadata` interceptor runs after the + `post_list_membership_rbac_role_bindings` interceptor. The (possibly modified) response returned by + `post_list_membership_rbac_role_bindings` will be passed to + `post_list_membership_rbac_role_bindings_with_metadata`. + """ + return response, metadata + + def pre_list_memberships( + self, + request: service.ListMembershipsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.ListMembershipsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_memberships + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_list_memberships( + self, response: service.ListMembershipsResponse + ) -> service.ListMembershipsResponse: + """Post-rpc interceptor for list_memberships + + DEPRECATED. Please use the `post_list_memberships_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_list_memberships` interceptor runs + before the `post_list_memberships_with_metadata` interceptor. + """ + return response + + def post_list_memberships_with_metadata( + self, + response: service.ListMembershipsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.ListMembershipsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_memberships + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_list_memberships_with_metadata` + interceptor in new development instead of the `post_list_memberships` interceptor. + When both interceptors are used, this `post_list_memberships_with_metadata` interceptor runs after the + `post_list_memberships` interceptor. The (possibly modified) response returned by + `post_list_memberships` will be passed to + `post_list_memberships_with_metadata`. + """ + return response, metadata + + def pre_list_permitted_scopes( + self, + request: service.ListPermittedScopesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.ListPermittedScopesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_permitted_scopes + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_list_permitted_scopes( + self, response: service.ListPermittedScopesResponse + ) -> service.ListPermittedScopesResponse: + """Post-rpc interceptor for list_permitted_scopes + + DEPRECATED. Please use the `post_list_permitted_scopes_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_list_permitted_scopes` interceptor runs + before the `post_list_permitted_scopes_with_metadata` interceptor. + """ + return response + + def post_list_permitted_scopes_with_metadata( + self, + response: service.ListPermittedScopesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.ListPermittedScopesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_permitted_scopes + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_list_permitted_scopes_with_metadata` + interceptor in new development instead of the `post_list_permitted_scopes` interceptor. + When both interceptors are used, this `post_list_permitted_scopes_with_metadata` interceptor runs after the + `post_list_permitted_scopes` interceptor. The (possibly modified) response returned by + `post_list_permitted_scopes` will be passed to + `post_list_permitted_scopes_with_metadata`. + """ + return response, metadata + + def pre_list_scope_namespaces( + self, + request: service.ListScopeNamespacesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.ListScopeNamespacesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_scope_namespaces + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_list_scope_namespaces( + self, response: service.ListScopeNamespacesResponse + ) -> service.ListScopeNamespacesResponse: + """Post-rpc interceptor for list_scope_namespaces + + DEPRECATED. Please use the `post_list_scope_namespaces_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_list_scope_namespaces` interceptor runs + before the `post_list_scope_namespaces_with_metadata` interceptor. + """ + return response + + def post_list_scope_namespaces_with_metadata( + self, + response: service.ListScopeNamespacesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.ListScopeNamespacesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_scope_namespaces + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_list_scope_namespaces_with_metadata` + interceptor in new development instead of the `post_list_scope_namespaces` interceptor. + When both interceptors are used, this `post_list_scope_namespaces_with_metadata` interceptor runs after the + `post_list_scope_namespaces` interceptor. The (possibly modified) response returned by + `post_list_scope_namespaces` will be passed to + `post_list_scope_namespaces_with_metadata`. + """ + return response, metadata + + def pre_list_scope_rbac_role_bindings( + self, + request: service.ListScopeRBACRoleBindingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.ListScopeRBACRoleBindingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_scope_rbac_role_bindings + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_list_scope_rbac_role_bindings( + self, response: service.ListScopeRBACRoleBindingsResponse + ) -> service.ListScopeRBACRoleBindingsResponse: + """Post-rpc interceptor for list_scope_rbac_role_bindings + + DEPRECATED. Please use the `post_list_scope_rbac_role_bindings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_list_scope_rbac_role_bindings` interceptor runs + before the `post_list_scope_rbac_role_bindings_with_metadata` interceptor. + """ + return response + + def post_list_scope_rbac_role_bindings_with_metadata( + self, + response: service.ListScopeRBACRoleBindingsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.ListScopeRBACRoleBindingsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_scope_rbac_role_bindings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_list_scope_rbac_role_bindings_with_metadata` + interceptor in new development instead of the `post_list_scope_rbac_role_bindings` interceptor. + When both interceptors are used, this `post_list_scope_rbac_role_bindings_with_metadata` interceptor runs after the + `post_list_scope_rbac_role_bindings` interceptor. The (possibly modified) response returned by + `post_list_scope_rbac_role_bindings` will be passed to + `post_list_scope_rbac_role_bindings_with_metadata`. + """ + return response, metadata + + def pre_list_scopes( + self, + request: service.ListScopesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.ListScopesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_scopes + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_list_scopes( + self, response: service.ListScopesResponse + ) -> service.ListScopesResponse: + """Post-rpc interceptor for list_scopes + + DEPRECATED. Please use the `post_list_scopes_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_list_scopes` interceptor runs + before the `post_list_scopes_with_metadata` interceptor. + """ + return response + + def post_list_scopes_with_metadata( + self, + response: service.ListScopesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.ListScopesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_scopes + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_list_scopes_with_metadata` + interceptor in new development instead of the `post_list_scopes` interceptor. + When both interceptors are used, this `post_list_scopes_with_metadata` interceptor runs after the + `post_list_scopes` interceptor. The (possibly modified) response returned by + `post_list_scopes` will be passed to + `post_list_scopes_with_metadata`. + """ + return response, metadata + + def pre_update_feature( + self, + request: service.UpdateFeatureRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.UpdateFeatureRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_feature + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_update_feature( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_feature + + DEPRECATED. Please use the `post_update_feature_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_update_feature` interceptor runs + before the `post_update_feature_with_metadata` interceptor. + """ + return response + + def post_update_feature_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_feature + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_update_feature_with_metadata` + interceptor in new development instead of the `post_update_feature` interceptor. + When both interceptors are used, this `post_update_feature_with_metadata` interceptor runs after the + `post_update_feature` interceptor. The (possibly modified) response returned by + `post_update_feature` will be passed to + `post_update_feature_with_metadata`. + """ + return response, metadata + + def pre_update_fleet( + self, + request: service.UpdateFleetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.UpdateFleetRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_fleet + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_update_fleet( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_fleet + + DEPRECATED. Please use the `post_update_fleet_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_update_fleet` interceptor runs + before the `post_update_fleet_with_metadata` interceptor. + """ + return response + + def post_update_fleet_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_fleet + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_update_fleet_with_metadata` + interceptor in new development instead of the `post_update_fleet` interceptor. + When both interceptors are used, this `post_update_fleet_with_metadata` interceptor runs after the + `post_update_fleet` interceptor. The (possibly modified) response returned by + `post_update_fleet` will be passed to + `post_update_fleet_with_metadata`. + """ + return response, metadata + + def pre_update_membership( + self, + request: service.UpdateMembershipRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.UpdateMembershipRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_membership + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_update_membership( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_membership + + DEPRECATED. Please use the `post_update_membership_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_update_membership` interceptor runs + before the `post_update_membership_with_metadata` interceptor. + """ + return response + + def post_update_membership_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_membership + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_update_membership_with_metadata` + interceptor in new development instead of the `post_update_membership` interceptor. + When both interceptors are used, this `post_update_membership_with_metadata` interceptor runs after the + `post_update_membership` interceptor. The (possibly modified) response returned by + `post_update_membership` will be passed to + `post_update_membership_with_metadata`. + """ + return response, metadata + + def pre_update_membership_binding( + self, + request: service.UpdateMembershipBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.UpdateMembershipBindingRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_membership_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_update_membership_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_membership_binding + + DEPRECATED. Please use the `post_update_membership_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_update_membership_binding` interceptor runs + before the `post_update_membership_binding_with_metadata` interceptor. + """ + return response + + def post_update_membership_binding_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_membership_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_update_membership_binding_with_metadata` + interceptor in new development instead of the `post_update_membership_binding` interceptor. + When both interceptors are used, this `post_update_membership_binding_with_metadata` interceptor runs after the + `post_update_membership_binding` interceptor. The (possibly modified) response returned by + `post_update_membership_binding` will be passed to + `post_update_membership_binding_with_metadata`. + """ + return response, metadata + + def pre_update_membership_rbac_role_binding( + self, + request: service.UpdateMembershipRBACRoleBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.UpdateMembershipRBACRoleBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_membership_rbac_role_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_update_membership_rbac_role_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_membership_rbac_role_binding + + DEPRECATED. Please use the `post_update_membership_rbac_role_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_update_membership_rbac_role_binding` interceptor runs + before the `post_update_membership_rbac_role_binding_with_metadata` interceptor. + """ + return response + + def post_update_membership_rbac_role_binding_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_membership_rbac_role_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_update_membership_rbac_role_binding_with_metadata` + interceptor in new development instead of the `post_update_membership_rbac_role_binding` interceptor. + When both interceptors are used, this `post_update_membership_rbac_role_binding_with_metadata` interceptor runs after the + `post_update_membership_rbac_role_binding` interceptor. The (possibly modified) response returned by + `post_update_membership_rbac_role_binding` will be passed to + `post_update_membership_rbac_role_binding_with_metadata`. + """ + return response, metadata + + def pre_update_scope( + self, + request: service.UpdateScopeRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.UpdateScopeRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_scope + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_update_scope( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_scope + + DEPRECATED. Please use the `post_update_scope_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_update_scope` interceptor runs + before the `post_update_scope_with_metadata` interceptor. + """ + return response + + def post_update_scope_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_scope + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_update_scope_with_metadata` + interceptor in new development instead of the `post_update_scope` interceptor. + When both interceptors are used, this `post_update_scope_with_metadata` interceptor runs after the + `post_update_scope` interceptor. The (possibly modified) response returned by + `post_update_scope` will be passed to + `post_update_scope_with_metadata`. + """ + return response, metadata + + def pre_update_scope_namespace( + self, + request: service.UpdateScopeNamespaceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.UpdateScopeNamespaceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_scope_namespace + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_update_scope_namespace( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_scope_namespace + + DEPRECATED. Please use the `post_update_scope_namespace_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_update_scope_namespace` interceptor runs + before the `post_update_scope_namespace_with_metadata` interceptor. + """ + return response + + def post_update_scope_namespace_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_scope_namespace + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_update_scope_namespace_with_metadata` + interceptor in new development instead of the `post_update_scope_namespace` interceptor. + When both interceptors are used, this `post_update_scope_namespace_with_metadata` interceptor runs after the + `post_update_scope_namespace` interceptor. The (possibly modified) response returned by + `post_update_scope_namespace` will be passed to + `post_update_scope_namespace_with_metadata`. + """ + return response, metadata + + def pre_update_scope_rbac_role_binding( + self, + request: service.UpdateScopeRBACRoleBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.UpdateScopeRBACRoleBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_scope_rbac_role_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the GkeHub server. + """ + return request, metadata + + def post_update_scope_rbac_role_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_scope_rbac_role_binding + + DEPRECATED. Please use the `post_update_scope_rbac_role_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GkeHub server but before + it is returned to user code. This `post_update_scope_rbac_role_binding` interceptor runs + before the `post_update_scope_rbac_role_binding_with_metadata` interceptor. + """ + return response + + def post_update_scope_rbac_role_binding_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_scope_rbac_role_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GkeHub server but before it is returned to user code. + + We recommend only using this `post_update_scope_rbac_role_binding_with_metadata` + interceptor in new development instead of the `post_update_scope_rbac_role_binding` interceptor. + When both interceptors are used, this `post_update_scope_rbac_role_binding_with_metadata` interceptor runs after the + `post_update_scope_rbac_role_binding` interceptor. The (possibly modified) response returned by + `post_update_scope_rbac_role_binding` will be passed to + `post_update_scope_rbac_role_binding_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class GkeHubRestStub: + _session: AuthorizedSession + _host: str + _interceptor: GkeHubRestInterceptor + + +class GkeHubRestTransport(_BaseGkeHubRestTransport): + """REST backend synchronous transport for GkeHub. + + The GKE Hub service handles the registration of many Kubernetes + clusters to Google Cloud, and the management of multi-cluster + features over those clusters. + + The GKE Hub service operates on the following resources: + + - [Membership][google.cloud.gkehub.v1.Membership] + - [Feature][google.cloud.gkehub.v1.Feature] + + GKE Hub is currently available in the global region and all regions + in https://cloud.google.com/compute/docs/regions-zones. Feature is + only available in global region while membership is global region + and all the regions. + + **Membership management may be non-trivial:** it is recommended to + use one of the Google-provided client libraries or tools where + possible when working with Membership resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "gkehub.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[GkeHubRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'gkehub.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or GkeHubRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateFeature(_BaseGkeHubRestTransport._BaseCreateFeature, GkeHubRestStub): + def __hash__(self): + return hash("GkeHubRestTransport.CreateFeature") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.CreateFeatureRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create feature method over HTTP. + + Args: + request (~.service.CreateFeatureRequest): + The request object. Request message for the ``GkeHub.CreateFeature`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseCreateFeature._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_feature(request, metadata) + transcoded_request = ( + _BaseGkeHubRestTransport._BaseCreateFeature._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseGkeHubRestTransport._BaseCreateFeature._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseGkeHubRestTransport._BaseCreateFeature._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.CreateFeature", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "CreateFeature", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._CreateFeature._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_feature(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_feature_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.create_feature", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "CreateFeature", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateFleet(_BaseGkeHubRestTransport._BaseCreateFleet, GkeHubRestStub): + def __hash__(self): + return hash("GkeHubRestTransport.CreateFleet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.CreateFleetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create fleet method over HTTP. + + Args: + request (~.service.CreateFleetRequest): + The request object. Request message for the ``GkeHub.CreateFleet`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseGkeHubRestTransport._BaseCreateFleet._get_http_options() + + request, metadata = self._interceptor.pre_create_fleet(request, metadata) + transcoded_request = ( + _BaseGkeHubRestTransport._BaseCreateFleet._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseGkeHubRestTransport._BaseCreateFleet._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseGkeHubRestTransport._BaseCreateFleet._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.CreateFleet", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "CreateFleet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._CreateFleet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_fleet(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_fleet_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.create_fleet", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "CreateFleet", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateMembership( + _BaseGkeHubRestTransport._BaseCreateMembership, GkeHubRestStub + ): + def __hash__(self): + return hash("GkeHubRestTransport.CreateMembership") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.CreateMembershipRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create membership method over HTTP. + + Args: + request (~.service.CreateMembershipRequest): + The request object. Request message for the ``GkeHub.CreateMembership`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseCreateMembership._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_membership( + request, metadata + ) + transcoded_request = ( + _BaseGkeHubRestTransport._BaseCreateMembership._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseGkeHubRestTransport._BaseCreateMembership._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGkeHubRestTransport._BaseCreateMembership._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.CreateMembership", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "CreateMembership", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._CreateMembership._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_membership(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_membership_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.create_membership", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "CreateMembership", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateMembershipBinding( + _BaseGkeHubRestTransport._BaseCreateMembershipBinding, GkeHubRestStub + ): + def __hash__(self): + return hash("GkeHubRestTransport.CreateMembershipBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.CreateMembershipBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create membership binding method over HTTP. + + Args: + request (~.service.CreateMembershipBindingRequest): + The request object. Request to create a + MembershipBinding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseCreateMembershipBinding._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_membership_binding( + request, metadata + ) + transcoded_request = _BaseGkeHubRestTransport._BaseCreateMembershipBinding._get_transcoded_request( + http_options, request + ) + + body = _BaseGkeHubRestTransport._BaseCreateMembershipBinding._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseGkeHubRestTransport._BaseCreateMembershipBinding._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.CreateMembershipBinding", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "CreateMembershipBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._CreateMembershipBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_membership_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_membership_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.create_membership_binding", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "CreateMembershipBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateMembershipRBACRoleBinding( + _BaseGkeHubRestTransport._BaseCreateMembershipRBACRoleBinding, GkeHubRestStub + ): + def __hash__(self): + return hash("GkeHubRestTransport.CreateMembershipRBACRoleBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.CreateMembershipRBACRoleBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create membership rbac + role binding method over HTTP. + + Args: + request (~.service.CreateMembershipRBACRoleBindingRequest): + The request object. Request to create a rbacrolebindings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseCreateMembershipRBACRoleBinding._get_http_options() + ) + + ( + request, + metadata, + ) = self._interceptor.pre_create_membership_rbac_role_binding( + request, metadata + ) + transcoded_request = _BaseGkeHubRestTransport._BaseCreateMembershipRBACRoleBinding._get_transcoded_request( + http_options, request + ) + + body = _BaseGkeHubRestTransport._BaseCreateMembershipRBACRoleBinding._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseGkeHubRestTransport._BaseCreateMembershipRBACRoleBinding._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.CreateMembershipRBACRoleBinding", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "CreateMembershipRBACRoleBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + GkeHubRestTransport._CreateMembershipRBACRoleBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_membership_rbac_role_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_create_membership_rbac_role_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.create_membership_rbac_role_binding", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "CreateMembershipRBACRoleBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateScope(_BaseGkeHubRestTransport._BaseCreateScope, GkeHubRestStub): + def __hash__(self): + return hash("GkeHubRestTransport.CreateScope") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.CreateScopeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create scope method over HTTP. + + Args: + request (~.service.CreateScopeRequest): + The request object. Request to create a Scope. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseGkeHubRestTransport._BaseCreateScope._get_http_options() + + request, metadata = self._interceptor.pre_create_scope(request, metadata) + transcoded_request = ( + _BaseGkeHubRestTransport._BaseCreateScope._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseGkeHubRestTransport._BaseCreateScope._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseGkeHubRestTransport._BaseCreateScope._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.CreateScope", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "CreateScope", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._CreateScope._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_scope(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_scope_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.create_scope", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "CreateScope", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateScopeNamespace( + _BaseGkeHubRestTransport._BaseCreateScopeNamespace, GkeHubRestStub + ): + def __hash__(self): + return hash("GkeHubRestTransport.CreateScopeNamespace") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.CreateScopeNamespaceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create scope namespace method over HTTP. + + Args: + request (~.service.CreateScopeNamespaceRequest): + The request object. Request to create a fleet namespace. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseCreateScopeNamespace._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_scope_namespace( + request, metadata + ) + transcoded_request = _BaseGkeHubRestTransport._BaseCreateScopeNamespace._get_transcoded_request( + http_options, request + ) + + body = _BaseGkeHubRestTransport._BaseCreateScopeNamespace._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseGkeHubRestTransport._BaseCreateScopeNamespace._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.CreateScopeNamespace", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "CreateScopeNamespace", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._CreateScopeNamespace._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_scope_namespace(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_scope_namespace_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.create_scope_namespace", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "CreateScopeNamespace", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateScopeRBACRoleBinding( + _BaseGkeHubRestTransport._BaseCreateScopeRBACRoleBinding, GkeHubRestStub + ): + def __hash__(self): + return hash("GkeHubRestTransport.CreateScopeRBACRoleBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.CreateScopeRBACRoleBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create scope rbac role + binding method over HTTP. + + Args: + request (~.service.CreateScopeRBACRoleBindingRequest): + The request object. Request to create a rbacrolebindings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseCreateScopeRBACRoleBinding._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_scope_rbac_role_binding( + request, metadata + ) + transcoded_request = _BaseGkeHubRestTransport._BaseCreateScopeRBACRoleBinding._get_transcoded_request( + http_options, request + ) + + body = _BaseGkeHubRestTransport._BaseCreateScopeRBACRoleBinding._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseGkeHubRestTransport._BaseCreateScopeRBACRoleBinding._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.CreateScopeRBACRoleBinding", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "CreateScopeRBACRoleBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._CreateScopeRBACRoleBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_scope_rbac_role_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_create_scope_rbac_role_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.create_scope_rbac_role_binding", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "CreateScopeRBACRoleBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteFeature(_BaseGkeHubRestTransport._BaseDeleteFeature, GkeHubRestStub): + def __hash__(self): + return hash("GkeHubRestTransport.DeleteFeature") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.DeleteFeatureRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete feature method over HTTP. + + Args: + request (~.service.DeleteFeatureRequest): + The request object. Request message for ``GkeHub.DeleteFeature`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseDeleteFeature._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_feature(request, metadata) + transcoded_request = ( + _BaseGkeHubRestTransport._BaseDeleteFeature._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGkeHubRestTransport._BaseDeleteFeature._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.DeleteFeature", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "DeleteFeature", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._DeleteFeature._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_feature(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_feature_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.delete_feature", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "DeleteFeature", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteFleet(_BaseGkeHubRestTransport._BaseDeleteFleet, GkeHubRestStub): + def __hash__(self): + return hash("GkeHubRestTransport.DeleteFleet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.DeleteFleetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete fleet method over HTTP. + + Args: + request (~.service.DeleteFleetRequest): + The request object. Request message for ``GkeHub.DeleteFleet`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseGkeHubRestTransport._BaseDeleteFleet._get_http_options() + + request, metadata = self._interceptor.pre_delete_fleet(request, metadata) + transcoded_request = ( + _BaseGkeHubRestTransport._BaseDeleteFleet._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGkeHubRestTransport._BaseDeleteFleet._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.DeleteFleet", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "DeleteFleet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._DeleteFleet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_fleet(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_fleet_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.delete_fleet", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "DeleteFleet", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteMembership( + _BaseGkeHubRestTransport._BaseDeleteMembership, GkeHubRestStub + ): + def __hash__(self): + return hash("GkeHubRestTransport.DeleteMembership") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.DeleteMembershipRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete membership method over HTTP. + + Args: + request (~.service.DeleteMembershipRequest): + The request object. Request message for ``GkeHub.DeleteMembership`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseDeleteMembership._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_membership( + request, metadata + ) + transcoded_request = ( + _BaseGkeHubRestTransport._BaseDeleteMembership._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGkeHubRestTransport._BaseDeleteMembership._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.DeleteMembership", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "DeleteMembership", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._DeleteMembership._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_membership(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_membership_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.delete_membership", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "DeleteMembership", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteMembershipBinding( + _BaseGkeHubRestTransport._BaseDeleteMembershipBinding, GkeHubRestStub + ): + def __hash__(self): + return hash("GkeHubRestTransport.DeleteMembershipBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.DeleteMembershipBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete membership binding method over HTTP. + + Args: + request (~.service.DeleteMembershipBindingRequest): + The request object. Request to delete a Binding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseDeleteMembershipBinding._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_membership_binding( + request, metadata + ) + transcoded_request = _BaseGkeHubRestTransport._BaseDeleteMembershipBinding._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGkeHubRestTransport._BaseDeleteMembershipBinding._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.DeleteMembershipBinding", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "DeleteMembershipBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._DeleteMembershipBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_membership_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_membership_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.delete_membership_binding", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "DeleteMembershipBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteMembershipRBACRoleBinding( + _BaseGkeHubRestTransport._BaseDeleteMembershipRBACRoleBinding, GkeHubRestStub + ): + def __hash__(self): + return hash("GkeHubRestTransport.DeleteMembershipRBACRoleBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.DeleteMembershipRBACRoleBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete membership rbac + role binding method over HTTP. + + Args: + request (~.service.DeleteMembershipRBACRoleBindingRequest): + The request object. Request to delete a Membership + RBACRoleBinding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseDeleteMembershipRBACRoleBinding._get_http_options() + ) + + ( + request, + metadata, + ) = self._interceptor.pre_delete_membership_rbac_role_binding( + request, metadata + ) + transcoded_request = _BaseGkeHubRestTransport._BaseDeleteMembershipRBACRoleBinding._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGkeHubRestTransport._BaseDeleteMembershipRBACRoleBinding._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.DeleteMembershipRBACRoleBinding", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "DeleteMembershipRBACRoleBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + GkeHubRestTransport._DeleteMembershipRBACRoleBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_membership_rbac_role_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_delete_membership_rbac_role_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.delete_membership_rbac_role_binding", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "DeleteMembershipRBACRoleBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteScope(_BaseGkeHubRestTransport._BaseDeleteScope, GkeHubRestStub): + def __hash__(self): + return hash("GkeHubRestTransport.DeleteScope") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.DeleteScopeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete scope method over HTTP. + + Args: + request (~.service.DeleteScopeRequest): + The request object. Request to delete a Scope. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseGkeHubRestTransport._BaseDeleteScope._get_http_options() + + request, metadata = self._interceptor.pre_delete_scope(request, metadata) + transcoded_request = ( + _BaseGkeHubRestTransport._BaseDeleteScope._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGkeHubRestTransport._BaseDeleteScope._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.DeleteScope", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "DeleteScope", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._DeleteScope._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_scope(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_scope_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.delete_scope", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "DeleteScope", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteScopeNamespace( + _BaseGkeHubRestTransport._BaseDeleteScopeNamespace, GkeHubRestStub + ): + def __hash__(self): + return hash("GkeHubRestTransport.DeleteScopeNamespace") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.DeleteScopeNamespaceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete scope namespace method over HTTP. + + Args: + request (~.service.DeleteScopeNamespaceRequest): + The request object. Request to delete a fleet namespace. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseDeleteScopeNamespace._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_scope_namespace( + request, metadata + ) + transcoded_request = _BaseGkeHubRestTransport._BaseDeleteScopeNamespace._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGkeHubRestTransport._BaseDeleteScopeNamespace._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.DeleteScopeNamespace", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "DeleteScopeNamespace", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._DeleteScopeNamespace._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_scope_namespace(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_scope_namespace_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.delete_scope_namespace", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "DeleteScopeNamespace", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteScopeRBACRoleBinding( + _BaseGkeHubRestTransport._BaseDeleteScopeRBACRoleBinding, GkeHubRestStub + ): + def __hash__(self): + return hash("GkeHubRestTransport.DeleteScopeRBACRoleBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.DeleteScopeRBACRoleBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete scope rbac role + binding method over HTTP. + + Args: + request (~.service.DeleteScopeRBACRoleBindingRequest): + The request object. Request to delete a Scope + RBACRoleBinding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseDeleteScopeRBACRoleBinding._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_scope_rbac_role_binding( + request, metadata + ) + transcoded_request = _BaseGkeHubRestTransport._BaseDeleteScopeRBACRoleBinding._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGkeHubRestTransport._BaseDeleteScopeRBACRoleBinding._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.DeleteScopeRBACRoleBinding", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "DeleteScopeRBACRoleBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._DeleteScopeRBACRoleBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_scope_rbac_role_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_delete_scope_rbac_role_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.delete_scope_rbac_role_binding", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "DeleteScopeRBACRoleBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GenerateConnectManifest( + _BaseGkeHubRestTransport._BaseGenerateConnectManifest, GkeHubRestStub + ): + def __hash__(self): + return hash("GkeHubRestTransport.GenerateConnectManifest") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.GenerateConnectManifestRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.GenerateConnectManifestResponse: + r"""Call the generate connect manifest method over HTTP. + + Args: + request (~.service.GenerateConnectManifestRequest): + The request object. Request message for ``GkeHub.GenerateConnectManifest`` + method. . + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.service.GenerateConnectManifestResponse: + GenerateConnectManifestResponse + contains manifest information for + installing/upgrading a Connect agent. + + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseGenerateConnectManifest._get_http_options() + ) + + request, metadata = self._interceptor.pre_generate_connect_manifest( + request, metadata + ) + transcoded_request = _BaseGkeHubRestTransport._BaseGenerateConnectManifest._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGkeHubRestTransport._BaseGenerateConnectManifest._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.GenerateConnectManifest", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "GenerateConnectManifest", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._GenerateConnectManifest._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.GenerateConnectManifestResponse() + pb_resp = service.GenerateConnectManifestResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_generate_connect_manifest(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_generate_connect_manifest_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = service.GenerateConnectManifestResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.generate_connect_manifest", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "GenerateConnectManifest", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GenerateMembershipRBACRoleBindingYAML( + _BaseGkeHubRestTransport._BaseGenerateMembershipRBACRoleBindingYAML, + GkeHubRestStub, + ): + def __hash__(self): + return hash("GkeHubRestTransport.GenerateMembershipRBACRoleBindingYAML") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.GenerateMembershipRBACRoleBindingYAMLRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.GenerateMembershipRBACRoleBindingYAMLResponse: + r"""Call the generate membership rbac + role binding yaml method over HTTP. + + Args: + request (~.service.GenerateMembershipRBACRoleBindingYAMLRequest): + The request object. Request to generate a YAML of the + RBAC policies for the specified + RoleBinding and its associated + impersonation resources. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.service.GenerateMembershipRBACRoleBindingYAMLResponse: + Response for + GenerateRBACRoleBindingYAML. + + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseGenerateMembershipRBACRoleBindingYAML._get_http_options() + ) + + ( + request, + metadata, + ) = self._interceptor.pre_generate_membership_rbac_role_binding_yaml( + request, metadata + ) + transcoded_request = _BaseGkeHubRestTransport._BaseGenerateMembershipRBACRoleBindingYAML._get_transcoded_request( + http_options, request + ) + + body = _BaseGkeHubRestTransport._BaseGenerateMembershipRBACRoleBindingYAML._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseGkeHubRestTransport._BaseGenerateMembershipRBACRoleBindingYAML._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.GenerateMembershipRBACRoleBindingYAML", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "GenerateMembershipRBACRoleBindingYAML", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._GenerateMembershipRBACRoleBindingYAML._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.GenerateMembershipRBACRoleBindingYAMLResponse() + pb_resp = service.GenerateMembershipRBACRoleBindingYAMLResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_generate_membership_rbac_role_binding_yaml( + resp + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_generate_membership_rbac_role_binding_yaml_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + service.GenerateMembershipRBACRoleBindingYAMLResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.generate_membership_rbac_role_binding_yaml", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "GenerateMembershipRBACRoleBindingYAML", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetFeature(_BaseGkeHubRestTransport._BaseGetFeature, GkeHubRestStub): + def __hash__(self): + return hash("GkeHubRestTransport.GetFeature") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.GetFeatureRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> feature.Feature: + r"""Call the get feature method over HTTP. + + Args: + request (~.service.GetFeatureRequest): + The request object. Request message for ``GkeHub.GetFeature`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.feature.Feature: + Feature represents the settings and + status of any Fleet Feature. + + """ + + http_options = _BaseGkeHubRestTransport._BaseGetFeature._get_http_options() + + request, metadata = self._interceptor.pre_get_feature(request, metadata) + transcoded_request = ( + _BaseGkeHubRestTransport._BaseGetFeature._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGkeHubRestTransport._BaseGetFeature._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.GetFeature", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "GetFeature", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._GetFeature._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = feature.Feature() + pb_resp = feature.Feature.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_feature(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_feature_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = feature.Feature.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.get_feature", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "GetFeature", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetFleet(_BaseGkeHubRestTransport._BaseGetFleet, GkeHubRestStub): + def __hash__(self): + return hash("GkeHubRestTransport.GetFleet") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.GetFleetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> fleet.Fleet: + r"""Call the get fleet method over HTTP. + + Args: + request (~.service.GetFleetRequest): + The request object. Request message for the ``GkeHub.GetFleet`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.fleet.Fleet: + Fleet contains the Fleet-wide + metadata and configuration. + + """ + + http_options = _BaseGkeHubRestTransport._BaseGetFleet._get_http_options() + + request, metadata = self._interceptor.pre_get_fleet(request, metadata) + transcoded_request = ( + _BaseGkeHubRestTransport._BaseGetFleet._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGkeHubRestTransport._BaseGetFleet._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.GetFleet", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "GetFleet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._GetFleet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = fleet.Fleet() + pb_resp = fleet.Fleet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_fleet(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_fleet_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = fleet.Fleet.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.get_fleet", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "GetFleet", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetMembership(_BaseGkeHubRestTransport._BaseGetMembership, GkeHubRestStub): + def __hash__(self): + return hash("GkeHubRestTransport.GetMembership") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.GetMembershipRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> membership.Membership: + r"""Call the get membership method over HTTP. + + Args: + request (~.service.GetMembershipRequest): + The request object. Request message for ``GkeHub.GetMembership`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.membership.Membership: + Membership contains information about + a member cluster. + + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseGetMembership._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_membership(request, metadata) + transcoded_request = ( + _BaseGkeHubRestTransport._BaseGetMembership._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGkeHubRestTransport._BaseGetMembership._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.GetMembership", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "GetMembership", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._GetMembership._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = membership.Membership() + pb_resp = membership.Membership.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_membership(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_membership_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = membership.Membership.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.get_membership", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "GetMembership", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetMembershipBinding( + _BaseGkeHubRestTransport._BaseGetMembershipBinding, GkeHubRestStub + ): + def __hash__(self): + return hash("GkeHubRestTransport.GetMembershipBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.GetMembershipBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> fleet.MembershipBinding: + r"""Call the get membership binding method over HTTP. + + Args: + request (~.service.GetMembershipBindingRequest): + The request object. Request message for the ``GkeHub.GetMembershipBinding`` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.fleet.MembershipBinding: + MembershipBinding is a subresource of + a Membership, representing what Fleet + Scopes (or other, future Fleet + resources) a Membership is bound to. + + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseGetMembershipBinding._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_membership_binding( + request, metadata + ) + transcoded_request = _BaseGkeHubRestTransport._BaseGetMembershipBinding._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGkeHubRestTransport._BaseGetMembershipBinding._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.GetMembershipBinding", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "GetMembershipBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._GetMembershipBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = fleet.MembershipBinding() + pb_resp = fleet.MembershipBinding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_membership_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_membership_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = fleet.MembershipBinding.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.get_membership_binding", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "GetMembershipBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetMembershipRBACRoleBinding( + _BaseGkeHubRestTransport._BaseGetMembershipRBACRoleBinding, GkeHubRestStub + ): + def __hash__(self): + return hash("GkeHubRestTransport.GetMembershipRBACRoleBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.GetMembershipRBACRoleBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> fleet.RBACRoleBinding: + r"""Call the get membership rbac role + binding method over HTTP. + + Args: + request (~.service.GetMembershipRBACRoleBindingRequest): + The request object. Request message for the + ``GkeHub.GetMembershipRBACRoleBinding`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.fleet.RBACRoleBinding: + RBACRoleBinding represents a + rbacrolebinding across the Fleet + + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseGetMembershipRBACRoleBinding._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_membership_rbac_role_binding( + request, metadata + ) + transcoded_request = _BaseGkeHubRestTransport._BaseGetMembershipRBACRoleBinding._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGkeHubRestTransport._BaseGetMembershipRBACRoleBinding._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.GetMembershipRBACRoleBinding", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "GetMembershipRBACRoleBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._GetMembershipRBACRoleBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = fleet.RBACRoleBinding() + pb_resp = fleet.RBACRoleBinding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_membership_rbac_role_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_get_membership_rbac_role_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = fleet.RBACRoleBinding.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.get_membership_rbac_role_binding", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "GetMembershipRBACRoleBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetScope(_BaseGkeHubRestTransport._BaseGetScope, GkeHubRestStub): + def __hash__(self): + return hash("GkeHubRestTransport.GetScope") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.GetScopeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> fleet.Scope: + r"""Call the get scope method over HTTP. + + Args: + request (~.service.GetScopeRequest): + The request object. Request message for the ``GkeHub.GetScope`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.fleet.Scope: + Scope represents a Scope in a Fleet. + """ + + http_options = _BaseGkeHubRestTransport._BaseGetScope._get_http_options() + + request, metadata = self._interceptor.pre_get_scope(request, metadata) + transcoded_request = ( + _BaseGkeHubRestTransport._BaseGetScope._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGkeHubRestTransport._BaseGetScope._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.GetScope", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "GetScope", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._GetScope._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = fleet.Scope() + pb_resp = fleet.Scope.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_scope(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_scope_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = fleet.Scope.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.get_scope", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "GetScope", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetScopeNamespace( + _BaseGkeHubRestTransport._BaseGetScopeNamespace, GkeHubRestStub + ): + def __hash__(self): + return hash("GkeHubRestTransport.GetScopeNamespace") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.GetScopeNamespaceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> fleet.Namespace: + r"""Call the get scope namespace method over HTTP. + + Args: + request (~.service.GetScopeNamespaceRequest): + The request object. Request message for the ``GkeHub.GetNamespace`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.fleet.Namespace: + Namespace represents a namespace + across the Fleet + + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseGetScopeNamespace._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_scope_namespace( + request, metadata + ) + transcoded_request = ( + _BaseGkeHubRestTransport._BaseGetScopeNamespace._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGkeHubRestTransport._BaseGetScopeNamespace._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.GetScopeNamespace", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "GetScopeNamespace", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._GetScopeNamespace._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = fleet.Namespace() + pb_resp = fleet.Namespace.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_scope_namespace(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_scope_namespace_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = fleet.Namespace.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.get_scope_namespace", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "GetScopeNamespace", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetScopeRBACRoleBinding( + _BaseGkeHubRestTransport._BaseGetScopeRBACRoleBinding, GkeHubRestStub + ): + def __hash__(self): + return hash("GkeHubRestTransport.GetScopeRBACRoleBinding") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.GetScopeRBACRoleBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> fleet.RBACRoleBinding: + r"""Call the get scope rbac role + binding method over HTTP. + + Args: + request (~.service.GetScopeRBACRoleBindingRequest): + The request object. Request message for the + ``GkeHub.GetScopeRBACRoleBinding`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.fleet.RBACRoleBinding: + RBACRoleBinding represents a + rbacrolebinding across the Fleet + + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseGetScopeRBACRoleBinding._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_scope_rbac_role_binding( + request, metadata + ) + transcoded_request = _BaseGkeHubRestTransport._BaseGetScopeRBACRoleBinding._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGkeHubRestTransport._BaseGetScopeRBACRoleBinding._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.GetScopeRBACRoleBinding", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "GetScopeRBACRoleBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._GetScopeRBACRoleBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = fleet.RBACRoleBinding() + pb_resp = fleet.RBACRoleBinding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_scope_rbac_role_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_scope_rbac_role_binding_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = fleet.RBACRoleBinding.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.get_scope_rbac_role_binding", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "GetScopeRBACRoleBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListBoundMemberships( + _BaseGkeHubRestTransport._BaseListBoundMemberships, GkeHubRestStub + ): + def __hash__(self): + return hash("GkeHubRestTransport.ListBoundMemberships") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.ListBoundMembershipsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.ListBoundMembershipsResponse: + r"""Call the list bound memberships method over HTTP. + + Args: + request (~.service.ListBoundMembershipsRequest): + The request object. Request to list Memberships bound to + a Scope. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.service.ListBoundMembershipsResponse: + List of Memberships bound to a Scope. + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseListBoundMemberships._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_bound_memberships( + request, metadata + ) + transcoded_request = _BaseGkeHubRestTransport._BaseListBoundMemberships._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGkeHubRestTransport._BaseListBoundMemberships._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.ListBoundMemberships", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "ListBoundMemberships", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._ListBoundMemberships._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListBoundMembershipsResponse() + pb_resp = service.ListBoundMembershipsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_bound_memberships(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_bound_memberships_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = service.ListBoundMembershipsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.list_bound_memberships", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "ListBoundMemberships", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListFeatures(_BaseGkeHubRestTransport._BaseListFeatures, GkeHubRestStub): + def __hash__(self): + return hash("GkeHubRestTransport.ListFeatures") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.ListFeaturesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.ListFeaturesResponse: + r"""Call the list features method over HTTP. + + Args: + request (~.service.ListFeaturesRequest): + The request object. Request message for ``GkeHub.ListFeatures`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.service.ListFeaturesResponse: + Response message for the ``GkeHub.ListFeatures`` method. + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseListFeatures._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_features(request, metadata) + transcoded_request = ( + _BaseGkeHubRestTransport._BaseListFeatures._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGkeHubRestTransport._BaseListFeatures._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.ListFeatures", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "ListFeatures", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._ListFeatures._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListFeaturesResponse() + pb_resp = service.ListFeaturesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_features(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_features_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = service.ListFeaturesResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.list_features", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "ListFeatures", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListFleets(_BaseGkeHubRestTransport._BaseListFleets, GkeHubRestStub): + def __hash__(self): + return hash("GkeHubRestTransport.ListFleets") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.ListFleetsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.ListFleetsResponse: + r"""Call the list fleets method over HTTP. + + Args: + request (~.service.ListFleetsRequest): + The request object. Request message for the ``GkeHub.ListFleets`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.service.ListFleetsResponse: + Response message for the ``GkeHub.ListFleetsResponse`` + method. + + """ + + http_options = _BaseGkeHubRestTransport._BaseListFleets._get_http_options() + + request, metadata = self._interceptor.pre_list_fleets(request, metadata) + transcoded_request = ( + _BaseGkeHubRestTransport._BaseListFleets._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGkeHubRestTransport._BaseListFleets._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.ListFleets", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "ListFleets", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._ListFleets._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListFleetsResponse() + pb_resp = service.ListFleetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_fleets(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_fleets_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = service.ListFleetsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.list_fleets", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "ListFleets", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListMembershipBindings( + _BaseGkeHubRestTransport._BaseListMembershipBindings, GkeHubRestStub + ): + def __hash__(self): + return hash("GkeHubRestTransport.ListMembershipBindings") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.ListMembershipBindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.ListMembershipBindingsResponse: + r"""Call the list membership bindings method over HTTP. + + Args: + request (~.service.ListMembershipBindingsRequest): + The request object. Request to list MembershipBinding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.service.ListMembershipBindingsResponse: + List of MembershipBindings. + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseListMembershipBindings._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_membership_bindings( + request, metadata + ) + transcoded_request = _BaseGkeHubRestTransport._BaseListMembershipBindings._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGkeHubRestTransport._BaseListMembershipBindings._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.ListMembershipBindings", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "ListMembershipBindings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._ListMembershipBindings._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListMembershipBindingsResponse() + pb_resp = service.ListMembershipBindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_membership_bindings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_membership_bindings_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = service.ListMembershipBindingsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.list_membership_bindings", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "ListMembershipBindings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListMembershipRBACRoleBindings( + _BaseGkeHubRestTransport._BaseListMembershipRBACRoleBindings, GkeHubRestStub + ): + def __hash__(self): + return hash("GkeHubRestTransport.ListMembershipRBACRoleBindings") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.ListMembershipRBACRoleBindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.ListMembershipRBACRoleBindingsResponse: + r"""Call the list membership rbac role + bindings method over HTTP. + + Args: + request (~.service.ListMembershipRBACRoleBindingsRequest): + The request object. Request to list Membership + RBACRoleBindings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.service.ListMembershipRBACRoleBindingsResponse: + List of Membership RBACRoleBindings. + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseListMembershipRBACRoleBindings._get_http_options() + ) + + ( + request, + metadata, + ) = self._interceptor.pre_list_membership_rbac_role_bindings( + request, metadata + ) + transcoded_request = _BaseGkeHubRestTransport._BaseListMembershipRBACRoleBindings._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGkeHubRestTransport._BaseListMembershipRBACRoleBindings._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.ListMembershipRBACRoleBindings", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "ListMembershipRBACRoleBindings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + GkeHubRestTransport._ListMembershipRBACRoleBindings._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListMembershipRBACRoleBindingsResponse() + pb_resp = service.ListMembershipRBACRoleBindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_membership_rbac_role_bindings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + ( + resp, + _, + ) = self._interceptor.post_list_membership_rbac_role_bindings_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + service.ListMembershipRBACRoleBindingsResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.list_membership_rbac_role_bindings", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "ListMembershipRBACRoleBindings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListMemberships( + _BaseGkeHubRestTransport._BaseListMemberships, GkeHubRestStub + ): + def __hash__(self): + return hash("GkeHubRestTransport.ListMemberships") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.ListMembershipsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.ListMembershipsResponse: + r"""Call the list memberships method over HTTP. + + Args: + request (~.service.ListMembershipsRequest): + The request object. Request message for ``GkeHub.ListMemberships`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.service.ListMembershipsResponse: + Response message for the ``GkeHub.ListMemberships`` + method. + + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseListMemberships._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_memberships( + request, metadata + ) + transcoded_request = ( + _BaseGkeHubRestTransport._BaseListMemberships._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseGkeHubRestTransport._BaseListMemberships._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.ListMemberships", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "ListMemberships", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GkeHubRestTransport._ListMemberships._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListMembershipsResponse() + pb_resp = service.ListMembershipsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_memberships(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_memberships_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = service.ListMembershipsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.list_memberships", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "ListMemberships", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListPermittedScopes( + _BaseGkeHubRestTransport._BaseListPermittedScopes, GkeHubRestStub + ): + def __hash__(self): + return hash("GkeHubRestTransport.ListPermittedScopes") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.ListPermittedScopesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.ListPermittedScopesResponse: + r"""Call the list permitted scopes method over HTTP. + + Args: + request (~.service.ListPermittedScopesRequest): + The request object. Request to list permitted Scopes. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.service.ListPermittedScopesResponse: + List of permitted Scopes. + """ + + http_options = ( + _BaseGkeHubRestTransport._BaseListPermittedScopes._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_permitted_scopes( + request, metadata + ) + transcoded_request = _BaseGkeHubRestTransport._BaseListPermittedScopes._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGkeHubRestTransport._BaseListPermittedScopes._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.ListPermittedScopes", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "ListPermittedScopes", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1", + # Send the request + response = GkeHubRestTransport._ListPermittedScopes._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) - self._operations_client = operations_v1.AbstractOperationsClient( - transport=rest_transport - ) + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) - # Return the client from cache. - return self._operations_client + # Return the response + resp = service.ListPermittedScopesResponse() + pb_resp = service.ListPermittedScopesResponse.pb(resp) - class _CreateFeature(_BaseGkeHubRestTransport._BaseCreateFeature, GkeHubRestStub): + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_permitted_scopes(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_permitted_scopes_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = service.ListPermittedScopesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.gkehub_v1.GkeHubClient.list_permitted_scopes", + extra={ + "serviceName": "google.cloud.gkehub.v1.GkeHub", + "rpcName": "ListPermittedScopes", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListScopeNamespaces( + _BaseGkeHubRestTransport._BaseListScopeNamespaces, GkeHubRestStub + ): def __hash__(self): - return hash("GkeHubRestTransport.CreateFeature") + return hash("GkeHubRestTransport.ListScopeNamespaces") @staticmethod def _get_response( @@ -864,23 +7703,22 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, ) return response def __call__( self, - request: service.CreateFeatureRequest, + request: service.ListScopeNamespacesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the create feature method over HTTP. + ) -> service.ListScopeNamespacesResponse: + r"""Call the list scope namespaces method over HTTP. Args: - request (~.service.CreateFeatureRequest): - The request object. Request message for the ``GkeHub.CreateFeature`` method. + request (~.service.ListScopeNamespacesRequest): + The request object. Request to list fleet namespaces. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -890,33 +7728,24 @@ def __call__( be of type `bytes`. Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - + ~.service.ListScopeNamespacesResponse: + List of fleet namespaces. """ http_options = ( - _BaseGkeHubRestTransport._BaseCreateFeature._get_http_options() + _BaseGkeHubRestTransport._BaseListScopeNamespaces._get_http_options() ) - request, metadata = self._interceptor.pre_create_feature(request, metadata) - transcoded_request = ( - _BaseGkeHubRestTransport._BaseCreateFeature._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_list_scope_namespaces( + request, metadata ) - - body = _BaseGkeHubRestTransport._BaseCreateFeature._get_request_body_json( - transcoded_request + transcoded_request = _BaseGkeHubRestTransport._BaseListScopeNamespaces._get_transcoded_request( + http_options, request ) # Jsonify the query params - query_params = ( - _BaseGkeHubRestTransport._BaseCreateFeature._get_query_params_json( - transcoded_request - ) + query_params = _BaseGkeHubRestTransport._BaseListScopeNamespaces._get_query_params_json( + transcoded_request ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -937,24 +7766,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.gkehub_v1.GkeHubClient.CreateFeature", + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.ListScopeNamespaces", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "CreateFeature", + "rpcName": "ListScopeNamespaces", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = GkeHubRestTransport._CreateFeature._get_response( + response = GkeHubRestTransport._ListScopeNamespaces._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -963,19 +7791,23 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = service.ListScopeNamespacesResponse() + pb_resp = service.ListScopeNamespacesResponse.pb(resp) - resp = self._interceptor.post_create_feature(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_scope_namespaces(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_feature_with_metadata( + resp, _ = self._interceptor.post_list_scope_namespaces_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = json_format.MessageToJson(resp) + response_payload = service.ListScopeNamespacesResponse.to_json( + response + ) except: response_payload = None http_response = { @@ -984,21 +7816,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.gkehub_v1.GkeHubClient.create_feature", + "Received response for google.cloud.gkehub_v1.GkeHubClient.list_scope_namespaces", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "CreateFeature", + "rpcName": "ListScopeNamespaces", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _CreateMembership( - _BaseGkeHubRestTransport._BaseCreateMembership, GkeHubRestStub + class _ListScopeRBACRoleBindings( + _BaseGkeHubRestTransport._BaseListScopeRBACRoleBindings, GkeHubRestStub ): def __hash__(self): - return hash("GkeHubRestTransport.CreateMembership") + return hash("GkeHubRestTransport.ListScopeRBACRoleBindings") @staticmethod def _get_response( @@ -1019,64 +7851,51 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, ) return response def __call__( self, - request: service.CreateMembershipRequest, + request: service.ListScopeRBACRoleBindingsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the create membership method over HTTP. - - Args: - request (~.service.CreateMembershipRequest): - The request object. Request message for the ``GkeHub.CreateMembership`` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - + ) -> service.ListScopeRBACRoleBindingsResponse: + r"""Call the list scope rbac role + bindings method over HTTP. + + Args: + request (~.service.ListScopeRBACRoleBindingsRequest): + The request object. Request to list Scope + RBACRoleBindings. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.service.ListScopeRBACRoleBindingsResponse: + List of Scope RBACRoleBindings. """ http_options = ( - _BaseGkeHubRestTransport._BaseCreateMembership._get_http_options() + _BaseGkeHubRestTransport._BaseListScopeRBACRoleBindings._get_http_options() ) - request, metadata = self._interceptor.pre_create_membership( + request, metadata = self._interceptor.pre_list_scope_rbac_role_bindings( request, metadata ) - transcoded_request = ( - _BaseGkeHubRestTransport._BaseCreateMembership._get_transcoded_request( - http_options, request - ) - ) - - body = ( - _BaseGkeHubRestTransport._BaseCreateMembership._get_request_body_json( - transcoded_request - ) + transcoded_request = _BaseGkeHubRestTransport._BaseListScopeRBACRoleBindings._get_transcoded_request( + http_options, request ) # Jsonify the query params - query_params = ( - _BaseGkeHubRestTransport._BaseCreateMembership._get_query_params_json( - transcoded_request - ) + query_params = _BaseGkeHubRestTransport._BaseListScopeRBACRoleBindings._get_query_params_json( + transcoded_request ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -1097,24 +7916,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.gkehub_v1.GkeHubClient.CreateMembership", + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.ListScopeRBACRoleBindings", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "CreateMembership", + "rpcName": "ListScopeRBACRoleBindings", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = GkeHubRestTransport._CreateMembership._get_response( + response = GkeHubRestTransport._ListScopeRBACRoleBindings._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1123,19 +7941,26 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = service.ListScopeRBACRoleBindingsResponse() + pb_resp = service.ListScopeRBACRoleBindingsResponse.pb(resp) - resp = self._interceptor.post_create_membership(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_scope_rbac_role_bindings(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_membership_with_metadata( + ( + resp, + _, + ) = self._interceptor.post_list_scope_rbac_role_bindings_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = json_format.MessageToJson(resp) + response_payload = ( + service.ListScopeRBACRoleBindingsResponse.to_json(response) + ) except: response_payload = None http_response = { @@ -1144,19 +7969,19 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.gkehub_v1.GkeHubClient.create_membership", + "Received response for google.cloud.gkehub_v1.GkeHubClient.list_scope_rbac_role_bindings", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "CreateMembership", + "rpcName": "ListScopeRBACRoleBindings", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteFeature(_BaseGkeHubRestTransport._BaseDeleteFeature, GkeHubRestStub): + class _ListScopes(_BaseGkeHubRestTransport._BaseListScopes, GkeHubRestStub): def __hash__(self): - return hash("GkeHubRestTransport.DeleteFeature") + return hash("GkeHubRestTransport.ListScopes") @staticmethod def _get_response( @@ -1182,17 +8007,17 @@ def _get_response( def __call__( self, - request: service.DeleteFeatureRequest, + request: service.ListScopesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the delete feature method over HTTP. + ) -> service.ListScopesResponse: + r"""Call the list scopes method over HTTP. Args: - request (~.service.DeleteFeatureRequest): - The request object. Request message for ``GkeHub.DeleteFeature`` method. + request (~.service.ListScopesRequest): + The request object. Request to list Scopes. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1202,27 +8027,22 @@ def __call__( be of type `bytes`. Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - + ~.service.ListScopesResponse: + List of Scopes. """ - http_options = ( - _BaseGkeHubRestTransport._BaseDeleteFeature._get_http_options() - ) + http_options = _BaseGkeHubRestTransport._BaseListScopes._get_http_options() - request, metadata = self._interceptor.pre_delete_feature(request, metadata) + request, metadata = self._interceptor.pre_list_scopes(request, metadata) transcoded_request = ( - _BaseGkeHubRestTransport._BaseDeleteFeature._get_transcoded_request( + _BaseGkeHubRestTransport._BaseListScopes._get_transcoded_request( http_options, request ) ) # Jsonify the query params query_params = ( - _BaseGkeHubRestTransport._BaseDeleteFeature._get_query_params_json( + _BaseGkeHubRestTransport._BaseListScopes._get_query_params_json( transcoded_request ) ) @@ -1245,17 +8065,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.gkehub_v1.GkeHubClient.DeleteFeature", + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.ListScopes", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "DeleteFeature", + "rpcName": "ListScopes", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = GkeHubRestTransport._DeleteFeature._get_response( + response = GkeHubRestTransport._ListScopes._get_response( self._host, metadata, query_params, @@ -1270,19 +8090,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = service.ListScopesResponse() + pb_resp = service.ListScopesResponse.pb(resp) - resp = self._interceptor.post_delete_feature(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_scopes(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_feature_with_metadata( + resp, _ = self._interceptor.post_list_scopes_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = json_format.MessageToJson(resp) + response_payload = service.ListScopesResponse.to_json(response) except: response_payload = None http_response = { @@ -1291,21 +8113,19 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.gkehub_v1.GkeHubClient.delete_feature", + "Received response for google.cloud.gkehub_v1.GkeHubClient.list_scopes", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "DeleteFeature", + "rpcName": "ListScopes", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteMembership( - _BaseGkeHubRestTransport._BaseDeleteMembership, GkeHubRestStub - ): + class _UpdateFeature(_BaseGkeHubRestTransport._BaseUpdateFeature, GkeHubRestStub): def __hash__(self): - return hash("GkeHubRestTransport.DeleteMembership") + return hash("GkeHubRestTransport.UpdateFeature") @staticmethod def _get_response( @@ -1326,22 +8146,23 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: service.DeleteMembershipRequest, + request: service.UpdateFeatureRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the delete membership method over HTTP. + r"""Call the update feature method over HTTP. Args: - request (~.service.DeleteMembershipRequest): - The request object. Request message for ``GkeHub.DeleteMembership`` method. + request (~.service.UpdateFeatureRequest): + The request object. Request message for ``GkeHub.UpdateFeature`` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1359,21 +8180,23 @@ def __call__( """ http_options = ( - _BaseGkeHubRestTransport._BaseDeleteMembership._get_http_options() + _BaseGkeHubRestTransport._BaseUpdateFeature._get_http_options() ) - request, metadata = self._interceptor.pre_delete_membership( - request, metadata - ) + request, metadata = self._interceptor.pre_update_feature(request, metadata) transcoded_request = ( - _BaseGkeHubRestTransport._BaseDeleteMembership._get_transcoded_request( + _BaseGkeHubRestTransport._BaseUpdateFeature._get_transcoded_request( http_options, request ) ) + body = _BaseGkeHubRestTransport._BaseUpdateFeature._get_request_body_json( + transcoded_request + ) + # Jsonify the query params query_params = ( - _BaseGkeHubRestTransport._BaseDeleteMembership._get_query_params_json( + _BaseGkeHubRestTransport._BaseUpdateFeature._get_query_params_json( transcoded_request ) ) @@ -1396,23 +8219,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.gkehub_v1.GkeHubClient.DeleteMembership", + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.UpdateFeature", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "DeleteMembership", + "rpcName": "UpdateFeature", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = GkeHubRestTransport._DeleteMembership._get_response( + response = GkeHubRestTransport._UpdateFeature._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1424,9 +8248,9 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_membership(resp) + resp = self._interceptor.post_update_feature(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_membership_with_metadata( + resp, _ = self._interceptor.post_update_feature_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -1442,21 +8266,19 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.gkehub_v1.GkeHubClient.delete_membership", + "Received response for google.cloud.gkehub_v1.GkeHubClient.update_feature", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "DeleteMembership", + "rpcName": "UpdateFeature", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GenerateConnectManifest( - _BaseGkeHubRestTransport._BaseGenerateConnectManifest, GkeHubRestStub - ): + class _UpdateFleet(_BaseGkeHubRestTransport._BaseUpdateFleet, GkeHubRestStub): def __hash__(self): - return hash("GkeHubRestTransport.GenerateConnectManifest") + return hash("GkeHubRestTransport.UpdateFleet") @staticmethod def _get_response( @@ -1477,23 +8299,23 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: service.GenerateConnectManifestRequest, + request: service.UpdateFleetRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> service.GenerateConnectManifestResponse: - r"""Call the generate connect manifest method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the update fleet method over HTTP. Args: - request (~.service.GenerateConnectManifestRequest): - The request object. Request message for ``GkeHub.GenerateConnectManifest`` - method. . + request (~.service.UpdateFleetRequest): + The request object. Request message for the ``GkeHub.UpdateFleet`` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1503,27 +8325,31 @@ def __call__( be of type `bytes`. Returns: - ~.service.GenerateConnectManifestResponse: - GenerateConnectManifestResponse - contains manifest information for - installing/upgrading a Connect agent. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = ( - _BaseGkeHubRestTransport._BaseGenerateConnectManifest._get_http_options() - ) + http_options = _BaseGkeHubRestTransport._BaseUpdateFleet._get_http_options() - request, metadata = self._interceptor.pre_generate_connect_manifest( - request, metadata + request, metadata = self._interceptor.pre_update_fleet(request, metadata) + transcoded_request = ( + _BaseGkeHubRestTransport._BaseUpdateFleet._get_transcoded_request( + http_options, request + ) ) - transcoded_request = _BaseGkeHubRestTransport._BaseGenerateConnectManifest._get_transcoded_request( - http_options, request + + body = _BaseGkeHubRestTransport._BaseUpdateFleet._get_request_body_json( + transcoded_request ) # Jsonify the query params - query_params = _BaseGkeHubRestTransport._BaseGenerateConnectManifest._get_query_params_json( - transcoded_request + query_params = ( + _BaseGkeHubRestTransport._BaseUpdateFleet._get_query_params_json( + transcoded_request + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -1544,23 +8370,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.gkehub_v1.GkeHubClient.GenerateConnectManifest", + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.UpdateFleet", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "GenerateConnectManifest", + "rpcName": "UpdateFleet", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = GkeHubRestTransport._GenerateConnectManifest._get_response( + response = GkeHubRestTransport._UpdateFleet._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1569,23 +8396,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = service.GenerateConnectManifestResponse() - pb_resp = service.GenerateConnectManifestResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_generate_connect_manifest(resp) + resp = self._interceptor.post_update_fleet(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_generate_connect_manifest_with_metadata( + resp, _ = self._interceptor.post_update_fleet_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = service.GenerateConnectManifestResponse.to_json( - response - ) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -1594,19 +8417,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.gkehub_v1.GkeHubClient.generate_connect_manifest", + "Received response for google.cloud.gkehub_v1.GkeHubClient.update_fleet", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "GenerateConnectManifest", + "rpcName": "UpdateFleet", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetFeature(_BaseGkeHubRestTransport._BaseGetFeature, GkeHubRestStub): + class _UpdateMembership( + _BaseGkeHubRestTransport._BaseUpdateMembership, GkeHubRestStub + ): def __hash__(self): - return hash("GkeHubRestTransport.GetFeature") + return hash("GkeHubRestTransport.UpdateMembership") @staticmethod def _get_response( @@ -1627,22 +8452,23 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: service.GetFeatureRequest, + request: service.UpdateMembershipRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> feature.Feature: - r"""Call the get feature method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the update membership method over HTTP. Args: - request (~.service.GetFeatureRequest): - The request object. Request message for ``GkeHub.GetFeature`` method. + request (~.service.UpdateMembershipRequest): + The request object. Request message for ``GkeHub.UpdateMembership`` method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1652,24 +8478,35 @@ def __call__( be of type `bytes`. Returns: - ~.feature.Feature: - Feature represents the settings and - status of any Hub Feature. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = _BaseGkeHubRestTransport._BaseGetFeature._get_http_options() + http_options = ( + _BaseGkeHubRestTransport._BaseUpdateMembership._get_http_options() + ) - request, metadata = self._interceptor.pre_get_feature(request, metadata) + request, metadata = self._interceptor.pre_update_membership( + request, metadata + ) transcoded_request = ( - _BaseGkeHubRestTransport._BaseGetFeature._get_transcoded_request( + _BaseGkeHubRestTransport._BaseUpdateMembership._get_transcoded_request( http_options, request ) ) + body = ( + _BaseGkeHubRestTransport._BaseUpdateMembership._get_request_body_json( + transcoded_request + ) + ) + # Jsonify the query params query_params = ( - _BaseGkeHubRestTransport._BaseGetFeature._get_query_params_json( + _BaseGkeHubRestTransport._BaseUpdateMembership._get_query_params_json( transcoded_request ) ) @@ -1692,23 +8529,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.gkehub_v1.GkeHubClient.GetFeature", + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.UpdateMembership", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "GetFeature", + "rpcName": "UpdateMembership", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = GkeHubRestTransport._GetFeature._get_response( + response = GkeHubRestTransport._UpdateMembership._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1717,21 +8555,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = feature.Feature() - pb_resp = feature.Feature.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_feature(resp) + resp = self._interceptor.post_update_membership(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_feature_with_metadata( + resp, _ = self._interceptor.post_update_membership_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = feature.Feature.to_json(response) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -1740,19 +8576,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.gkehub_v1.GkeHubClient.get_feature", + "Received response for google.cloud.gkehub_v1.GkeHubClient.update_membership", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "GetFeature", + "rpcName": "UpdateMembership", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetMembership(_BaseGkeHubRestTransport._BaseGetMembership, GkeHubRestStub): + class _UpdateMembershipBinding( + _BaseGkeHubRestTransport._BaseUpdateMembershipBinding, GkeHubRestStub + ): def __hash__(self): - return hash("GkeHubRestTransport.GetMembership") + return hash("GkeHubRestTransport.UpdateMembershipBinding") @staticmethod def _get_response( @@ -1773,22 +8611,24 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: service.GetMembershipRequest, + request: service.UpdateMembershipBindingRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> membership.Membership: - r"""Call the get membership method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the update membership binding method over HTTP. Args: - request (~.service.GetMembershipRequest): - The request object. Request message for ``GkeHub.GetMembership`` method. + request (~.service.UpdateMembershipBindingRequest): + The request object. Request to update a + MembershipBinding. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1798,28 +8638,31 @@ def __call__( be of type `bytes`. Returns: - ~.membership.Membership: - Membership contains information about - a member cluster. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ http_options = ( - _BaseGkeHubRestTransport._BaseGetMembership._get_http_options() + _BaseGkeHubRestTransport._BaseUpdateMembershipBinding._get_http_options() ) - request, metadata = self._interceptor.pre_get_membership(request, metadata) - transcoded_request = ( - _BaseGkeHubRestTransport._BaseGetMembership._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_update_membership_binding( + request, metadata + ) + transcoded_request = _BaseGkeHubRestTransport._BaseUpdateMembershipBinding._get_transcoded_request( + http_options, request + ) + + body = _BaseGkeHubRestTransport._BaseUpdateMembershipBinding._get_request_body_json( + transcoded_request ) # Jsonify the query params - query_params = ( - _BaseGkeHubRestTransport._BaseGetMembership._get_query_params_json( - transcoded_request - ) + query_params = _BaseGkeHubRestTransport._BaseUpdateMembershipBinding._get_query_params_json( + transcoded_request ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -1840,23 +8683,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.gkehub_v1.GkeHubClient.GetMembership", + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.UpdateMembershipBinding", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "GetMembership", + "rpcName": "UpdateMembershipBinding", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = GkeHubRestTransport._GetMembership._get_response( + response = GkeHubRestTransport._UpdateMembershipBinding._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1865,21 +8709,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = membership.Membership() - pb_resp = membership.Membership.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_membership(resp) + resp = self._interceptor.post_update_membership_binding(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_membership_with_metadata( + resp, _ = self._interceptor.post_update_membership_binding_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = membership.Membership.to_json(response) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -1888,19 +8730,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.gkehub_v1.GkeHubClient.get_membership", + "Received response for google.cloud.gkehub_v1.GkeHubClient.update_membership_binding", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "GetMembership", + "rpcName": "UpdateMembershipBinding", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListFeatures(_BaseGkeHubRestTransport._BaseListFeatures, GkeHubRestStub): + class _UpdateMembershipRBACRoleBinding( + _BaseGkeHubRestTransport._BaseUpdateMembershipRBACRoleBinding, GkeHubRestStub + ): def __hash__(self): - return hash("GkeHubRestTransport.ListFeatures") + return hash("GkeHubRestTransport.UpdateMembershipRBACRoleBinding") @staticmethod def _get_response( @@ -1921,51 +8765,62 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: service.ListFeaturesRequest, + request: service.UpdateMembershipRBACRoleBindingRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> service.ListFeaturesResponse: - r"""Call the list features method over HTTP. - - Args: - request (~.service.ListFeaturesRequest): - The request object. Request message for ``GkeHub.ListFeatures`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. + ) -> operations_pb2.Operation: + r"""Call the update membership rbac + role binding method over HTTP. + + Args: + request (~.service.UpdateMembershipRBACRoleBindingRequest): + The request object. Request to update a membership + rbacrolebinding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. - Returns: - ~.service.ListFeaturesResponse: - Response message for the ``GkeHub.ListFeatures`` method. """ http_options = ( - _BaseGkeHubRestTransport._BaseListFeatures._get_http_options() + _BaseGkeHubRestTransport._BaseUpdateMembershipRBACRoleBinding._get_http_options() ) - request, metadata = self._interceptor.pre_list_features(request, metadata) - transcoded_request = ( - _BaseGkeHubRestTransport._BaseListFeatures._get_transcoded_request( - http_options, request - ) + ( + request, + metadata, + ) = self._interceptor.pre_update_membership_rbac_role_binding( + request, metadata + ) + transcoded_request = _BaseGkeHubRestTransport._BaseUpdateMembershipRBACRoleBinding._get_transcoded_request( + http_options, request + ) + + body = _BaseGkeHubRestTransport._BaseUpdateMembershipRBACRoleBinding._get_request_body_json( + transcoded_request ) # Jsonify the query params - query_params = ( - _BaseGkeHubRestTransport._BaseListFeatures._get_query_params_json( - transcoded_request - ) + query_params = _BaseGkeHubRestTransport._BaseUpdateMembershipRBACRoleBinding._get_query_params_json( + transcoded_request ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -1986,23 +8841,26 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.gkehub_v1.GkeHubClient.ListFeatures", + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.UpdateMembershipRBACRoleBinding", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "ListFeatures", + "rpcName": "UpdateMembershipRBACRoleBinding", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = GkeHubRestTransport._ListFeatures._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, + response = ( + GkeHubRestTransport._UpdateMembershipRBACRoleBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2011,21 +8869,22 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = service.ListFeaturesResponse() - pb_resp = service.ListFeaturesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_features(resp) + resp = self._interceptor.post_update_membership_rbac_role_binding(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_features_with_metadata( + ( + resp, + _, + ) = self._interceptor.post_update_membership_rbac_role_binding_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = service.ListFeaturesResponse.to_json(response) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -2034,21 +8893,19 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.gkehub_v1.GkeHubClient.list_features", + "Received response for google.cloud.gkehub_v1.GkeHubClient.update_membership_rbac_role_binding", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "ListFeatures", + "rpcName": "UpdateMembershipRBACRoleBinding", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListMemberships( - _BaseGkeHubRestTransport._BaseListMemberships, GkeHubRestStub - ): + class _UpdateScope(_BaseGkeHubRestTransport._BaseUpdateScope, GkeHubRestStub): def __hash__(self): - return hash("GkeHubRestTransport.ListMemberships") + return hash("GkeHubRestTransport.UpdateScope") @staticmethod def _get_response( @@ -2069,22 +8926,23 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: service.ListMembershipsRequest, + request: service.UpdateScopeRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> service.ListMembershipsResponse: - r"""Call the list memberships method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the update scope method over HTTP. Args: - request (~.service.ListMembershipsRequest): - The request object. Request message for ``GkeHub.ListMemberships`` method. + request (~.service.UpdateScopeRequest): + The request object. Request to update a Scope. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2094,28 +8952,29 @@ def __call__( be of type `bytes`. Returns: - ~.service.ListMembershipsResponse: - Response message for the ``GkeHub.ListMemberships`` - method. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = ( - _BaseGkeHubRestTransport._BaseListMemberships._get_http_options() - ) + http_options = _BaseGkeHubRestTransport._BaseUpdateScope._get_http_options() - request, metadata = self._interceptor.pre_list_memberships( - request, metadata - ) + request, metadata = self._interceptor.pre_update_scope(request, metadata) transcoded_request = ( - _BaseGkeHubRestTransport._BaseListMemberships._get_transcoded_request( + _BaseGkeHubRestTransport._BaseUpdateScope._get_transcoded_request( http_options, request ) ) + body = _BaseGkeHubRestTransport._BaseUpdateScope._get_request_body_json( + transcoded_request + ) + # Jsonify the query params query_params = ( - _BaseGkeHubRestTransport._BaseListMemberships._get_query_params_json( + _BaseGkeHubRestTransport._BaseUpdateScope._get_query_params_json( transcoded_request ) ) @@ -2138,23 +8997,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.gkehub_v1.GkeHubClient.ListMemberships", + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.UpdateScope", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "ListMemberships", + "rpcName": "UpdateScope", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = GkeHubRestTransport._ListMemberships._get_response( + response = GkeHubRestTransport._UpdateScope._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2163,21 +9023,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = service.ListMembershipsResponse() - pb_resp = service.ListMembershipsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_memberships(resp) + resp = self._interceptor.post_update_scope(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_memberships_with_metadata( + resp, _ = self._interceptor.post_update_scope_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = service.ListMembershipsResponse.to_json(response) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -2186,19 +9044,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.gkehub_v1.GkeHubClient.list_memberships", + "Received response for google.cloud.gkehub_v1.GkeHubClient.update_scope", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "ListMemberships", + "rpcName": "UpdateScope", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _UpdateFeature(_BaseGkeHubRestTransport._BaseUpdateFeature, GkeHubRestStub): + class _UpdateScopeNamespace( + _BaseGkeHubRestTransport._BaseUpdateScopeNamespace, GkeHubRestStub + ): def __hash__(self): - return hash("GkeHubRestTransport.UpdateFeature") + return hash("GkeHubRestTransport.UpdateScopeNamespace") @staticmethod def _get_response( @@ -2225,17 +9085,17 @@ def _get_response( def __call__( self, - request: service.UpdateFeatureRequest, + request: service.UpdateScopeNamespaceRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the update feature method over HTTP. + r"""Call the update scope namespace method over HTTP. Args: - request (~.service.UpdateFeatureRequest): - The request object. Request message for ``GkeHub.UpdateFeature`` method. + request (~.service.UpdateScopeNamespaceRequest): + The request object. Request to update a fleet namespace. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2253,25 +9113,23 @@ def __call__( """ http_options = ( - _BaseGkeHubRestTransport._BaseUpdateFeature._get_http_options() + _BaseGkeHubRestTransport._BaseUpdateScopeNamespace._get_http_options() ) - request, metadata = self._interceptor.pre_update_feature(request, metadata) - transcoded_request = ( - _BaseGkeHubRestTransport._BaseUpdateFeature._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_update_scope_namespace( + request, metadata + ) + transcoded_request = _BaseGkeHubRestTransport._BaseUpdateScopeNamespace._get_transcoded_request( + http_options, request ) - body = _BaseGkeHubRestTransport._BaseUpdateFeature._get_request_body_json( + body = _BaseGkeHubRestTransport._BaseUpdateScopeNamespace._get_request_body_json( transcoded_request ) # Jsonify the query params - query_params = ( - _BaseGkeHubRestTransport._BaseUpdateFeature._get_query_params_json( - transcoded_request - ) + query_params = _BaseGkeHubRestTransport._BaseUpdateScopeNamespace._get_query_params_json( + transcoded_request ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -2292,17 +9150,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.gkehub_v1.GkeHubClient.UpdateFeature", + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.UpdateScopeNamespace", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "UpdateFeature", + "rpcName": "UpdateScopeNamespace", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = GkeHubRestTransport._UpdateFeature._get_response( + response = GkeHubRestTransport._UpdateScopeNamespace._get_response( self._host, metadata, query_params, @@ -2321,9 +9179,9 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_feature(resp) + resp = self._interceptor.post_update_scope_namespace(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_feature_with_metadata( + resp, _ = self._interceptor.post_update_scope_namespace_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -2339,21 +9197,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.gkehub_v1.GkeHubClient.update_feature", + "Received response for google.cloud.gkehub_v1.GkeHubClient.update_scope_namespace", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "UpdateFeature", + "rpcName": "UpdateScopeNamespace", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _UpdateMembership( - _BaseGkeHubRestTransport._BaseUpdateMembership, GkeHubRestStub + class _UpdateScopeRBACRoleBinding( + _BaseGkeHubRestTransport._BaseUpdateScopeRBACRoleBinding, GkeHubRestStub ): def __hash__(self): - return hash("GkeHubRestTransport.UpdateMembership") + return hash("GkeHubRestTransport.UpdateScopeRBACRoleBinding") @staticmethod def _get_response( @@ -2380,57 +9238,53 @@ def _get_response( def __call__( self, - request: service.UpdateMembershipRequest, + request: service.UpdateScopeRBACRoleBindingRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the update membership method over HTTP. - - Args: - request (~.service.UpdateMembershipRequest): - The request object. Request message for ``GkeHub.UpdateMembership`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. + r"""Call the update scope rbac role + binding method over HTTP. + + Args: + request (~.service.UpdateScopeRBACRoleBindingRequest): + The request object. Request to update a scope + rbacrolebinding. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ http_options = ( - _BaseGkeHubRestTransport._BaseUpdateMembership._get_http_options() + _BaseGkeHubRestTransport._BaseUpdateScopeRBACRoleBinding._get_http_options() ) - request, metadata = self._interceptor.pre_update_membership( + request, metadata = self._interceptor.pre_update_scope_rbac_role_binding( request, metadata ) - transcoded_request = ( - _BaseGkeHubRestTransport._BaseUpdateMembership._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseGkeHubRestTransport._BaseUpdateScopeRBACRoleBinding._get_transcoded_request( + http_options, request ) - body = ( - _BaseGkeHubRestTransport._BaseUpdateMembership._get_request_body_json( - transcoded_request - ) + body = _BaseGkeHubRestTransport._BaseUpdateScopeRBACRoleBinding._get_request_body_json( + transcoded_request ) # Jsonify the query params - query_params = ( - _BaseGkeHubRestTransport._BaseUpdateMembership._get_query_params_json( - transcoded_request - ) + query_params = _BaseGkeHubRestTransport._BaseUpdateScopeRBACRoleBinding._get_query_params_json( + transcoded_request ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -2451,17 +9305,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.gkehub_v1.GkeHubClient.UpdateMembership", + f"Sending request for google.cloud.gkehub_v1.GkeHubClient.UpdateScopeRBACRoleBinding", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "UpdateMembership", + "rpcName": "UpdateScopeRBACRoleBinding", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = GkeHubRestTransport._UpdateMembership._get_response( + response = GkeHubRestTransport._UpdateScopeRBACRoleBinding._get_response( self._host, metadata, query_params, @@ -2480,9 +9334,12 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_membership(resp) + resp = self._interceptor.post_update_scope_rbac_role_binding(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_membership_with_metadata( + ( + resp, + _, + ) = self._interceptor.post_update_scope_rbac_role_binding_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -2498,10 +9355,10 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.gkehub_v1.GkeHubClient.update_membership", + "Received response for google.cloud.gkehub_v1.GkeHubClient.update_scope_rbac_role_binding", extra={ "serviceName": "google.cloud.gkehub.v1.GkeHub", - "rpcName": "UpdateMembership", + "rpcName": "UpdateScopeRBACRoleBinding", "metadata": http_response["headers"], "httpResponse": http_response, }, @@ -2516,6 +9373,14 @@ def create_feature( # In C++ this would require a dynamic_cast return self._CreateFeature(self._session, self._host, self._interceptor) # type: ignore + @property + def create_fleet( + self, + ) -> Callable[[service.CreateFleetRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateFleet(self._session, self._host, self._interceptor) # type: ignore + @property def create_membership( self, @@ -2524,6 +9389,50 @@ def create_membership( # In C++ this would require a dynamic_cast return self._CreateMembership(self._session, self._host, self._interceptor) # type: ignore + @property + def create_membership_binding( + self, + ) -> Callable[[service.CreateMembershipBindingRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateMembershipBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_membership_rbac_role_binding( + self, + ) -> Callable[ + [service.CreateMembershipRBACRoleBindingRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateMembershipRBACRoleBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_scope( + self, + ) -> Callable[[service.CreateScopeRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateScope(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_scope_namespace( + self, + ) -> Callable[[service.CreateScopeNamespaceRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateScopeNamespace(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_scope_rbac_role_binding( + self, + ) -> Callable[ + [service.CreateScopeRBACRoleBindingRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateScopeRBACRoleBinding(self._session, self._host, self._interceptor) # type: ignore + @property def delete_feature( self, @@ -2532,6 +9441,14 @@ def delete_feature( # In C++ this would require a dynamic_cast return self._DeleteFeature(self._session, self._host, self._interceptor) # type: ignore + @property + def delete_fleet( + self, + ) -> Callable[[service.DeleteFleetRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteFleet(self._session, self._host, self._interceptor) # type: ignore + @property def delete_membership( self, @@ -2540,6 +9457,50 @@ def delete_membership( # In C++ this would require a dynamic_cast return self._DeleteMembership(self._session, self._host, self._interceptor) # type: ignore + @property + def delete_membership_binding( + self, + ) -> Callable[[service.DeleteMembershipBindingRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteMembershipBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_membership_rbac_role_binding( + self, + ) -> Callable[ + [service.DeleteMembershipRBACRoleBindingRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteMembershipRBACRoleBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_scope( + self, + ) -> Callable[[service.DeleteScopeRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteScope(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_scope_namespace( + self, + ) -> Callable[[service.DeleteScopeNamespaceRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteScopeNamespace(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_scope_rbac_role_binding( + self, + ) -> Callable[ + [service.DeleteScopeRBACRoleBindingRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteScopeRBACRoleBinding(self._session, self._host, self._interceptor) # type: ignore + @property def generate_connect_manifest( self, @@ -2551,12 +9512,29 @@ def generate_connect_manifest( # In C++ this would require a dynamic_cast return self._GenerateConnectManifest(self._session, self._host, self._interceptor) # type: ignore + @property + def generate_membership_rbac_role_binding_yaml( + self, + ) -> Callable[ + [service.GenerateMembershipRBACRoleBindingYAMLRequest], + service.GenerateMembershipRBACRoleBindingYAMLResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateMembershipRBACRoleBindingYAML(self._session, self._host, self._interceptor) # type: ignore + @property def get_feature(self) -> Callable[[service.GetFeatureRequest], feature.Feature]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast return self._GetFeature(self._session, self._host, self._interceptor) # type: ignore + @property + def get_fleet(self) -> Callable[[service.GetFleetRequest], fleet.Fleet]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetFleet(self._session, self._host, self._interceptor) # type: ignore + @property def get_membership( self, @@ -2565,6 +9543,54 @@ def get_membership( # In C++ this would require a dynamic_cast return self._GetMembership(self._session, self._host, self._interceptor) # type: ignore + @property + def get_membership_binding( + self, + ) -> Callable[[service.GetMembershipBindingRequest], fleet.MembershipBinding]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetMembershipBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_membership_rbac_role_binding( + self, + ) -> Callable[[service.GetMembershipRBACRoleBindingRequest], fleet.RBACRoleBinding]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetMembershipRBACRoleBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_scope(self) -> Callable[[service.GetScopeRequest], fleet.Scope]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetScope(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_scope_namespace( + self, + ) -> Callable[[service.GetScopeNamespaceRequest], fleet.Namespace]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetScopeNamespace(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_scope_rbac_role_binding( + self, + ) -> Callable[[service.GetScopeRBACRoleBindingRequest], fleet.RBACRoleBinding]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetScopeRBACRoleBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_bound_memberships( + self, + ) -> Callable[ + [service.ListBoundMembershipsRequest], service.ListBoundMembershipsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListBoundMemberships(self._session, self._host, self._interceptor) # type: ignore + @property def list_features( self, @@ -2573,6 +9599,35 @@ def list_features( # In C++ this would require a dynamic_cast return self._ListFeatures(self._session, self._host, self._interceptor) # type: ignore + @property + def list_fleets( + self, + ) -> Callable[[service.ListFleetsRequest], service.ListFleetsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListFleets(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_membership_bindings( + self, + ) -> Callable[ + [service.ListMembershipBindingsRequest], service.ListMembershipBindingsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListMembershipBindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_membership_rbac_role_bindings( + self, + ) -> Callable[ + [service.ListMembershipRBACRoleBindingsRequest], + service.ListMembershipRBACRoleBindingsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListMembershipRBACRoleBindings(self._session, self._host, self._interceptor) # type: ignore + @property def list_memberships( self, @@ -2581,6 +9636,45 @@ def list_memberships( # In C++ this would require a dynamic_cast return self._ListMemberships(self._session, self._host, self._interceptor) # type: ignore + @property + def list_permitted_scopes( + self, + ) -> Callable[ + [service.ListPermittedScopesRequest], service.ListPermittedScopesResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListPermittedScopes(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_scope_namespaces( + self, + ) -> Callable[ + [service.ListScopeNamespacesRequest], service.ListScopeNamespacesResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListScopeNamespaces(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_scope_rbac_role_bindings( + self, + ) -> Callable[ + [service.ListScopeRBACRoleBindingsRequest], + service.ListScopeRBACRoleBindingsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListScopeRBACRoleBindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_scopes( + self, + ) -> Callable[[service.ListScopesRequest], service.ListScopesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListScopes(self._session, self._host, self._interceptor) # type: ignore + @property def update_feature( self, @@ -2589,6 +9683,14 @@ def update_feature( # In C++ this would require a dynamic_cast return self._UpdateFeature(self._session, self._host, self._interceptor) # type: ignore + @property + def update_fleet( + self, + ) -> Callable[[service.UpdateFleetRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateFleet(self._session, self._host, self._interceptor) # type: ignore + @property def update_membership( self, @@ -2597,6 +9699,50 @@ def update_membership( # In C++ this would require a dynamic_cast return self._UpdateMembership(self._session, self._host, self._interceptor) # type: ignore + @property + def update_membership_binding( + self, + ) -> Callable[[service.UpdateMembershipBindingRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateMembershipBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_membership_rbac_role_binding( + self, + ) -> Callable[ + [service.UpdateMembershipRBACRoleBindingRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateMembershipRBACRoleBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_scope( + self, + ) -> Callable[[service.UpdateScopeRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateScope(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_scope_namespace( + self, + ) -> Callable[[service.UpdateScopeNamespaceRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateScopeNamespace(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_scope_rbac_role_binding( + self, + ) -> Callable[ + [service.UpdateScopeRBACRoleBindingRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateScopeRBACRoleBinding(self._session, self._host, self._interceptor) # type: ignore + @property def kind(self) -> str: return "rest" diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/rest_base.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/rest_base.py index 4530ffe30939..5012dbda57e9 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/rest_base.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/services/gke_hub/transports/rest_base.py @@ -21,7 +21,7 @@ from google.longrunning import operations_pb2 # type: ignore from google.protobuf import json_format -from google.cloud.gkehub_v1.types import feature, membership, service +from google.cloud.gkehub_v1.types import feature, fleet, membership, service from .base import DEFAULT_CLIENT_INFO, GkeHubTransport @@ -130,13 +130,1570 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseCreateFleet: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/fleets", + "body": "fleet", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.CreateFleetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseCreateFleet._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseCreateMembership: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "membershipId": "", - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "membershipId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/memberships", + "body": "resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.CreateMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseCreateMembership._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateMembershipBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "membershipBindingId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/memberships/*}/bindings", + "body": "membership_binding", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.CreateMembershipBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseCreateMembershipBinding._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateMembershipRBACRoleBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "rbacrolebindingId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/memberships/*}/rbacrolebindings", + "body": "rbacrolebinding", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.CreateMembershipRBACRoleBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseCreateMembershipRBACRoleBinding._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateScope: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "scopeId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/scopes", + "body": "scope", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.CreateScopeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseCreateScope._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateScopeNamespace: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "scopeNamespaceId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/scopes/*}/namespaces", + "body": "scope_namespace", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.CreateScopeNamespaceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseCreateScopeNamespace._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateScopeRBACRoleBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "rbacrolebindingId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/scopes/*}/rbacrolebindings", + "body": "rbacrolebinding", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.CreateScopeRBACRoleBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseCreateScopeRBACRoleBinding._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteFeature: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/features/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.DeleteFeatureRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteFleet: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/fleets/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.DeleteFleetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseDeleteFleet._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteMembership: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/memberships/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.DeleteMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseDeleteMembership._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteMembershipBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/memberships/*/bindings/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.DeleteMembershipBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseDeleteMembershipBinding._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteMembershipRBACRoleBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/memberships/*/rbacrolebindings/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.DeleteMembershipRBACRoleBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseDeleteMembershipRBACRoleBinding._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteScope: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/scopes/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.DeleteScopeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseDeleteScope._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteScopeNamespace: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/scopes/*/namespaces/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.DeleteScopeNamespaceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseDeleteScopeNamespace._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteScopeRBACRoleBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/scopes/*/rbacrolebindings/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.DeleteScopeRBACRoleBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseDeleteScopeRBACRoleBinding._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGenerateConnectManifest: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/memberships/*}:generateConnectManifest", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GenerateConnectManifestRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseGenerateConnectManifest._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGenerateMembershipRBACRoleBindingYAML: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "rbacrolebindingId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/memberships/*}/rbacrolebindings:generateMembershipRBACRoleBindingYAML", + "body": "rbacrolebinding", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GenerateMembershipRBACRoleBindingYAMLRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseGenerateMembershipRBACRoleBindingYAML._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetFeature: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/features/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetFeatureRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetFleet: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/fleets/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetFleetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseGetFleet._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetMembership: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/memberships/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetMembershipRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseGetMembership._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetMembershipBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/memberships/*/bindings/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetMembershipBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseGetMembershipBinding._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetMembershipRBACRoleBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/memberships/*/rbacrolebindings/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetMembershipRBACRoleBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseGetMembershipRBACRoleBinding._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetScope: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/scopes/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetScopeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseGetScope._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetScopeNamespace: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/scopes/*/namespaces/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetScopeNamespaceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseGetScopeNamespace._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetScopeRBACRoleBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/scopes/*/rbacrolebindings/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetScopeRBACRoleBindingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseGetScopeRBACRoleBinding._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListBoundMemberships: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{scope_name=projects/*/locations/*/scopes/*}:listMemberships", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListBoundMembershipsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseListBoundMemberships._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListFeatures: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/features", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListFeaturesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListFleets: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/fleets", + }, + { + "method": "get", + "uri": "/v1/{parent=organizations/*/locations/*}/fleets", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListFleetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseListFleets._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListMembershipBindings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/memberships/*}/bindings", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListMembershipBindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseListMembershipBindings._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListMembershipRBACRoleBindings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/memberships/*}/rbacrolebindings", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListMembershipRBACRoleBindingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseListMembershipRBACRoleBindings._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListMemberships: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/memberships", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListMembershipsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseListMemberships._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListPermittedScopes: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/scopes:listPermitted", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListPermittedScopesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseGkeHubRestTransport._BaseListPermittedScopes._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListScopeNamespaces: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -150,28 +1707,18 @@ def _get_unset_required_fields(cls, message_dict): def _get_http_options(): http_options: List[Dict[str, str]] = [ { - "method": "post", - "uri": "/v1/{parent=projects/*/locations/*}/memberships", - "body": "resource", + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/scopes/*}/namespaces", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = service.CreateMembershipRequest.pb(request) + pb_request = service.ListScopeNamespacesRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request["body"], use_integers_for_enums=True - ) - return body - @staticmethod def _get_query_params_json(transcoded_request): query_params = json.loads( @@ -181,7 +1728,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseGkeHubRestTransport._BaseCreateMembership._get_unset_required_fields( + _BaseGkeHubRestTransport._BaseListScopeNamespaces._get_unset_required_fields( query_params ) ) @@ -189,23 +1736,33 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseDeleteFeature: + class _BaseListScopeRBACRoleBindings: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + @staticmethod def _get_http_options(): http_options: List[Dict[str, str]] = [ { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/features/*}", + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/scopes/*}/rbacrolebindings", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = service.DeleteFeatureRequest.pb(request) + pb_request = service.ListScopeRBACRoleBindingsRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -217,11 +1774,16 @@ def _get_query_params_json(transcoded_request): use_integers_for_enums=True, ) ) + query_params.update( + _BaseGkeHubRestTransport._BaseListScopeRBACRoleBindings._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseDeleteMembership: + class _BaseListScopes: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -239,15 +1801,15 @@ def _get_unset_required_fields(cls, message_dict): def _get_http_options(): http_options: List[Dict[str, str]] = [ { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/memberships/*}", + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/scopes", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = service.DeleteMembershipRequest.pb(request) + pb_request = service.ListScopesRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -260,7 +1822,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseGkeHubRestTransport._BaseDeleteMembership._get_unset_required_fields( + _BaseGkeHubRestTransport._BaseListScopes._get_unset_required_fields( query_params ) ) @@ -268,11 +1830,55 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseGenerateConnectManifest: + class _BaseUpdateFeature: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{name=projects/*/locations/*/features/*}", + "body": "resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.UpdateFeatureRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateFleet: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } @classmethod def _get_unset_required_fields(cls, message_dict): @@ -286,18 +1892,28 @@ def _get_unset_required_fields(cls, message_dict): def _get_http_options(): http_options: List[Dict[str, str]] = [ { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/memberships/*}:generateConnectManifest", + "method": "patch", + "uri": "/v1/{fleet.name=projects/*/locations/*/fleets/*}", + "body": "fleet", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = service.GenerateConnectManifestRequest.pb(request) + pb_request = service.UpdateFleetRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + @staticmethod def _get_query_params_json(transcoded_request): query_params = json.loads( @@ -307,7 +1923,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseGkeHubRestTransport._BaseGenerateConnectManifest._get_unset_required_fields( + _BaseGkeHubRestTransport._BaseUpdateFleet._get_unset_required_fields( query_params ) ) @@ -315,26 +1931,48 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseGetFeature: + class _BaseUpdateMembership: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + @staticmethod def _get_http_options(): http_options: List[Dict[str, str]] = [ { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/features/*}", + "method": "patch", + "uri": "/v1/{name=projects/*/locations/*/memberships/*}", + "body": "resource", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = service.GetFeatureRequest.pb(request) + pb_request = service.UpdateMembershipRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + @staticmethod def _get_query_params_json(transcoded_request): query_params = json.loads( @@ -343,15 +1981,22 @@ def _get_query_params_json(transcoded_request): use_integers_for_enums=True, ) ) + query_params.update( + _BaseGkeHubRestTransport._BaseUpdateMembership._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseGetMembership: + class _BaseUpdateMembershipBinding: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } @classmethod def _get_unset_required_fields(cls, message_dict): @@ -365,18 +2010,28 @@ def _get_unset_required_fields(cls, message_dict): def _get_http_options(): http_options: List[Dict[str, str]] = [ { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/memberships/*}", + "method": "patch", + "uri": "/v1/{membership_binding.name=projects/*/locations/*/memberships/*/bindings/*}", + "body": "membership_binding", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = service.GetMembershipRequest.pb(request) + pb_request = service.UpdateMembershipBindingRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + @staticmethod def _get_query_params_json(transcoded_request): query_params = json.loads( @@ -386,7 +2041,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseGkeHubRestTransport._BaseGetMembership._get_unset_required_fields( + _BaseGkeHubRestTransport._BaseUpdateMembershipBinding._get_unset_required_fields( query_params ) ) @@ -394,26 +2049,48 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseListFeatures: + class _BaseUpdateMembershipRBACRoleBinding: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + @staticmethod def _get_http_options(): http_options: List[Dict[str, str]] = [ { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*}/features", + "method": "patch", + "uri": "/v1/{rbacrolebinding.name=projects/*/locations/*/memberships/*/rbacrolebindings/*}", + "body": "rbacrolebinding", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = service.ListFeaturesRequest.pb(request) + pb_request = service.UpdateMembershipRBACRoleBindingRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + @staticmethod def _get_query_params_json(transcoded_request): query_params = json.loads( @@ -422,15 +2099,22 @@ def _get_query_params_json(transcoded_request): use_integers_for_enums=True, ) ) + query_params.update( + _BaseGkeHubRestTransport._BaseUpdateMembershipRBACRoleBinding._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseListMemberships: + class _BaseUpdateScope: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } @classmethod def _get_unset_required_fields(cls, message_dict): @@ -444,18 +2128,28 @@ def _get_unset_required_fields(cls, message_dict): def _get_http_options(): http_options: List[Dict[str, str]] = [ { - "method": "get", - "uri": "/v1/{parent=projects/*/locations/*}/memberships", + "method": "patch", + "uri": "/v1/{scope.name=projects/*/locations/*/scopes/*}", + "body": "scope", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = service.ListMembershipsRequest.pb(request) + pb_request = service.UpdateScopeRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + @staticmethod def _get_query_params_json(transcoded_request): query_params = json.loads( @@ -465,7 +2159,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseGkeHubRestTransport._BaseListMemberships._get_unset_required_fields( + _BaseGkeHubRestTransport._BaseUpdateScope._get_unset_required_fields( query_params ) ) @@ -473,24 +2167,36 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseUpdateFeature: + class _BaseUpdateScopeNamespace: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + @staticmethod def _get_http_options(): http_options: List[Dict[str, str]] = [ { "method": "patch", - "uri": "/v1/{name=projects/*/locations/*/features/*}", - "body": "resource", + "uri": "/v1/{scope_namespace.name=projects/*/locations/*/scopes/*/namespaces/*}", + "body": "scope_namespace", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = service.UpdateFeatureRequest.pb(request) + pb_request = service.UpdateScopeNamespaceRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -511,11 +2217,16 @@ def _get_query_params_json(transcoded_request): use_integers_for_enums=True, ) ) + query_params.update( + _BaseGkeHubRestTransport._BaseUpdateScopeNamespace._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseUpdateMembership: + class _BaseUpdateScopeRBACRoleBinding: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -536,15 +2247,15 @@ def _get_http_options(): http_options: List[Dict[str, str]] = [ { "method": "patch", - "uri": "/v1/{name=projects/*/locations/*/memberships/*}", - "body": "resource", + "uri": "/v1/{rbacrolebinding.name=projects/*/locations/*/scopes/*/rbacrolebindings/*}", + "body": "rbacrolebinding", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = service.UpdateMembershipRequest.pb(request) + pb_request = service.UpdateScopeRBACRoleBindingRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -566,7 +2277,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseGkeHubRestTransport._BaseUpdateMembership._get_unset_required_fields( + _BaseGkeHubRestTransport._BaseUpdateScopeRBACRoleBinding._get_unset_required_fields( query_params ) ) diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/types/__init__.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/types/__init__.py index cdc072f1f476..3dd6868fec17 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/types/__init__.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/types/__init__.py @@ -21,6 +21,24 @@ FeatureState, MembershipFeatureSpec, MembershipFeatureState, + ScopeFeatureSpec, + ScopeFeatureState, +) +from .fleet import ( + BinaryAuthorizationConfig, + CompliancePostureConfig, + DefaultClusterConfig, + Fleet, + FleetLifecycleState, + MembershipBinding, + MembershipBindingLifecycleState, + Namespace, + NamespaceLifecycleState, + RBACRoleBinding, + RBACRoleBindingLifecycleState, + Scope, + ScopeLifecycleState, + SecurityPostureConfig, ) from .membership import ( Authority, @@ -37,21 +55,63 @@ from .service import ( ConnectAgentResource, CreateFeatureRequest, + CreateFleetRequest, + CreateMembershipBindingRequest, + CreateMembershipRBACRoleBindingRequest, CreateMembershipRequest, + CreateScopeNamespaceRequest, + CreateScopeRBACRoleBindingRequest, + CreateScopeRequest, DeleteFeatureRequest, + DeleteFleetRequest, + DeleteMembershipBindingRequest, + DeleteMembershipRBACRoleBindingRequest, DeleteMembershipRequest, + DeleteScopeNamespaceRequest, + DeleteScopeRBACRoleBindingRequest, + DeleteScopeRequest, GenerateConnectManifestRequest, GenerateConnectManifestResponse, + GenerateMembershipRBACRoleBindingYAMLRequest, + GenerateMembershipRBACRoleBindingYAMLResponse, GetFeatureRequest, + GetFleetRequest, + GetMembershipBindingRequest, + GetMembershipRBACRoleBindingRequest, GetMembershipRequest, + GetScopeNamespaceRequest, + GetScopeRBACRoleBindingRequest, + GetScopeRequest, + ListBoundMembershipsRequest, + ListBoundMembershipsResponse, ListFeaturesRequest, ListFeaturesResponse, + ListFleetsRequest, + ListFleetsResponse, + ListMembershipBindingsRequest, + ListMembershipBindingsResponse, + ListMembershipRBACRoleBindingsRequest, + ListMembershipRBACRoleBindingsResponse, ListMembershipsRequest, ListMembershipsResponse, + ListPermittedScopesRequest, + ListPermittedScopesResponse, + ListScopeNamespacesRequest, + ListScopeNamespacesResponse, + ListScopeRBACRoleBindingsRequest, + ListScopeRBACRoleBindingsResponse, + ListScopesRequest, + ListScopesResponse, OperationMetadata, TypeMeta, UpdateFeatureRequest, + UpdateFleetRequest, + UpdateMembershipBindingRequest, + UpdateMembershipRBACRoleBindingRequest, UpdateMembershipRequest, + UpdateScopeNamespaceRequest, + UpdateScopeRBACRoleBindingRequest, + UpdateScopeRequest, ) __all__ = ( @@ -62,6 +122,22 @@ "FeatureState", "MembershipFeatureSpec", "MembershipFeatureState", + "ScopeFeatureSpec", + "ScopeFeatureState", + "BinaryAuthorizationConfig", + "CompliancePostureConfig", + "DefaultClusterConfig", + "Fleet", + "FleetLifecycleState", + "MembershipBinding", + "MembershipBindingLifecycleState", + "Namespace", + "NamespaceLifecycleState", + "RBACRoleBinding", + "RBACRoleBindingLifecycleState", + "Scope", + "ScopeLifecycleState", + "SecurityPostureConfig", "Authority", "GkeCluster", "KubernetesMetadata", @@ -74,19 +150,61 @@ "ResourceOptions", "ConnectAgentResource", "CreateFeatureRequest", + "CreateFleetRequest", + "CreateMembershipBindingRequest", + "CreateMembershipRBACRoleBindingRequest", "CreateMembershipRequest", + "CreateScopeNamespaceRequest", + "CreateScopeRBACRoleBindingRequest", + "CreateScopeRequest", "DeleteFeatureRequest", + "DeleteFleetRequest", + "DeleteMembershipBindingRequest", + "DeleteMembershipRBACRoleBindingRequest", "DeleteMembershipRequest", + "DeleteScopeNamespaceRequest", + "DeleteScopeRBACRoleBindingRequest", + "DeleteScopeRequest", "GenerateConnectManifestRequest", "GenerateConnectManifestResponse", + "GenerateMembershipRBACRoleBindingYAMLRequest", + "GenerateMembershipRBACRoleBindingYAMLResponse", "GetFeatureRequest", + "GetFleetRequest", + "GetMembershipBindingRequest", + "GetMembershipRBACRoleBindingRequest", "GetMembershipRequest", + "GetScopeNamespaceRequest", + "GetScopeRBACRoleBindingRequest", + "GetScopeRequest", + "ListBoundMembershipsRequest", + "ListBoundMembershipsResponse", "ListFeaturesRequest", "ListFeaturesResponse", + "ListFleetsRequest", + "ListFleetsResponse", + "ListMembershipBindingsRequest", + "ListMembershipBindingsResponse", + "ListMembershipRBACRoleBindingsRequest", + "ListMembershipRBACRoleBindingsResponse", "ListMembershipsRequest", "ListMembershipsResponse", + "ListPermittedScopesRequest", + "ListPermittedScopesResponse", + "ListScopeNamespacesRequest", + "ListScopeNamespacesResponse", + "ListScopeRBACRoleBindingsRequest", + "ListScopeRBACRoleBindingsResponse", + "ListScopesRequest", + "ListScopesResponse", "OperationMetadata", "TypeMeta", "UpdateFeatureRequest", + "UpdateFleetRequest", + "UpdateMembershipBindingRequest", + "UpdateMembershipRBACRoleBindingRequest", "UpdateMembershipRequest", + "UpdateScopeNamespaceRequest", + "UpdateScopeRBACRoleBindingRequest", + "UpdateScopeRequest", ) diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/types/feature.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/types/feature.py index 3afed11dec96..29fac5f51a6b 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/types/feature.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/types/feature.py @@ -22,6 +22,7 @@ from google.cloud.gkehub_v1 import configmanagement_v1 # type: ignore from google.cloud.gkehub_v1 import multiclusteringress_v1 # type: ignore +from google.cloud.gkehub_v1 import rbacrolebindingactuation_v1 # type: ignore __protobuf__ = proto.module( package="google.cloud.gkehub.v1", @@ -31,6 +32,8 @@ "FeatureState", "CommonFeatureSpec", "CommonFeatureState", + "ScopeFeatureSpec", + "ScopeFeatureState", "MembershipFeatureSpec", "MembershipFeatureState", }, @@ -38,7 +41,7 @@ class Feature(proto.Message): - r"""Feature represents the settings and status of any Hub + r"""Feature represents the settings and status of any Fleet Feature. Attributes: @@ -46,55 +49,50 @@ class Feature(proto.Message): Output only. The full, unique name of this Feature resource in the format ``projects/*/locations/*/features/*``. labels (MutableMapping[str, str]): - GCP labels for this Feature. + Labels for this Feature. resource_state (google.cloud.gkehub_v1.types.FeatureResourceState): Output only. State of the Feature resource itself. spec (google.cloud.gkehub_v1.types.CommonFeatureSpec): - Optional. Hub-wide Feature configuration. If - this Feature does not support any Hub-wide + Optional. Fleet-wide Feature configuration. + If this Feature does not support any Fleet-wide configuration, this field may be unused. membership_specs (MutableMapping[str, google.cloud.gkehub_v1.types.MembershipFeatureSpec]): - Optional. Membership-specific configuration - for this Feature. If this Feature does not - support any per-Membership configuration, this - field may be unused. - - The keys indicate which Membership the - configuration is for, in the form: - - projects/{p}/locations/{l}/memberships/{m} - - Where {p} is the project, {l} is a valid - location and {m} is a valid Membership in this - project at that location. {p} WILL match the - Feature's project. - - {p} will always be returned as the project - number, but the project ID is also accepted - during input. If the same Membership is - specified in the map twice (using the project ID - form, and the project number form), exactly ONE - of the entries will be saved, with no guarantees - as to which. For this reason, it is recommended - the same format be used for all entries when - mutating a Feature. + Optional. Membership-specific configuration for this + Feature. If this Feature does not support any per-Membership + configuration, this field may be unused. + + The keys indicate which Membership the configuration is for, + in the form: + + ``projects/{p}/locations/{l}/memberships/{m}`` + + Where {p} is the project, {l} is a valid location and {m} is + a valid Membership in this project at that location. {p} + WILL match the Feature's project. + + {p} will always be returned as the project number, but the + project ID is also accepted during input. If the same + Membership is specified in the map twice (using the project + ID form, and the project number form), exactly ONE of the + entries will be saved, with no guarantees as to which. For + this reason, it is recommended the same format be used for + all entries when mutating a Feature. state (google.cloud.gkehub_v1.types.CommonFeatureState): - Output only. The Hub-wide Feature state. + Output only. The Fleet-wide Feature state. membership_states (MutableMapping[str, google.cloud.gkehub_v1.types.MembershipFeatureState]): - Output only. Membership-specific Feature - status. If this Feature does report any - per-Membership status, this field may be unused. + Output only. Membership-specific Feature status. If this + Feature does report any per-Membership status, this field + may be unused. - The keys indicate which Membership the state is - for, in the form: + The keys indicate which Membership the state is for, in the + form: - projects/{p}/locations/{l}/memberships/{m} + ``projects/{p}/locations/{l}/memberships/{m}`` - Where {p} is the project number, {l} is a valid - location and {m} is a valid Membership in this - project at that location. {p} MUST match the - Feature's project number. + Where {p} is the project number, {l} is a valid location and + {m} is a valid Membership in this project at that location. + {p} MUST match the Feature's project number. create_time (google.protobuf.timestamp_pb2.Timestamp): Output only. When the Feature resource was created. @@ -104,6 +102,39 @@ class Feature(proto.Message): delete_time (google.protobuf.timestamp_pb2.Timestamp): Output only. When the Feature resource was deleted. + scope_specs (MutableMapping[str, google.cloud.gkehub_v1.types.ScopeFeatureSpec]): + Optional. Scope-specific configuration for this Feature. If + this Feature does not support any per-Scope configuration, + this field may be unused. + + The keys indicate which Scope the configuration is for, in + the form: + + ``projects/{p}/locations/global/scopes/{s}`` + + Where {p} is the project, {s} is a valid Scope in this + project. {p} WILL match the Feature's project. + + {p} will always be returned as the project number, but the + project ID is also accepted during input. If the same Scope + is specified in the map twice (using the project ID form, + and the project number form), exactly ONE of the entries + will be saved, with no guarantees as to which. For this + reason, it is recommended the same format be used for all + entries when mutating a Feature. + scope_states (MutableMapping[str, google.cloud.gkehub_v1.types.ScopeFeatureState]): + Output only. Scope-specific Feature status. If this Feature + does report any per-Scope status, this field may be unused. + + The keys indicate which Scope the state is for, in the form: + + ``projects/{p}/locations/global/scopes/{s}`` + + Where {p} is the project, {s} is a valid Scope in this + project. {p} WILL match the Feature's project. + unreachable (MutableSequence[str]): + Output only. List of locations that could not + be reached while fetching this feature. """ name: str = proto.Field( @@ -157,12 +188,28 @@ class Feature(proto.Message): number=10, message=timestamp_pb2.Timestamp, ) + scope_specs: MutableMapping[str, "ScopeFeatureSpec"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=12, + message="ScopeFeatureSpec", + ) + scope_states: MutableMapping[str, "ScopeFeatureState"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=13, + message="ScopeFeatureState", + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=15, + ) class FeatureResourceState(proto.Message): r"""FeatureResourceState describes the state of a Feature *resource* in the GkeHub API. See ``FeatureState`` for the "running state" of the - Feature in the Hub and across Memberships. + Feature in the Fleet and across Memberships. Attributes: state (google.cloud.gkehub_v1.types.FeatureResourceState.State): @@ -180,12 +227,12 @@ class State(proto.Enum): The Feature is being enabled, and the Feature resource is being created. Once complete, the corresponding Feature will be enabled in this - Hub. + Fleet. ACTIVE (2): - The Feature is enabled in this Hub, and the + The Feature is enabled in this Fleet, and the Feature resource is fully available. DISABLING (3): - The Feature is being disabled in this Hub, + The Feature is being disabled in this Fleet, and the Feature resource is being deleted. UPDATING (4): The Feature resource is being updated. @@ -288,13 +335,47 @@ class CommonFeatureSpec(proto.Message): class CommonFeatureState(proto.Message): - r"""CommonFeatureState contains Hub-wide Feature status + r"""CommonFeatureState contains Fleet-wide Feature status + information. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + rbacrolebindingactuation (google.cloud.gkehub_v1.rbacrolebindingactuation_v1.FeatureState): + RBAC Role Binding Actuation feature state + + This field is a member of `oneof`_ ``feature_state``. + state (google.cloud.gkehub_v1.types.FeatureState): + Output only. The "running state" of the + Feature in this Fleet. + """ + + rbacrolebindingactuation: rbacrolebindingactuation_v1.FeatureState = proto.Field( + proto.MESSAGE, + number=120, + oneof="feature_state", + message=rbacrolebindingactuation_v1.FeatureState, + ) + state: "FeatureState" = proto.Field( + proto.MESSAGE, + number=1, + message="FeatureState", + ) + + +class ScopeFeatureSpec(proto.Message): + r"""ScopeFeatureSpec contains feature specs for a fleet scope.""" + + +class ScopeFeatureState(proto.Message): + r"""ScopeFeatureState contains Scope-wide Feature status information. Attributes: state (google.cloud.gkehub_v1.types.FeatureState): Output only. The "running state" of the - Feature in this Hub. + Feature in this Scope. """ state: "FeatureState" = proto.Field( diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/types/fleet.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/types/fleet.py new file mode 100644 index 000000000000..aad55d2628f7 --- /dev/null +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/types/fleet.py @@ -0,0 +1,908 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.gkehub.v1", + manifest={ + "Fleet", + "DefaultClusterConfig", + "SecurityPostureConfig", + "BinaryAuthorizationConfig", + "CompliancePostureConfig", + "FleetLifecycleState", + "Namespace", + "NamespaceLifecycleState", + "RBACRoleBinding", + "RBACRoleBindingLifecycleState", + "Scope", + "ScopeLifecycleState", + "MembershipBinding", + "MembershipBindingLifecycleState", + }, +) + + +class Fleet(proto.Message): + r"""Fleet contains the Fleet-wide metadata and configuration. + + Attributes: + name (str): + Output only. The full, unique resource name of this fleet in + the format of + ``projects/{project}/locations/{location}/fleets/{fleet}``. + + Each Google Cloud project can have at most one fleet + resource, named "default". + display_name (str): + Optional. A user-assigned display name of the Fleet. When + present, it must be between 4 to 30 characters. Allowed + characters are: lowercase and uppercase letters, numbers, + hyphen, single-quote, double-quote, space, and exclamation + point. + + Example: ``Production Fleet`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the Fleet was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the Fleet was last updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the Fleet was deleted. + uid (str): + Output only. Google-generated UUID for this + resource. This is unique across all Fleet + resources. If a Fleet resource is deleted and + another resource with the same name is created, + it gets a different uid. + state (google.cloud.gkehub_v1.types.FleetLifecycleState): + Output only. State of the namespace resource. + default_cluster_config (google.cloud.gkehub_v1.types.DefaultClusterConfig): + Optional. The default cluster configurations + to apply across the fleet. + labels (MutableMapping[str, str]): + Optional. Labels for this Fleet. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + uid: str = proto.Field( + proto.STRING, + number=6, + ) + state: "FleetLifecycleState" = proto.Field( + proto.MESSAGE, + number=9, + message="FleetLifecycleState", + ) + default_cluster_config: "DefaultClusterConfig" = proto.Field( + proto.MESSAGE, + number=10, + message="DefaultClusterConfig", + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=11, + ) + + +class DefaultClusterConfig(proto.Message): + r"""DefaultClusterConfig describes the default cluster + configurations to be applied to all clusters born-in-fleet. + + Attributes: + security_posture_config (google.cloud.gkehub_v1.types.SecurityPostureConfig): + Enable/Disable Security Posture features for + the cluster. + binary_authorization_config (google.cloud.gkehub_v1.types.BinaryAuthorizationConfig): + Optional. Enable/Disable binary authorization + features for the cluster. + compliance_posture_config (google.cloud.gkehub_v1.types.CompliancePostureConfig): + Optional. Enable/Disable Compliance Posture + features for the cluster. Note that on + UpdateFleet, only full replacement of this field + is allowed. Users are not allowed for partial + updates through field mask. + """ + + security_posture_config: "SecurityPostureConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="SecurityPostureConfig", + ) + binary_authorization_config: "BinaryAuthorizationConfig" = proto.Field( + proto.MESSAGE, + number=2, + message="BinaryAuthorizationConfig", + ) + compliance_posture_config: "CompliancePostureConfig" = proto.Field( + proto.MESSAGE, + number=3, + message="CompliancePostureConfig", + ) + + +class SecurityPostureConfig(proto.Message): + r"""SecurityPostureConfig defines the flags needed to + enable/disable features for the Security Posture API. + + Attributes: + mode (google.cloud.gkehub_v1.types.SecurityPostureConfig.Mode): + Sets which mode to use for Security Posture + features. + vulnerability_mode (google.cloud.gkehub_v1.types.SecurityPostureConfig.VulnerabilityMode): + Sets which mode to use for vulnerability + scanning. + """ + + class Mode(proto.Enum): + r"""Mode defines enablement mode for GKE Security posture + features. + + Values: + MODE_UNSPECIFIED (0): + Default value not specified. + DISABLED (1): + Disables Security Posture features on the + cluster. + BASIC (2): + Applies Security Posture features on the + cluster. + ENTERPRISE (3): + Applies the Security Posture off cluster + Enterprise level features. + """ + MODE_UNSPECIFIED = 0 + DISABLED = 1 + BASIC = 2 + ENTERPRISE = 3 + + class VulnerabilityMode(proto.Enum): + r"""VulnerabilityMode defines enablement mode for vulnerability + scanning. + + Values: + VULNERABILITY_MODE_UNSPECIFIED (0): + Default value not specified. + VULNERABILITY_DISABLED (1): + Disables vulnerability scanning on the + cluster. + VULNERABILITY_BASIC (2): + Applies basic vulnerability scanning on the + cluster. + VULNERABILITY_ENTERPRISE (3): + Applies the Security Posture's vulnerability + on cluster Enterprise level features. + """ + VULNERABILITY_MODE_UNSPECIFIED = 0 + VULNERABILITY_DISABLED = 1 + VULNERABILITY_BASIC = 2 + VULNERABILITY_ENTERPRISE = 3 + + mode: Mode = proto.Field( + proto.ENUM, + number=1, + enum=Mode, + ) + vulnerability_mode: VulnerabilityMode = proto.Field( + proto.ENUM, + number=2, + enum=VulnerabilityMode, + ) + + +class BinaryAuthorizationConfig(proto.Message): + r"""BinaryAuthorizationConfig defines the fleet level + configuration of binary authorization feature. + + Attributes: + evaluation_mode (google.cloud.gkehub_v1.types.BinaryAuthorizationConfig.EvaluationMode): + Optional. Mode of operation for binauthz + policy evaluation. + policy_bindings (MutableSequence[google.cloud.gkehub_v1.types.BinaryAuthorizationConfig.PolicyBinding]): + Optional. Binauthz policies that apply to + this cluster. + """ + + class EvaluationMode(proto.Enum): + r"""Binary Authorization mode of operation. + + Values: + EVALUATION_MODE_UNSPECIFIED (0): + Default value + DISABLED (1): + Disable BinaryAuthorization + POLICY_BINDINGS (2): + Use Binary Authorization with the policies specified in + policy_bindings. + """ + EVALUATION_MODE_UNSPECIFIED = 0 + DISABLED = 1 + POLICY_BINDINGS = 2 + + class PolicyBinding(proto.Message): + r"""Binauthz policy that applies to this cluster. + + Attributes: + name (str): + The relative resource name of the binauthz platform policy + to audit. GKE platform policies have the following format: + ``projects/{project_number}/platforms/gke/policies/{policy_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + evaluation_mode: EvaluationMode = proto.Field( + proto.ENUM, + number=1, + enum=EvaluationMode, + ) + policy_bindings: MutableSequence[PolicyBinding] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=PolicyBinding, + ) + + +class CompliancePostureConfig(proto.Message): + r"""CompliancePostureConfig defines the settings needed to + enable/disable features for the Compliance Posture. + + Attributes: + mode (google.cloud.gkehub_v1.types.CompliancePostureConfig.Mode): + Defines the enablement mode for Compliance + Posture. + compliance_standards (MutableSequence[google.cloud.gkehub_v1.types.CompliancePostureConfig.ComplianceStandard]): + List of enabled compliance standards. + """ + + class Mode(proto.Enum): + r""" + + Values: + MODE_UNSPECIFIED (0): + Default value not specified. + DISABLED (1): + Disables Compliance Posture features on the + cluster. + ENABLED (2): + Enables Compliance Posture features on the + cluster. + """ + MODE_UNSPECIFIED = 0 + DISABLED = 1 + ENABLED = 2 + + class ComplianceStandard(proto.Message): + r""" + + Attributes: + standard (str): + Name of the compliance standard. + """ + + standard: str = proto.Field( + proto.STRING, + number=1, + ) + + mode: Mode = proto.Field( + proto.ENUM, + number=1, + enum=Mode, + ) + compliance_standards: MutableSequence[ComplianceStandard] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=ComplianceStandard, + ) + + +class FleetLifecycleState(proto.Message): + r"""FleetLifecycleState describes the state of a Fleet resource. + + Attributes: + code (google.cloud.gkehub_v1.types.FleetLifecycleState.Code): + Output only. The current state of the Fleet + resource. + """ + + class Code(proto.Enum): + r"""Code describes the state of a Fleet resource. + + Values: + CODE_UNSPECIFIED (0): + The code is not set. + CREATING (1): + The fleet is being created. + READY (2): + The fleet active. + DELETING (3): + The fleet is being deleted. + UPDATING (4): + The fleet is being updated. + """ + CODE_UNSPECIFIED = 0 + CREATING = 1 + READY = 2 + DELETING = 3 + UPDATING = 4 + + code: Code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + + +class Namespace(proto.Message): + r"""Namespace represents a namespace across the Fleet + + Attributes: + name (str): + The resource name for the namespace + ``projects/{project}/locations/{location}/namespaces/{namespace}`` + uid (str): + Output only. Google-generated UUID for this + resource. This is unique across all namespace + resources. If a namespace resource is deleted + and another resource with the same name is + created, it gets a different uid. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the namespace was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the namespace was last + updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the namespace was deleted. + state (google.cloud.gkehub_v1.types.NamespaceLifecycleState): + Output only. State of the namespace resource. + scope (str): + Required. Scope associated with the namespace + namespace_labels (MutableMapping[str, str]): + Optional. Namespace-level cluster namespace labels. These + labels are applied to the related namespace of the member + clusters bound to the parent Scope. Scope-level labels + (``namespace_labels`` in the Fleet Scope resource) take + precedence over Namespace-level labels if they share a key. + Keys and values must be Kubernetes-conformant. + labels (MutableMapping[str, str]): + Optional. Labels for this Namespace. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + state: "NamespaceLifecycleState" = proto.Field( + proto.MESSAGE, + number=6, + message="NamespaceLifecycleState", + ) + scope: str = proto.Field( + proto.STRING, + number=8, + ) + namespace_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=9, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=10, + ) + + +class NamespaceLifecycleState(proto.Message): + r"""NamespaceLifecycleState describes the state of a Namespace + resource. + + Attributes: + code (google.cloud.gkehub_v1.types.NamespaceLifecycleState.Code): + Output only. The current state of the + Namespace resource. + """ + + class Code(proto.Enum): + r"""Code describes the state of a Namespace resource. + + Values: + CODE_UNSPECIFIED (0): + The code is not set. + CREATING (1): + The namespace is being created. + READY (2): + The namespace active. + DELETING (3): + The namespace is being deleted. + UPDATING (4): + The namespace is being updated. + """ + CODE_UNSPECIFIED = 0 + CREATING = 1 + READY = 2 + DELETING = 3 + UPDATING = 4 + + code: Code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + + +class RBACRoleBinding(proto.Message): + r"""RBACRoleBinding represents a rbacrolebinding across the Fleet + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + user (str): + user is the name of the user as seen by the + kubernetes cluster, example "alice" or + "alice@domain.tld". + + This field is a member of `oneof`_ ``principal``. + group (str): + group is the group, as seen by the kubernetes + cluster. + + This field is a member of `oneof`_ ``principal``. + name (str): + The resource name for the rbacrolebinding + ``projects/{project}/locations/{location}/scopes/{scope}/rbacrolebindings/{rbacrolebinding}`` + or + ``projects/{project}/locations/{location}/memberships/{membership}/rbacrolebindings/{rbacrolebinding}`` + uid (str): + Output only. Google-generated UUID for this + resource. This is unique across all + rbacrolebinding resources. If a rbacrolebinding + resource is deleted and another resource with + the same name is created, it gets a different + uid. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the rbacrolebinding was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the rbacrolebinding was + last updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the rbacrolebinding was + deleted. + state (google.cloud.gkehub_v1.types.RBACRoleBindingLifecycleState): + Output only. State of the rbacrolebinding + resource. + role (google.cloud.gkehub_v1.types.RBACRoleBinding.Role): + Required. Role to bind to the principal + labels (MutableMapping[str, str]): + Optional. Labels for this RBACRolebinding. + """ + + class Role(proto.Message): + r"""Role is the type for Kubernetes roles + + Attributes: + predefined_role (google.cloud.gkehub_v1.types.RBACRoleBinding.Role.PredefinedRoles): + predefined_role is the Kubernetes default role to use + custom_role (str): + Optional. custom_role is the name of a custom + KubernetesClusterRole to use. + """ + + class PredefinedRoles(proto.Enum): + r"""PredefinedRoles is an ENUM representation of the default + Kubernetes Roles + + Values: + UNKNOWN (0): + UNKNOWN + ADMIN (1): + ADMIN has EDIT and RBAC permissions + EDIT (2): + EDIT can edit all resources except RBAC + VIEW (3): + VIEW can only read resources + ANTHOS_SUPPORT (4): + ANTHOS_SUPPORT gives Google Support read-only access to a + number of cluster resources. + """ + UNKNOWN = 0 + ADMIN = 1 + EDIT = 2 + VIEW = 3 + ANTHOS_SUPPORT = 4 + + predefined_role: "RBACRoleBinding.Role.PredefinedRoles" = proto.Field( + proto.ENUM, + number=1, + enum="RBACRoleBinding.Role.PredefinedRoles", + ) + custom_role: str = proto.Field( + proto.STRING, + number=2, + ) + + user: str = proto.Field( + proto.STRING, + number=7, + oneof="principal", + ) + group: str = proto.Field( + proto.STRING, + number=8, + oneof="principal", + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + state: "RBACRoleBindingLifecycleState" = proto.Field( + proto.MESSAGE, + number=6, + message="RBACRoleBindingLifecycleState", + ) + role: Role = proto.Field( + proto.MESSAGE, + number=9, + message=Role, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=10, + ) + + +class RBACRoleBindingLifecycleState(proto.Message): + r"""RBACRoleBindingLifecycleState describes the state of a + RbacRoleBinding resource. + + Attributes: + code (google.cloud.gkehub_v1.types.RBACRoleBindingLifecycleState.Code): + Output only. The current state of the + rbacrolebinding resource. + """ + + class Code(proto.Enum): + r"""Code describes the state of a rbacrolebinding resource. + + Values: + CODE_UNSPECIFIED (0): + The code is not set. + CREATING (1): + The rbacrolebinding is being created. + READY (2): + The rbacrolebinding active. + DELETING (3): + The rbacrolebinding is being deleted. + UPDATING (4): + The rbacrolebinding is being updated. + """ + CODE_UNSPECIFIED = 0 + CREATING = 1 + READY = 2 + DELETING = 3 + UPDATING = 4 + + code: Code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + + +class Scope(proto.Message): + r"""Scope represents a Scope in a Fleet. + + Attributes: + name (str): + The resource name for the scope + ``projects/{project}/locations/{location}/scopes/{scope}`` + uid (str): + Output only. Google-generated UUID for this + resource. This is unique across all scope + resources. If a scope resource is deleted and + another resource with the same name is created, + it gets a different uid. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the scope was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the scope was last updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the scope was deleted. + state (google.cloud.gkehub_v1.types.ScopeLifecycleState): + Output only. State of the scope resource. + namespace_labels (MutableMapping[str, str]): + Optional. Scope-level cluster namespace labels. For the + member clusters bound to the Scope, these labels are applied + to each namespace under the Scope. Scope-level labels take + precedence over Namespace-level labels (``namespace_labels`` + in the Fleet Namespace resource) if they share a key. Keys + and values must be Kubernetes-conformant. + labels (MutableMapping[str, str]): + Optional. Labels for this Scope. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + state: "ScopeLifecycleState" = proto.Field( + proto.MESSAGE, + number=6, + message="ScopeLifecycleState", + ) + namespace_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=9, + ) + + +class ScopeLifecycleState(proto.Message): + r"""ScopeLifecycleState describes the state of a Scope resource. + + Attributes: + code (google.cloud.gkehub_v1.types.ScopeLifecycleState.Code): + Output only. The current state of the scope + resource. + """ + + class Code(proto.Enum): + r"""Code describes the state of a Scope resource. + + Values: + CODE_UNSPECIFIED (0): + The code is not set. + CREATING (1): + The scope is being created. + READY (2): + The scope active. + DELETING (3): + The scope is being deleted. + UPDATING (4): + The scope is being updated. + """ + CODE_UNSPECIFIED = 0 + CREATING = 1 + READY = 2 + DELETING = 3 + UPDATING = 4 + + code: Code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + + +class MembershipBinding(proto.Message): + r"""MembershipBinding is a subresource of a Membership, + representing what Fleet Scopes (or other, future Fleet + resources) a Membership is bound to. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + scope (str): + A Scope resource name in the format + ``projects/*/locations/*/scopes/*``. + + This field is a member of `oneof`_ ``target``. + name (str): + The resource name for the membershipbinding itself + ``projects/{project}/locations/{location}/memberships/{membership}/bindings/{membershipbinding}`` + uid (str): + Output only. Google-generated UUID for this + resource. This is unique across all + membershipbinding resources. If a + membershipbinding resource is deleted and + another resource with the same name is created, + it gets a different uid. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the membership binding was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the membership binding was + last updated. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the membership binding was + deleted. + state (google.cloud.gkehub_v1.types.MembershipBindingLifecycleState): + Output only. State of the membership binding + resource. + labels (MutableMapping[str, str]): + Optional. Labels for this MembershipBinding. + """ + + scope: str = proto.Field( + proto.STRING, + number=3, + oneof="target", + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + state: "MembershipBindingLifecycleState" = proto.Field( + proto.MESSAGE, + number=8, + message="MembershipBindingLifecycleState", + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=9, + ) + + +class MembershipBindingLifecycleState(proto.Message): + r"""MembershipBindingLifecycleState describes the state of a + Binding resource. + + Attributes: + code (google.cloud.gkehub_v1.types.MembershipBindingLifecycleState.Code): + Output only. The current state of the + MembershipBinding resource. + """ + + class Code(proto.Enum): + r"""Code describes the state of a MembershipBinding resource. + + Values: + CODE_UNSPECIFIED (0): + The code is not set. + CREATING (1): + The membershipbinding is being created. + READY (2): + The membershipbinding active. + DELETING (3): + The membershipbinding is being deleted. + UPDATING (4): + The membershipbinding is being updated. + """ + CODE_UNSPECIFIED = 0 + CREATING = 1 + READY = 2 + DELETING = 3 + UPDATING = 4 + + code: Code = proto.Field( + proto.ENUM, + number=1, + enum=Code, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/types/service.py b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/types/service.py index 600c24e22df4..86b57eb1242a 100644 --- a/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/types/service.py +++ b/packages/google-cloud-gke-hub/google/cloud/gkehub_v1/types/service.py @@ -21,14 +21,52 @@ import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import proto # type: ignore -from google.cloud.gkehub_v1.types import feature, membership +from google.cloud.gkehub_v1.types import feature +from google.cloud.gkehub_v1.types import fleet as gcg_fleet +from google.cloud.gkehub_v1.types import membership __protobuf__ = proto.module( package="google.cloud.gkehub.v1", manifest={ + "GetScopeNamespaceRequest", + "CreateScopeNamespaceRequest", + "UpdateScopeNamespaceRequest", + "DeleteScopeNamespaceRequest", + "ListScopeNamespacesRequest", + "ListScopeNamespacesResponse", + "GetScopeRBACRoleBindingRequest", + "CreateScopeRBACRoleBindingRequest", + "UpdateScopeRBACRoleBindingRequest", + "DeleteScopeRBACRoleBindingRequest", + "ListScopeRBACRoleBindingsRequest", + "ListScopeRBACRoleBindingsResponse", + "GetScopeRequest", + "CreateScopeRequest", + "UpdateScopeRequest", + "DeleteScopeRequest", + "ListScopesRequest", + "ListScopesResponse", + "ListPermittedScopesRequest", + "ListPermittedScopesResponse", + "GetMembershipBindingRequest", + "CreateMembershipBindingRequest", + "UpdateMembershipBindingRequest", + "DeleteMembershipBindingRequest", + "ListMembershipBindingsRequest", + "ListMembershipBindingsResponse", "ListMembershipsRequest", + "GetMembershipRBACRoleBindingRequest", + "CreateMembershipRBACRoleBindingRequest", + "UpdateMembershipRBACRoleBindingRequest", + "DeleteMembershipRBACRoleBindingRequest", + "ListMembershipRBACRoleBindingsRequest", + "ListMembershipRBACRoleBindingsResponse", + "GenerateMembershipRBACRoleBindingYAMLRequest", + "GenerateMembershipRBACRoleBindingYAMLResponse", "ListMembershipsResponse", "GetMembershipRequest", + "ListBoundMembershipsRequest", + "ListBoundMembershipsResponse", "CreateMembershipRequest", "DeleteMembershipRequest", "UpdateMembershipRequest", @@ -42,11 +80,686 @@ "CreateFeatureRequest", "DeleteFeatureRequest", "UpdateFeatureRequest", + "CreateFleetRequest", + "GetFleetRequest", + "UpdateFleetRequest", + "DeleteFleetRequest", + "ListFleetsRequest", + "ListFleetsResponse", "OperationMetadata", }, ) +class GetScopeNamespaceRequest(proto.Message): + r"""Request message for the ``GkeHub.GetNamespace`` method. + + Attributes: + name (str): + Required. The Namespace resource name in the format + ``projects/*/locations/*/scopes/*/namespaces/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateScopeNamespaceRequest(proto.Message): + r"""Request to create a fleet namespace. + + Attributes: + parent (str): + Required. The parent (project and location) where the + Namespace will be created. Specified in the format + ``projects/*/locations/*/scopes/*``. + scope_namespace_id (str): + Required. Client chosen ID for the Namespace. + ``namespace_id`` must be a valid RFC 1123 compliant DNS + label: + + 1. At most 63 characters in length + 2. It must consist of lower case alphanumeric characters or + ``-`` + 3. It must start and end with an alphanumeric character + + Which can be expressed as the regex: + ``[a-z0-9]([-a-z0-9]*[a-z0-9])?``, with a maximum length of + 63 characters. + scope_namespace (google.cloud.gkehub_v1.types.Namespace): + Required. The fleet namespace to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + scope_namespace_id: str = proto.Field( + proto.STRING, + number=2, + ) + scope_namespace: gcg_fleet.Namespace = proto.Field( + proto.MESSAGE, + number=3, + message=gcg_fleet.Namespace, + ) + + +class UpdateScopeNamespaceRequest(proto.Message): + r"""Request to update a fleet namespace. + + Attributes: + scope_namespace (google.cloud.gkehub_v1.types.Namespace): + Required. A namespace with fields updated. The 'name' field + in this namespace is used to identify the resource to + update. Given 'updated' prefix to follow + go/proto-best-practices-checkers#keyword_conflict + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The fields to be updated. + """ + + scope_namespace: gcg_fleet.Namespace = proto.Field( + proto.MESSAGE, + number=1, + message=gcg_fleet.Namespace, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteScopeNamespaceRequest(proto.Message): + r"""Request to delete a fleet namespace. + + Attributes: + name (str): + Required. The Namespace resource name in the format + ``projects/*/locations/*/scopes/*/namespaces/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListScopeNamespacesRequest(proto.Message): + r"""Request to list fleet namespaces. + + Attributes: + parent (str): + Required. The parent (project and location) where the + Features will be listed. Specified in the format + ``projects/*/locations/*/scopes/*``. + page_size (int): + Optional. When requesting a 'page' of resources, + ``page_size`` specifies number of resources to return. If + unspecified or set to 0, all resources will be returned. + page_token (str): + Optional. Token returned by previous call to + ``ListFeatures`` which specifies the position in the list + from where to continue listing the resources. + """ + + 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 ListScopeNamespacesResponse(proto.Message): + r"""List of fleet namespaces. + + Attributes: + scope_namespaces (MutableSequence[google.cloud.gkehub_v1.types.Namespace]): + The list of fleet namespaces + next_page_token (str): + A token to request the next page of resources from the + ``ListNamespaces`` method. The value of an empty string + means that there are no more resources to return. + """ + + @property + def raw_page(self): + return self + + scope_namespaces: MutableSequence[gcg_fleet.Namespace] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcg_fleet.Namespace, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetScopeRBACRoleBindingRequest(proto.Message): + r"""Request message for the ``GkeHub.GetScopeRBACRoleBinding`` method. + + Attributes: + name (str): + Required. The RBACRoleBinding resource name in the format + ``projects/*/locations/*/scopes/*/rbacrolebindings/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateScopeRBACRoleBindingRequest(proto.Message): + r"""Request to create a rbacrolebindings. + + Attributes: + parent (str): + Required. The parent (project and location) where the + RBACRoleBinding will be created. Specified in the format + ``projects/*/locations/*/scopes/*``. + rbacrolebinding_id (str): + Required. Client chosen ID for the RBACRoleBinding. + ``rbacrolebinding_id`` must be a valid RFC 1123 compliant + DNS label: + + 1. At most 63 characters in length + 2. It must consist of lower case alphanumeric characters or + ``-`` + 3. It must start and end with an alphanumeric character + + Which can be expressed as the regex: + ``[a-z0-9]([-a-z0-9]*[a-z0-9])?``, with a maximum length of + 63 characters. + rbacrolebinding (google.cloud.gkehub_v1.types.RBACRoleBinding): + Required. The rbacrolebindings to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + rbacrolebinding_id: str = proto.Field( + proto.STRING, + number=2, + ) + rbacrolebinding: gcg_fleet.RBACRoleBinding = proto.Field( + proto.MESSAGE, + number=3, + message=gcg_fleet.RBACRoleBinding, + ) + + +class UpdateScopeRBACRoleBindingRequest(proto.Message): + r"""Request to update a scope rbacrolebinding. + + Attributes: + rbacrolebinding (google.cloud.gkehub_v1.types.RBACRoleBinding): + Required. A rbacrolebinding with fields + updated. The 'name' field in this + rbacrolebinding is used to identify the resource + to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The fields to be updated. + """ + + rbacrolebinding: gcg_fleet.RBACRoleBinding = proto.Field( + proto.MESSAGE, + number=1, + message=gcg_fleet.RBACRoleBinding, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteScopeRBACRoleBindingRequest(proto.Message): + r"""Request to delete a Scope RBACRoleBinding. + + Attributes: + name (str): + Required. The RBACRoleBinding resource name in the format + ``projects/*/locations/*/scopes/*/rbacrolebindings/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListScopeRBACRoleBindingsRequest(proto.Message): + r"""Request to list Scope RBACRoleBindings. + + Attributes: + parent (str): + Required. The parent (project and location) where the + Features will be listed. Specified in the format + ``projects/*/locations/*/scopes/*``. + page_size (int): + Optional. When requesting a 'page' of resources, + ``page_size`` specifies number of resources to return. If + unspecified or set to 0, all resources will be returned. + page_token (str): + Optional. Token returned by previous call to + ``ListScopeRBACRoleBindings`` which specifies the position + in the list from where to continue listing the resources. + """ + + 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 ListScopeRBACRoleBindingsResponse(proto.Message): + r"""List of Scope RBACRoleBindings. + + Attributes: + rbacrolebindings (MutableSequence[google.cloud.gkehub_v1.types.RBACRoleBinding]): + The list of Scope RBACRoleBindings. + next_page_token (str): + A token to request the next page of resources from the + ``ListScopeRBACRoleBindings`` method. The value of an empty + string means that there are no more resources to return. + """ + + @property + def raw_page(self): + return self + + rbacrolebindings: MutableSequence[gcg_fleet.RBACRoleBinding] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcg_fleet.RBACRoleBinding, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetScopeRequest(proto.Message): + r"""Request message for the ``GkeHub.GetScope`` method. + + Attributes: + name (str): + Required. The Scope resource name in the format + ``projects/*/locations/*/scopes/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateScopeRequest(proto.Message): + r"""Request to create a Scope. + + Attributes: + parent (str): + Required. The parent (project and location) where the Scope + will be created. Specified in the format + ``projects/*/locations/*``. + scope_id (str): + Required. Client chosen ID for the Scope. ``scope_id`` must + be a ???? + scope (google.cloud.gkehub_v1.types.Scope): + Required. The Scope to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + scope_id: str = proto.Field( + proto.STRING, + number=2, + ) + scope: gcg_fleet.Scope = proto.Field( + proto.MESSAGE, + number=3, + message=gcg_fleet.Scope, + ) + + +class UpdateScopeRequest(proto.Message): + r"""Request to update a Scope. + + Attributes: + scope (google.cloud.gkehub_v1.types.Scope): + Required. A Scope with fields updated. The + 'name' field in this namespace is used to + identify the resource to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The fields to be updated. + """ + + scope: gcg_fleet.Scope = proto.Field( + proto.MESSAGE, + number=1, + message=gcg_fleet.Scope, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteScopeRequest(proto.Message): + r"""Request to delete a Scope. + + Attributes: + name (str): + Required. The Scope resource name in the format + ``projects/*/locations/*/scopes/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListScopesRequest(proto.Message): + r"""Request to list Scopes. + + Attributes: + parent (str): + Required. The parent (project and location) where the Scope + will be listed. Specified in the format + ``projects/*/locations/*``. + page_size (int): + Optional. When requesting a 'page' of resources, + ``page_size`` specifies number of resources to return. If + unspecified or set to 0, all resources will be returned. + page_token (str): + Optional. Token returned by previous call to ``ListScopes`` + which specifies the position in the list from where to + continue listing the resources. + """ + + 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 ListScopesResponse(proto.Message): + r"""List of Scopes. + + Attributes: + scopes (MutableSequence[google.cloud.gkehub_v1.types.Scope]): + The list of Scopes + next_page_token (str): + A token to request the next page of resources from the + ``ListScopes`` method. The value of an empty string means + that there are no more resources to return. + """ + + @property + def raw_page(self): + return self + + scopes: MutableSequence[gcg_fleet.Scope] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcg_fleet.Scope, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListPermittedScopesRequest(proto.Message): + r"""Request to list permitted Scopes. + + Attributes: + parent (str): + Required. The parent (project and location) where the Scope + will be listed. Specified in the format + ``projects/*/locations/*``. + page_size (int): + Optional. When requesting a 'page' of resources, + ``page_size`` specifies number of resources to return. If + unspecified or set to 0, all resources will be returned. + page_token (str): + Optional. Token returned by previous call to + ``ListPermittedScopes`` which specifies the position in the + list from where to continue listing the resources. + """ + + 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 ListPermittedScopesResponse(proto.Message): + r"""List of permitted Scopes. + + Attributes: + scopes (MutableSequence[google.cloud.gkehub_v1.types.Scope]): + The list of permitted Scopes + next_page_token (str): + A token to request the next page of resources from the + ``ListPermittedScopes`` method. The value of an empty string + means that there are no more resources to return. + """ + + @property + def raw_page(self): + return self + + scopes: MutableSequence[gcg_fleet.Scope] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcg_fleet.Scope, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetMembershipBindingRequest(proto.Message): + r"""Request message for the ``GkeHub.GetMembershipBinding`` method. + + Attributes: + name (str): + Required. The MembershipBinding resource name in the format + ``projects/*/locations/*/memberships/*/bindings/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateMembershipBindingRequest(proto.Message): + r"""Request to create a MembershipBinding. + + Attributes: + parent (str): + Required. The parent (project and location) where the + MembershipBinding will be created. Specified in the format + ``projects/*/locations/*/memberships/*``. + membership_binding (google.cloud.gkehub_v1.types.MembershipBinding): + Required. The MembershipBinding to create. + membership_binding_id (str): + Required. The ID to use for the + MembershipBinding. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + membership_binding: gcg_fleet.MembershipBinding = proto.Field( + proto.MESSAGE, + number=2, + message=gcg_fleet.MembershipBinding, + ) + membership_binding_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateMembershipBindingRequest(proto.Message): + r"""Request to update a MembershipBinding. + + Attributes: + membership_binding (google.cloud.gkehub_v1.types.MembershipBinding): + Required. The MembershipBinding object with + fields updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The fields to be updated. + """ + + membership_binding: gcg_fleet.MembershipBinding = proto.Field( + proto.MESSAGE, + number=1, + message=gcg_fleet.MembershipBinding, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteMembershipBindingRequest(proto.Message): + r"""Request to delete a Binding. + + Attributes: + name (str): + Required. The MembershipBinding resource name in the format + ``projects/*/locations/*/memberships/*/bindings/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListMembershipBindingsRequest(proto.Message): + r"""Request to list MembershipBinding. + + Attributes: + parent (str): + Required. The parent Membership for which the + MembershipBindings will be listed. Specified in the format + ``projects/*/locations/*/memberships/*``. + page_size (int): + Optional. When requesting a 'page' of resources, + ``page_size`` specifies number of resources to return. If + unspecified or set to 0, all resources will be returned. + page_token (str): + Optional. Token returned by previous call to + ``ListMembershipBindings`` which specifies the position in + the list from where to continue listing the resources. + filter (str): + Optional. Lists MembershipBindings that match + the filter expression, following the syntax + outlined in https://google.aip.dev/160. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListMembershipBindingsResponse(proto.Message): + r"""List of MembershipBindings. + + Attributes: + membership_bindings (MutableSequence[google.cloud.gkehub_v1.types.MembershipBinding]): + The list of membership_bindings + next_page_token (str): + A token to request the next page of resources from the + ``ListMembershipBindings`` method. The value of an empty + string means that there are no more resources to return. + unreachable (MutableSequence[str]): + List of locations that could not be reached + while fetching this list. + """ + + @property + def raw_page(self): + return self + + membership_bindings: MutableSequence[ + gcg_fleet.MembershipBinding + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcg_fleet.MembershipBinding, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + class ListMembershipsRequest(proto.Message): r"""Request message for ``GkeHub.ListMemberships`` method. @@ -62,57 +775,278 @@ class ListMembershipsRequest(proto.Message): unspecified or set to 0, all resources will be returned. page_token (str): Optional. Token returned by previous call to - ``ListMemberships`` which specifies the position in the list - from where to continue listing the resources. - filter (str): - Optional. Lists Memberships that match the filter - expression, following the syntax outlined in - https://google.aip.dev/160. + ``ListMemberships`` which specifies the position in the list + from where to continue listing the resources. + filter (str): + Optional. Lists Memberships that match the filter + expression, following the syntax outlined in + https://google.aip.dev/160. + + Examples: + + - Name is ``bar`` in project ``foo-proj`` and location + ``global``: + + name = "projects/foo-proj/locations/global/membership/bar" + + - Memberships that have a label called ``foo``: + + labels.foo:\* + + - Memberships that have a label called ``foo`` whose value + is ``bar``: + + labels.foo = bar + + - Memberships in the CREATING state: + + state = CREATING + order_by (str): + Optional. One or more fields to compare and + use to sort the output. See + https://google.aip.dev/132#ordering. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class GetMembershipRBACRoleBindingRequest(proto.Message): + r"""Request message for the ``GkeHub.GetMembershipRBACRoleBinding`` + method. + + Attributes: + name (str): + Required. The RBACRoleBinding resource name in the format + ``projects/*/locations/*/memberships/*/rbacrolebindings/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateMembershipRBACRoleBindingRequest(proto.Message): + r"""Request to create a rbacrolebindings. + + Attributes: + parent (str): + Required. The parent (project and location) where the + RBACRoleBinding will be created. Specified in the format + ``projects/*/locations/*/memberships/*``. + rbacrolebinding_id (str): + Required. Client chosen ID for the RBACRoleBinding. + ``rbacrolebinding_id`` must be a valid RFC 1123 compliant + DNS label: + + 1. At most 63 characters in length + 2. It must consist of lower case alphanumeric characters or + ``-`` + 3. It must start and end with an alphanumeric character + + Which can be expressed as the regex: + ``[a-z0-9]([-a-z0-9]*[a-z0-9])?``, with a maximum length of + 63 characters. + rbacrolebinding (google.cloud.gkehub_v1.types.RBACRoleBinding): + Required. The rbacrolebindings to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + rbacrolebinding_id: str = proto.Field( + proto.STRING, + number=2, + ) + rbacrolebinding: gcg_fleet.RBACRoleBinding = proto.Field( + proto.MESSAGE, + number=3, + message=gcg_fleet.RBACRoleBinding, + ) + + +class UpdateMembershipRBACRoleBindingRequest(proto.Message): + r"""Request to update a membership rbacrolebinding. + + Attributes: + rbacrolebinding (google.cloud.gkehub_v1.types.RBACRoleBinding): + Required. A rbacrolebinding with fields + updated. The 'name' field in this + rbacrolebinding is used to identify the resource + to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The fields to be updated. + """ + + rbacrolebinding: gcg_fleet.RBACRoleBinding = proto.Field( + proto.MESSAGE, + number=1, + message=gcg_fleet.RBACRoleBinding, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteMembershipRBACRoleBindingRequest(proto.Message): + r"""Request to delete a Membership RBACRoleBinding. + + Attributes: + name (str): + Required. The RBACRoleBinding resource name in the format + ``projects/*/locations/*/memberships/*/rbacrolebindings/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListMembershipRBACRoleBindingsRequest(proto.Message): + r"""Request to list Membership RBACRoleBindings. + + Attributes: + parent (str): + Required. The parent (project and location) where the + Features will be listed. Specified in the format + ``projects/*/locations/*/memberships/*``. + page_size (int): + Optional. When requesting a 'page' of resources, + ``page_size`` specifies number of resources to return. If + unspecified or set to 0, all resources will be returned. + page_token (str): + Optional. Token returned by previous call to + ``ListMembershipRBACRoleBindings`` which specifies the + position in the list from where to continue listing the + resources. + """ - Examples: + 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, + ) - - Name is ``bar`` in project ``foo-proj`` and location - ``global``: - name = "projects/foo-proj/locations/global/membership/bar" +class ListMembershipRBACRoleBindingsResponse(proto.Message): + r"""List of Membership RBACRoleBindings. - - Memberships that have a label called ``foo``: + Attributes: + rbacrolebindings (MutableSequence[google.cloud.gkehub_v1.types.RBACRoleBinding]): + The list of Membership RBACRoleBindings. + next_page_token (str): + A token to request the next page of resources from the + ``ListMembershipRBACRoleBindings`` method. The value of an + empty string means that there are no more resources to + return. + unreachable (MutableSequence[str]): + List of locations that could not be reached + while fetching this list. + """ - labels.foo:\* + @property + def raw_page(self): + return self - - Memberships that have a label called ``foo`` whose value - is ``bar``: + rbacrolebindings: MutableSequence[gcg_fleet.RBACRoleBinding] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcg_fleet.RBACRoleBinding, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) - labels.foo = bar - - Memberships in the CREATING state: +class GenerateMembershipRBACRoleBindingYAMLRequest(proto.Message): + r"""Request to generate a YAML of the RBAC policies for the + specified RoleBinding and its associated impersonation + resources. - state = CREATING - order_by (str): - Optional. One or more fields to compare and - use to sort the output. See - https://google.aip.dev/132#ordering. + Attributes: + parent (str): + Required. The parent (project and location) where the + RBACRoleBinding will be created. Specified in the format + ``projects/*/locations/*/memberships/*``. + rbacrolebinding_id (str): + Required. Client chosen ID for the RBACRoleBinding. + ``rbacrolebinding_id`` must be a valid RFC 1123 compliant + DNS label: + + 1. At most 63 characters in length + 2. It must consist of lower case alphanumeric characters or + ``-`` + 3. It must start and end with an alphanumeric character + + Which can be expressed as the regex: + ``[a-z0-9]([-a-z0-9]*[a-z0-9])?``, with a maximum length of + 63 characters. + rbacrolebinding (google.cloud.gkehub_v1.types.RBACRoleBinding): + Required. The rbacrolebindings to generate + the YAML for. """ parent: str = proto.Field( proto.STRING, number=1, ) - page_size: int = proto.Field( - proto.INT32, + rbacrolebinding_id: str = proto.Field( + proto.STRING, number=2, ) - page_token: str = proto.Field( - proto.STRING, + rbacrolebinding: gcg_fleet.RBACRoleBinding = proto.Field( + proto.MESSAGE, number=3, + message=gcg_fleet.RBACRoleBinding, ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - order_by: str = proto.Field( + + +class GenerateMembershipRBACRoleBindingYAMLResponse(proto.Message): + r"""Response for GenerateRBACRoleBindingYAML. + + Attributes: + role_bindings_yaml (str): + a yaml text blob including the RBAC policies. + """ + + role_bindings_yaml: str = proto.Field( proto.STRING, - number=5, + number=1, ) @@ -165,6 +1099,85 @@ class GetMembershipRequest(proto.Message): ) +class ListBoundMembershipsRequest(proto.Message): + r"""Request to list Memberships bound to a Scope. + + Attributes: + scope_name (str): + Required. Name of the Scope, in the format + ``projects/*/locations/global/scopes/*``, to which the + Memberships are bound. + filter (str): + Optional. Lists Memberships that match the filter + expression, following the syntax outlined in + https://google.aip.dev/160. Currently, filtering can be done + only based on Memberships's ``name``, ``labels``, + ``create_time``, ``update_time``, and ``unique_id``. + page_size (int): + Optional. When requesting a 'page' of resources, + ``page_size`` specifies number of resources to return. If + unspecified or set to 0, all resources will be returned. + Pagination is currently not supported; therefore, setting + this field does not have any impact for now. + page_token (str): + Optional. Token returned by previous call to + ``ListBoundMemberships`` which specifies the position in the + list from where to continue listing the resources. + """ + + scope_name: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListBoundMembershipsResponse(proto.Message): + r"""List of Memberships bound to a Scope. + + Attributes: + memberships (MutableSequence[google.cloud.gkehub_v1.types.Membership]): + The list of Memberships bound to the given + Scope. + unreachable (MutableSequence[str]): + List of locations that could not be reached + while fetching this list. + next_page_token (str): + A token to request the next page of resources from the + ``ListBoundMemberships`` method. The value of an empty + string means that there are no more resources to return. + """ + + @property + def raw_page(self): + return self + + memberships: MutableSequence[membership.Membership] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=membership.Membership, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + class CreateMembershipRequest(proto.Message): r"""Request message for the ``GkeHub.CreateMembership`` method. @@ -504,6 +1517,13 @@ class ListFeaturesRequest(proto.Message): One or more fields to compare and use to sort the output. See https://google.aip.dev/132#ordering. + return_partial_success (bool): + Optional. If set to true, the response will + return partial results when some regions are + unreachable and the unreachable field in Feature + proto will be populated. If set to false, the + request will fail when some regions are + unreachable. """ parent: str = proto.Field( @@ -526,6 +1546,10 @@ class ListFeaturesRequest(proto.Message): proto.STRING, number=5, ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=6, + ) class ListFeaturesResponse(proto.Message): @@ -562,12 +1586,23 @@ class GetFeatureRequest(proto.Message): name (str): Required. The Feature resource name in the format ``projects/*/locations/*/features/*`` + return_partial_success (bool): + Optional. If set to true, the response will + return partial results when some regions are + unreachable and the unreachable field in Feature + proto will be populated. If set to false, the + request will fail when some regions are + unreachable. """ name: str = proto.Field( proto.STRING, number=1, ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=2, + ) class CreateFeatureRequest(proto.Message): @@ -583,12 +1618,12 @@ class CreateFeatureRequest(proto.Message): resource (google.cloud.gkehub_v1.types.Feature): The Feature resource to create. request_id (str): - Optional. A request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. The server will guarantee that for at - least 60 minutes after the first request. + A request ID to identify requests. Specify a + unique request ID so that if you must retry your + request, the server will know to ignore the + request if it has already been completed. The + server will guarantee that for at least 60 + minutes after the first request. For example, consider a situation where you make an initial request and the request times out. If @@ -690,12 +1725,12 @@ class UpdateFeatureRequest(proto.Message): update_mask to be a special path "\*", fully replaces all user-modifiable fields to match ``resource``. request_id (str): - Optional. A request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. The server will guarantee that for at - least 60 minutes after the first request. + A request ID to identify requests. Specify a + unique request ID so that if you must retry your + request, the server will know to ignore the + request if it has already been completed. The + server will guarantee that for at least 60 + minutes after the first request. For example, consider a situation where you make an initial request and the request times out. If @@ -731,6 +1766,149 @@ class UpdateFeatureRequest(proto.Message): ) +class CreateFleetRequest(proto.Message): + r"""Request message for the ``GkeHub.CreateFleet`` method. + + Attributes: + parent (str): + Required. The parent (project and location) where the Fleet + will be created. Specified in the format + ``projects/*/locations/*``. + fleet (google.cloud.gkehub_v1.types.Fleet): + Required. The fleet to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + fleet: gcg_fleet.Fleet = proto.Field( + proto.MESSAGE, + number=2, + message=gcg_fleet.Fleet, + ) + + +class GetFleetRequest(proto.Message): + r"""Request message for the ``GkeHub.GetFleet`` method. + + Attributes: + name (str): + Required. The Fleet resource name in the format + ``projects/*/locations/*/fleets/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateFleetRequest(proto.Message): + r"""Request message for the ``GkeHub.UpdateFleet`` method. + + Attributes: + fleet (google.cloud.gkehub_v1.types.Fleet): + Required. The Fleet to update. + + The ``name`` field of the Fleet object identifies which + fleet will be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The fields to be updated; + """ + + fleet: gcg_fleet.Fleet = proto.Field( + proto.MESSAGE, + number=1, + message=gcg_fleet.Fleet, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteFleetRequest(proto.Message): + r"""Request message for ``GkeHub.DeleteFleet`` method. + + Attributes: + name (str): + Required. The Fleet resource name in the format + ``projects/*/locations/*/fleets/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFleetsRequest(proto.Message): + r"""Request message for the ``GkeHub.ListFleets`` method. + + Attributes: + parent (str): + Required. The organization or project to list for Fleets + under, in the format ``organizations/*/locations/*`` or + ``projects/*/locations/*``. + page_token (str): + Optional. A page token, received from a previous + ``ListFleets`` call. Provide this to retrieve the subsequent + page. + + When paginating, all other parameters provided to + ``ListFleets`` must match the call that provided the page + token. + page_size (int): + Optional. The maximum number of fleets to + return. The service may return fewer than this + value. If unspecified, at most 200 fleets will + be returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class ListFleetsResponse(proto.Message): + r"""Response message for the ``GkeHub.ListFleetsResponse`` method. + + Attributes: + fleets (MutableSequence[google.cloud.gkehub_v1.types.Fleet]): + The list of matching fleets. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. The token is only valid for 1h. + """ + + @property + def raw_page(self): + return self + + fleets: MutableSequence[gcg_fleet.Fleet] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcg_fleet.Fleet, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + class OperationMetadata(proto.Message): r"""Represents the metadata of the long-running operation. @@ -753,9 +1931,11 @@ class OperationMetadata(proto.Message): cancel_requested (bool): Output only. Identifies whether the user has requested cancellation of the operation. Operations that have - successfully been cancelled have [Operation.error][] value - with a [google.rpc.Status.code][google.rpc.Status.code] of - 1, corresponding to ``Code.CANCELLED``. + successfully been cancelled have + [google.longrunning.Operation.error][google.longrunning.Operation.error] + value with a + [google.rpc.Status.code][google.rpc.Status.code] of 1, + corresponding to ``Code.CANCELLED``. api_version (str): Output only. API version used to start the operation. diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_fleet_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_fleet_async.py new file mode 100644 index 000000000000..c164243015a1 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_fleet_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateFleet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_CreateFleet_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_create_fleet(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.CreateFleetRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_fleet(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_CreateFleet_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_fleet_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_fleet_sync.py new file mode 100644 index 000000000000..9451281520b1 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_fleet_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateFleet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_CreateFleet_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_create_fleet(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.CreateFleetRequest( + parent="parent_value", + ) + + # Make the request + operation = client.create_fleet(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_CreateFleet_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_binding_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_binding_async.py new file mode 100644 index 000000000000..a4297d0601e3 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_binding_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMembershipBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_CreateMembershipBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_create_membership_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + membership_binding = gkehub_v1.MembershipBinding() + membership_binding.scope = "scope_value" + + request = gkehub_v1.CreateMembershipBindingRequest( + parent="parent_value", + membership_binding=membership_binding, + membership_binding_id="membership_binding_id_value", + ) + + # Make the request + operation = client.create_membership_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_CreateMembershipBinding_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_binding_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_binding_sync.py new file mode 100644 index 000000000000..fe8c95aace0a --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_binding_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMembershipBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_CreateMembershipBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_create_membership_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + membership_binding = gkehub_v1.MembershipBinding() + membership_binding.scope = "scope_value" + + request = gkehub_v1.CreateMembershipBindingRequest( + parent="parent_value", + membership_binding=membership_binding, + membership_binding_id="membership_binding_id_value", + ) + + # Make the request + operation = client.create_membership_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_CreateMembershipBinding_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_rbac_role_binding_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_rbac_role_binding_async.py new file mode 100644 index 000000000000..2f4f857ee8b2 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_rbac_role_binding_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMembershipRBACRoleBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_CreateMembershipRBACRoleBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_create_membership_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + rbacrolebinding = gkehub_v1.RBACRoleBinding() + rbacrolebinding.user = "user_value" + + request = gkehub_v1.CreateMembershipRBACRoleBindingRequest( + parent="parent_value", + rbacrolebinding_id="rbacrolebinding_id_value", + rbacrolebinding=rbacrolebinding, + ) + + # Make the request + operation = client.create_membership_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_CreateMembershipRBACRoleBinding_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_rbac_role_binding_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_rbac_role_binding_sync.py new file mode 100644 index 000000000000..3cb00a5aab36 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_membership_rbac_role_binding_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMembershipRBACRoleBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_CreateMembershipRBACRoleBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_create_membership_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + rbacrolebinding = gkehub_v1.RBACRoleBinding() + rbacrolebinding.user = "user_value" + + request = gkehub_v1.CreateMembershipRBACRoleBindingRequest( + parent="parent_value", + rbacrolebinding_id="rbacrolebinding_id_value", + rbacrolebinding=rbacrolebinding, + ) + + # Make the request + operation = client.create_membership_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_CreateMembershipRBACRoleBinding_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_scope_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_scope_async.py new file mode 100644 index 000000000000..04c6fe341e03 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_scope_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateScope +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_CreateScope_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_create_scope(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.CreateScopeRequest( + parent="parent_value", + scope_id="scope_id_value", + ) + + # Make the request + operation = client.create_scope(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_CreateScope_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_scope_namespace_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_scope_namespace_async.py new file mode 100644 index 000000000000..298f88658b31 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_scope_namespace_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateScopeNamespace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_CreateScopeNamespace_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_create_scope_namespace(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + scope_namespace = gkehub_v1.Namespace() + scope_namespace.scope = "scope_value" + + request = gkehub_v1.CreateScopeNamespaceRequest( + parent="parent_value", + scope_namespace_id="scope_namespace_id_value", + scope_namespace=scope_namespace, + ) + + # Make the request + operation = client.create_scope_namespace(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_CreateScopeNamespace_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_scope_namespace_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_scope_namespace_sync.py new file mode 100644 index 000000000000..085a5287346b --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_scope_namespace_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateScopeNamespace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_CreateScopeNamespace_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_create_scope_namespace(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + scope_namespace = gkehub_v1.Namespace() + scope_namespace.scope = "scope_value" + + request = gkehub_v1.CreateScopeNamespaceRequest( + parent="parent_value", + scope_namespace_id="scope_namespace_id_value", + scope_namespace=scope_namespace, + ) + + # Make the request + operation = client.create_scope_namespace(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_CreateScopeNamespace_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_scope_rbac_role_binding_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_scope_rbac_role_binding_async.py new file mode 100644 index 000000000000..4dc53cb80f54 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_scope_rbac_role_binding_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateScopeRBACRoleBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_CreateScopeRBACRoleBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_create_scope_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + rbacrolebinding = gkehub_v1.RBACRoleBinding() + rbacrolebinding.user = "user_value" + + request = gkehub_v1.CreateScopeRBACRoleBindingRequest( + parent="parent_value", + rbacrolebinding_id="rbacrolebinding_id_value", + rbacrolebinding=rbacrolebinding, + ) + + # Make the request + operation = client.create_scope_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_CreateScopeRBACRoleBinding_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_scope_rbac_role_binding_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_scope_rbac_role_binding_sync.py new file mode 100644 index 000000000000..0f33072aa872 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_scope_rbac_role_binding_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateScopeRBACRoleBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_CreateScopeRBACRoleBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_create_scope_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + rbacrolebinding = gkehub_v1.RBACRoleBinding() + rbacrolebinding.user = "user_value" + + request = gkehub_v1.CreateScopeRBACRoleBindingRequest( + parent="parent_value", + rbacrolebinding_id="rbacrolebinding_id_value", + rbacrolebinding=rbacrolebinding, + ) + + # Make the request + operation = client.create_scope_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_CreateScopeRBACRoleBinding_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_scope_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_scope_sync.py new file mode 100644 index 000000000000..280d335b611d --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_create_scope_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateScope +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_CreateScope_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_create_scope(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.CreateScopeRequest( + parent="parent_value", + scope_id="scope_id_value", + ) + + # Make the request + operation = client.create_scope(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_CreateScope_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_fleet_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_fleet_async.py new file mode 100644 index 000000000000..8c28e1e667d8 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_fleet_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteFleet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_DeleteFleet_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_delete_fleet(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteFleetRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_fleet(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_DeleteFleet_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_fleet_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_fleet_sync.py new file mode 100644 index 000000000000..1e88a64d9ec6 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_fleet_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteFleet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_DeleteFleet_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_delete_fleet(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteFleetRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_fleet(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_DeleteFleet_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_membership_binding_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_membership_binding_async.py new file mode 100644 index 000000000000..9c2b1c67ddc7 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_membership_binding_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteMembershipBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_DeleteMembershipBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_delete_membership_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteMembershipBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_membership_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_DeleteMembershipBinding_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_membership_binding_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_membership_binding_sync.py new file mode 100644 index 000000000000..95fceb05884f --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_membership_binding_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteMembershipBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_DeleteMembershipBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_delete_membership_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteMembershipBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_membership_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_DeleteMembershipBinding_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_membership_rbac_role_binding_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_membership_rbac_role_binding_async.py new file mode 100644 index 000000000000..c77a660fccb9 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_membership_rbac_role_binding_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteMembershipRBACRoleBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_DeleteMembershipRBACRoleBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_delete_membership_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteMembershipRBACRoleBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_membership_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_DeleteMembershipRBACRoleBinding_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_membership_rbac_role_binding_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_membership_rbac_role_binding_sync.py new file mode 100644 index 000000000000..8ee198849e1a --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_membership_rbac_role_binding_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteMembershipRBACRoleBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_DeleteMembershipRBACRoleBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_delete_membership_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteMembershipRBACRoleBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_membership_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_DeleteMembershipRBACRoleBinding_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_scope_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_scope_async.py new file mode 100644 index 000000000000..318b01844035 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_scope_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteScope +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_DeleteScope_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_delete_scope(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteScopeRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_scope(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_DeleteScope_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_scope_namespace_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_scope_namespace_async.py new file mode 100644 index 000000000000..bba0f2c568e0 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_scope_namespace_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteScopeNamespace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_DeleteScopeNamespace_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_delete_scope_namespace(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteScopeNamespaceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_scope_namespace(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_DeleteScopeNamespace_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_scope_namespace_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_scope_namespace_sync.py new file mode 100644 index 000000000000..9044586320d7 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_scope_namespace_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteScopeNamespace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_DeleteScopeNamespace_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_delete_scope_namespace(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteScopeNamespaceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_scope_namespace(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_DeleteScopeNamespace_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_scope_rbac_role_binding_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_scope_rbac_role_binding_async.py new file mode 100644 index 000000000000..f1f6b6d152fc --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_scope_rbac_role_binding_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteScopeRBACRoleBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_DeleteScopeRBACRoleBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_delete_scope_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteScopeRBACRoleBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_scope_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_DeleteScopeRBACRoleBinding_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_scope_rbac_role_binding_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_scope_rbac_role_binding_sync.py new file mode 100644 index 000000000000..1aeabf113637 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_scope_rbac_role_binding_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteScopeRBACRoleBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_DeleteScopeRBACRoleBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_delete_scope_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteScopeRBACRoleBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_scope_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_DeleteScopeRBACRoleBinding_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_scope_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_scope_sync.py new file mode 100644 index 000000000000..128fca636296 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_delete_scope_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteScope +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_DeleteScope_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_delete_scope(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.DeleteScopeRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_scope(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_DeleteScope_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_generate_membership_rbac_role_binding_yaml_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_generate_membership_rbac_role_binding_yaml_async.py new file mode 100644 index 000000000000..8cd08f58b372 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_generate_membership_rbac_role_binding_yaml_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateMembershipRBACRoleBindingYAML +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_GenerateMembershipRBACRoleBindingYAML_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_generate_membership_rbac_role_binding_yaml(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + rbacrolebinding = gkehub_v1.RBACRoleBinding() + rbacrolebinding.user = "user_value" + + request = gkehub_v1.GenerateMembershipRBACRoleBindingYAMLRequest( + parent="parent_value", + rbacrolebinding_id="rbacrolebinding_id_value", + rbacrolebinding=rbacrolebinding, + ) + + # Make the request + response = await client.generate_membership_rbac_role_binding_yaml(request=request) + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_GenerateMembershipRBACRoleBindingYAML_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_generate_membership_rbac_role_binding_yaml_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_generate_membership_rbac_role_binding_yaml_sync.py new file mode 100644 index 000000000000..25b61b9aa0d8 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_generate_membership_rbac_role_binding_yaml_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateMembershipRBACRoleBindingYAML +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_GenerateMembershipRBACRoleBindingYAML_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_generate_membership_rbac_role_binding_yaml(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + rbacrolebinding = gkehub_v1.RBACRoleBinding() + rbacrolebinding.user = "user_value" + + request = gkehub_v1.GenerateMembershipRBACRoleBindingYAMLRequest( + parent="parent_value", + rbacrolebinding_id="rbacrolebinding_id_value", + rbacrolebinding=rbacrolebinding, + ) + + # Make the request + response = client.generate_membership_rbac_role_binding_yaml(request=request) + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_GenerateMembershipRBACRoleBindingYAML_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_fleet_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_fleet_async.py new file mode 100644 index 000000000000..2c47b5d4b213 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_fleet_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetFleet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_GetFleet_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_get_fleet(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.GetFleetRequest( + name="name_value", + ) + + # Make the request + response = await client.get_fleet(request=request) + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_GetFleet_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_fleet_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_fleet_sync.py new file mode 100644 index 000000000000..90e01682bf00 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_fleet_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetFleet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_GetFleet_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_get_fleet(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.GetFleetRequest( + name="name_value", + ) + + # Make the request + response = client.get_fleet(request=request) + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_GetFleet_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_membership_binding_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_membership_binding_async.py new file mode 100644 index 000000000000..3b1933369216 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_membership_binding_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMembershipBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_GetMembershipBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_get_membership_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.GetMembershipBindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_membership_binding(request=request) + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_GetMembershipBinding_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_membership_binding_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_membership_binding_sync.py new file mode 100644 index 000000000000..ea5c769c35cc --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_membership_binding_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMembershipBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_GetMembershipBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_get_membership_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.GetMembershipBindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_membership_binding(request=request) + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_GetMembershipBinding_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_membership_rbac_role_binding_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_membership_rbac_role_binding_async.py new file mode 100644 index 000000000000..39202abb9014 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_membership_rbac_role_binding_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMembershipRBACRoleBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_GetMembershipRBACRoleBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_get_membership_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.GetMembershipRBACRoleBindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_membership_rbac_role_binding(request=request) + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_GetMembershipRBACRoleBinding_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_membership_rbac_role_binding_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_membership_rbac_role_binding_sync.py new file mode 100644 index 000000000000..a54ce5cdae5e --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_membership_rbac_role_binding_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetMembershipRBACRoleBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_GetMembershipRBACRoleBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_get_membership_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.GetMembershipRBACRoleBindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_membership_rbac_role_binding(request=request) + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_GetMembershipRBACRoleBinding_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_scope_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_scope_async.py new file mode 100644 index 000000000000..94c9611283c2 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_scope_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetScope +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_GetScope_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_get_scope(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.GetScopeRequest( + name="name_value", + ) + + # Make the request + response = await client.get_scope(request=request) + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_GetScope_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_scope_namespace_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_scope_namespace_async.py new file mode 100644 index 000000000000..96ffe8b17190 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_scope_namespace_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetScopeNamespace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_GetScopeNamespace_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_get_scope_namespace(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.GetScopeNamespaceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_scope_namespace(request=request) + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_GetScopeNamespace_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_scope_namespace_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_scope_namespace_sync.py new file mode 100644 index 000000000000..438ed5c3beb2 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_scope_namespace_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetScopeNamespace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_GetScopeNamespace_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_get_scope_namespace(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.GetScopeNamespaceRequest( + name="name_value", + ) + + # Make the request + response = client.get_scope_namespace(request=request) + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_GetScopeNamespace_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_scope_rbac_role_binding_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_scope_rbac_role_binding_async.py new file mode 100644 index 000000000000..2eda0acfb673 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_scope_rbac_role_binding_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetScopeRBACRoleBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_GetScopeRBACRoleBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_get_scope_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.GetScopeRBACRoleBindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_scope_rbac_role_binding(request=request) + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_GetScopeRBACRoleBinding_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_scope_rbac_role_binding_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_scope_rbac_role_binding_sync.py new file mode 100644 index 000000000000..b3c1abcebb8c --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_scope_rbac_role_binding_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetScopeRBACRoleBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_GetScopeRBACRoleBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_get_scope_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.GetScopeRBACRoleBindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_scope_rbac_role_binding(request=request) + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_GetScopeRBACRoleBinding_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_scope_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_scope_sync.py new file mode 100644 index 000000000000..daa1efbe99d7 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_get_scope_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetScope +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_GetScope_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_get_scope(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.GetScopeRequest( + name="name_value", + ) + + # Make the request + response = client.get_scope(request=request) + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_GetScope_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_bound_memberships_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_bound_memberships_async.py new file mode 100644 index 000000000000..c47804c045e4 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_bound_memberships_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBoundMemberships +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_ListBoundMemberships_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_list_bound_memberships(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.ListBoundMembershipsRequest( + scope_name="scope_name_value", + ) + + # Make the request + page_result = client.list_bound_memberships(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END gkehub_v1_generated_GkeHub_ListBoundMemberships_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_bound_memberships_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_bound_memberships_sync.py new file mode 100644 index 000000000000..a32146f856ac --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_bound_memberships_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListBoundMemberships +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_ListBoundMemberships_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_list_bound_memberships(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.ListBoundMembershipsRequest( + scope_name="scope_name_value", + ) + + # Make the request + page_result = client.list_bound_memberships(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END gkehub_v1_generated_GkeHub_ListBoundMemberships_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_fleets_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_fleets_async.py new file mode 100644 index 000000000000..54d8d0589eb8 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_fleets_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListFleets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_ListFleets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_list_fleets(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.ListFleetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_fleets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END gkehub_v1_generated_GkeHub_ListFleets_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_fleets_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_fleets_sync.py new file mode 100644 index 000000000000..e3c9ec3862f2 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_fleets_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListFleets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_ListFleets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_list_fleets(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.ListFleetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_fleets(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END gkehub_v1_generated_GkeHub_ListFleets_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_membership_bindings_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_membership_bindings_async.py new file mode 100644 index 000000000000..346365d4e150 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_membership_bindings_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMembershipBindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_ListMembershipBindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_list_membership_bindings(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.ListMembershipBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_membership_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END gkehub_v1_generated_GkeHub_ListMembershipBindings_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_membership_bindings_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_membership_bindings_sync.py new file mode 100644 index 000000000000..1581e6e1e2eb --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_membership_bindings_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMembershipBindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_ListMembershipBindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_list_membership_bindings(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.ListMembershipBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_membership_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END gkehub_v1_generated_GkeHub_ListMembershipBindings_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_membership_rbac_role_bindings_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_membership_rbac_role_bindings_async.py new file mode 100644 index 000000000000..fe528136732a --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_membership_rbac_role_bindings_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMembershipRBACRoleBindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_ListMembershipRBACRoleBindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_list_membership_rbac_role_bindings(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.ListMembershipRBACRoleBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_membership_rbac_role_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END gkehub_v1_generated_GkeHub_ListMembershipRBACRoleBindings_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_membership_rbac_role_bindings_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_membership_rbac_role_bindings_sync.py new file mode 100644 index 000000000000..a24516c2526c --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_membership_rbac_role_bindings_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListMembershipRBACRoleBindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_ListMembershipRBACRoleBindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_list_membership_rbac_role_bindings(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.ListMembershipRBACRoleBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_membership_rbac_role_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END gkehub_v1_generated_GkeHub_ListMembershipRBACRoleBindings_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_permitted_scopes_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_permitted_scopes_async.py new file mode 100644 index 000000000000..12a7423729e0 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_permitted_scopes_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPermittedScopes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_ListPermittedScopes_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_list_permitted_scopes(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.ListPermittedScopesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_permitted_scopes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END gkehub_v1_generated_GkeHub_ListPermittedScopes_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_permitted_scopes_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_permitted_scopes_sync.py new file mode 100644 index 000000000000..15f0cf60fa6d --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_permitted_scopes_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPermittedScopes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_ListPermittedScopes_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_list_permitted_scopes(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.ListPermittedScopesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_permitted_scopes(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END gkehub_v1_generated_GkeHub_ListPermittedScopes_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_scope_namespaces_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_scope_namespaces_async.py new file mode 100644 index 000000000000..eb7c3810f617 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_scope_namespaces_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListScopeNamespaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_ListScopeNamespaces_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_list_scope_namespaces(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.ListScopeNamespacesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scope_namespaces(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END gkehub_v1_generated_GkeHub_ListScopeNamespaces_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_scope_namespaces_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_scope_namespaces_sync.py new file mode 100644 index 000000000000..a1f335b82018 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_scope_namespaces_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListScopeNamespaces +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_ListScopeNamespaces_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_list_scope_namespaces(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.ListScopeNamespacesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scope_namespaces(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END gkehub_v1_generated_GkeHub_ListScopeNamespaces_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_scope_rbac_role_bindings_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_scope_rbac_role_bindings_async.py new file mode 100644 index 000000000000..d9f34b224593 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_scope_rbac_role_bindings_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListScopeRBACRoleBindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_ListScopeRBACRoleBindings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_list_scope_rbac_role_bindings(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.ListScopeRBACRoleBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scope_rbac_role_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END gkehub_v1_generated_GkeHub_ListScopeRBACRoleBindings_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_scope_rbac_role_bindings_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_scope_rbac_role_bindings_sync.py new file mode 100644 index 000000000000..39512ec7354e --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_scope_rbac_role_bindings_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListScopeRBACRoleBindings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_ListScopeRBACRoleBindings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_list_scope_rbac_role_bindings(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.ListScopeRBACRoleBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scope_rbac_role_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END gkehub_v1_generated_GkeHub_ListScopeRBACRoleBindings_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_scopes_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_scopes_async.py new file mode 100644 index 000000000000..4dee1db18867 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_scopes_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListScopes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_ListScopes_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_list_scopes(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.ListScopesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scopes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END gkehub_v1_generated_GkeHub_ListScopes_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_scopes_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_scopes_sync.py new file mode 100644 index 000000000000..12adcb5f49b8 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_list_scopes_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListScopes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_ListScopes_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_list_scopes(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.ListScopesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scopes(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END gkehub_v1_generated_GkeHub_ListScopes_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_fleet_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_fleet_async.py new file mode 100644 index 000000000000..5bc3039fcb1c --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_fleet_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateFleet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_UpdateFleet_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_update_fleet(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.UpdateFleetRequest() + + # Make the request + operation = client.update_fleet(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_UpdateFleet_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_fleet_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_fleet_sync.py new file mode 100644 index 000000000000..f31ea4b446f3 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_fleet_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateFleet +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_UpdateFleet_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_update_fleet(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.UpdateFleetRequest() + + # Make the request + operation = client.update_fleet(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_UpdateFleet_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_membership_binding_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_membership_binding_async.py new file mode 100644 index 000000000000..19ff1c5552f6 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_membership_binding_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMembershipBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_UpdateMembershipBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_update_membership_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + membership_binding = gkehub_v1.MembershipBinding() + membership_binding.scope = "scope_value" + + request = gkehub_v1.UpdateMembershipBindingRequest( + membership_binding=membership_binding, + ) + + # Make the request + operation = client.update_membership_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_UpdateMembershipBinding_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_membership_binding_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_membership_binding_sync.py new file mode 100644 index 000000000000..ffbb540d8854 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_membership_binding_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMembershipBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_UpdateMembershipBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_update_membership_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + membership_binding = gkehub_v1.MembershipBinding() + membership_binding.scope = "scope_value" + + request = gkehub_v1.UpdateMembershipBindingRequest( + membership_binding=membership_binding, + ) + + # Make the request + operation = client.update_membership_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_UpdateMembershipBinding_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_membership_rbac_role_binding_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_membership_rbac_role_binding_async.py new file mode 100644 index 000000000000..155c9e99fad1 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_membership_rbac_role_binding_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMembershipRBACRoleBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_UpdateMembershipRBACRoleBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_update_membership_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + rbacrolebinding = gkehub_v1.RBACRoleBinding() + rbacrolebinding.user = "user_value" + + request = gkehub_v1.UpdateMembershipRBACRoleBindingRequest( + rbacrolebinding=rbacrolebinding, + ) + + # Make the request + operation = client.update_membership_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_UpdateMembershipRBACRoleBinding_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_membership_rbac_role_binding_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_membership_rbac_role_binding_sync.py new file mode 100644 index 000000000000..21f3ac85948c --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_membership_rbac_role_binding_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMembershipRBACRoleBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_UpdateMembershipRBACRoleBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_update_membership_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + rbacrolebinding = gkehub_v1.RBACRoleBinding() + rbacrolebinding.user = "user_value" + + request = gkehub_v1.UpdateMembershipRBACRoleBindingRequest( + rbacrolebinding=rbacrolebinding, + ) + + # Make the request + operation = client.update_membership_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_UpdateMembershipRBACRoleBinding_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_scope_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_scope_async.py new file mode 100644 index 000000000000..464a57e7781f --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_scope_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateScope +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_UpdateScope_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_update_scope(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + request = gkehub_v1.UpdateScopeRequest() + + # Make the request + operation = client.update_scope(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_UpdateScope_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_scope_namespace_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_scope_namespace_async.py new file mode 100644 index 000000000000..20e53abc0471 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_scope_namespace_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateScopeNamespace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_UpdateScopeNamespace_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_update_scope_namespace(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + scope_namespace = gkehub_v1.Namespace() + scope_namespace.scope = "scope_value" + + request = gkehub_v1.UpdateScopeNamespaceRequest( + scope_namespace=scope_namespace, + ) + + # Make the request + operation = client.update_scope_namespace(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_UpdateScopeNamespace_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_scope_namespace_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_scope_namespace_sync.py new file mode 100644 index 000000000000..3b6513d3985a --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_scope_namespace_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateScopeNamespace +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_UpdateScopeNamespace_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_update_scope_namespace(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + scope_namespace = gkehub_v1.Namespace() + scope_namespace.scope = "scope_value" + + request = gkehub_v1.UpdateScopeNamespaceRequest( + scope_namespace=scope_namespace, + ) + + # Make the request + operation = client.update_scope_namespace(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_UpdateScopeNamespace_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_scope_rbac_role_binding_async.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_scope_rbac_role_binding_async.py new file mode 100644 index 000000000000..271b23f7e0ea --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_scope_rbac_role_binding_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateScopeRBACRoleBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_UpdateScopeRBACRoleBinding_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +async def sample_update_scope_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubAsyncClient() + + # Initialize request argument(s) + rbacrolebinding = gkehub_v1.RBACRoleBinding() + rbacrolebinding.user = "user_value" + + request = gkehub_v1.UpdateScopeRBACRoleBindingRequest( + rbacrolebinding=rbacrolebinding, + ) + + # Make the request + operation = client.update_scope_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_UpdateScopeRBACRoleBinding_async] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_scope_rbac_role_binding_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_scope_rbac_role_binding_sync.py new file mode 100644 index 000000000000..8f7172389736 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_scope_rbac_role_binding_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateScopeRBACRoleBinding +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_UpdateScopeRBACRoleBinding_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_update_scope_rbac_role_binding(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + rbacrolebinding = gkehub_v1.RBACRoleBinding() + rbacrolebinding.user = "user_value" + + request = gkehub_v1.UpdateScopeRBACRoleBindingRequest( + rbacrolebinding=rbacrolebinding, + ) + + # Make the request + operation = client.update_scope_rbac_role_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_UpdateScopeRBACRoleBinding_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_scope_sync.py b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_scope_sync.py new file mode 100644 index 000000000000..093548e452d9 --- /dev/null +++ b/packages/google-cloud-gke-hub/samples/generated_samples/gkehub_v1_generated_gke_hub_update_scope_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateScope +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-gke-hub + + +# [START gkehub_v1_generated_GkeHub_UpdateScope_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import gkehub_v1 + + +def sample_update_scope(): + # Create a client + client = gkehub_v1.GkeHubClient() + + # Initialize request argument(s) + request = gkehub_v1.UpdateScopeRequest() + + # Make the request + operation = client.update_scope(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END gkehub_v1_generated_GkeHub_UpdateScope_sync] diff --git a/packages/google-cloud-gke-hub/samples/generated_samples/snippet_metadata_google.cloud.gkehub.v1.json b/packages/google-cloud-gke-hub/samples/generated_samples/snippet_metadata_google.cloud.gkehub.v1.json index ca194bc03e5f..216207275904 100644 --- a/packages/google-cloud-gke-hub/samples/generated_samples/snippet_metadata_google.cloud.gkehub.v1.json +++ b/packages/google-cloud-gke-hub/samples/generated_samples/snippet_metadata_google.cloud.gkehub.v1.json @@ -196,31 +196,27 @@ "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", "shortName": "GkeHubAsyncClient" }, - "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.create_membership", + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.create_fleet", "method": { - "fullName": "google.cloud.gkehub.v1.GkeHub.CreateMembership", + "fullName": "google.cloud.gkehub.v1.GkeHub.CreateFleet", "service": { "fullName": "google.cloud.gkehub.v1.GkeHub", "shortName": "GkeHub" }, - "shortName": "CreateMembership" + "shortName": "CreateFleet" }, "parameters": [ { "name": "request", - "type": "google.cloud.gkehub_v1.types.CreateMembershipRequest" + "type": "google.cloud.gkehub_v1.types.CreateFleetRequest" }, { "name": "parent", "type": "str" }, { - "name": "resource", - "type": "google.cloud.gkehub_v1.types.Membership" - }, - { - "name": "membership_id", - "type": "str" + "name": "fleet", + "type": "google.cloud.gkehub_v1.types.Fleet" }, { "name": "retry", @@ -236,21 +232,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_membership" + "shortName": "create_fleet" }, - "description": "Sample for CreateMembership", - "file": "gkehub_v1_generated_gke_hub_create_membership_async.py", + "description": "Sample for CreateFleet", + "file": "gkehub_v1_generated_gke_hub_create_fleet_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "gkehub_v1_generated_GkeHub_CreateMembership_async", + "regionTag": "gkehub_v1_generated_GkeHub_CreateFleet_async", "segments": [ { - "end": 56, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 55, "start": 27, "type": "SHORT" }, @@ -260,22 +256,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "gkehub_v1_generated_gke_hub_create_membership_async.py" + "title": "gkehub_v1_generated_gke_hub_create_fleet_async.py" }, { "canonical": true, @@ -284,31 +280,27 @@ "fullName": "google.cloud.gkehub_v1.GkeHubClient", "shortName": "GkeHubClient" }, - "fullName": "google.cloud.gkehub_v1.GkeHubClient.create_membership", + "fullName": "google.cloud.gkehub_v1.GkeHubClient.create_fleet", "method": { - "fullName": "google.cloud.gkehub.v1.GkeHub.CreateMembership", + "fullName": "google.cloud.gkehub.v1.GkeHub.CreateFleet", "service": { "fullName": "google.cloud.gkehub.v1.GkeHub", "shortName": "GkeHub" }, - "shortName": "CreateMembership" + "shortName": "CreateFleet" }, "parameters": [ { "name": "request", - "type": "google.cloud.gkehub_v1.types.CreateMembershipRequest" + "type": "google.cloud.gkehub_v1.types.CreateFleetRequest" }, { "name": "parent", "type": "str" }, { - "name": "resource", - "type": "google.cloud.gkehub_v1.types.Membership" - }, - { - "name": "membership_id", - "type": "str" + "name": "fleet", + "type": "google.cloud.gkehub_v1.types.Fleet" }, { "name": "retry", @@ -324,21 +316,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "create_membership" + "shortName": "create_fleet" }, - "description": "Sample for CreateMembership", - "file": "gkehub_v1_generated_gke_hub_create_membership_sync.py", + "description": "Sample for CreateFleet", + "file": "gkehub_v1_generated_gke_hub_create_fleet_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "gkehub_v1_generated_GkeHub_CreateMembership_sync", + "regionTag": "gkehub_v1_generated_GkeHub_CreateFleet_sync", "segments": [ { - "end": 56, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 55, "start": 27, "type": "SHORT" }, @@ -348,22 +340,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "gkehub_v1_generated_gke_hub_create_membership_sync.py" + "title": "gkehub_v1_generated_gke_hub_create_fleet_sync.py" }, { "canonical": true, @@ -373,22 +365,30 @@ "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", "shortName": "GkeHubAsyncClient" }, - "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.delete_feature", + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.create_membership_binding", "method": { - "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteFeature", + "fullName": "google.cloud.gkehub.v1.GkeHub.CreateMembershipBinding", "service": { "fullName": "google.cloud.gkehub.v1.GkeHub", "shortName": "GkeHub" }, - "shortName": "DeleteFeature" + "shortName": "CreateMembershipBinding" }, "parameters": [ { "name": "request", - "type": "google.cloud.gkehub_v1.types.DeleteFeatureRequest" + "type": "google.cloud.gkehub_v1.types.CreateMembershipBindingRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "membership_binding", + "type": "google.cloud.gkehub_v1.types.MembershipBinding" + }, + { + "name": "membership_binding_id", "type": "str" }, { @@ -405,21 +405,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_feature" + "shortName": "create_membership_binding" }, - "description": "Sample for DeleteFeature", - "file": "gkehub_v1_generated_gke_hub_delete_feature_async.py", + "description": "Sample for CreateMembershipBinding", + "file": "gkehub_v1_generated_gke_hub_create_membership_binding_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "gkehub_v1_generated_GkeHub_DeleteFeature_async", + "regionTag": "gkehub_v1_generated_GkeHub_CreateMembershipBinding_async", "segments": [ { - "end": 54, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 60, "start": 27, "type": "SHORT" }, @@ -429,22 +429,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 45, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "gkehub_v1_generated_gke_hub_delete_feature_async.py" + "title": "gkehub_v1_generated_gke_hub_create_membership_binding_async.py" }, { "canonical": true, @@ -453,22 +453,30 @@ "fullName": "google.cloud.gkehub_v1.GkeHubClient", "shortName": "GkeHubClient" }, - "fullName": "google.cloud.gkehub_v1.GkeHubClient.delete_feature", + "fullName": "google.cloud.gkehub_v1.GkeHubClient.create_membership_binding", "method": { - "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteFeature", + "fullName": "google.cloud.gkehub.v1.GkeHub.CreateMembershipBinding", "service": { "fullName": "google.cloud.gkehub.v1.GkeHub", "shortName": "GkeHub" }, - "shortName": "DeleteFeature" + "shortName": "CreateMembershipBinding" }, "parameters": [ { "name": "request", - "type": "google.cloud.gkehub_v1.types.DeleteFeatureRequest" + "type": "google.cloud.gkehub_v1.types.CreateMembershipBindingRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "membership_binding", + "type": "google.cloud.gkehub_v1.types.MembershipBinding" + }, + { + "name": "membership_binding_id", "type": "str" }, { @@ -485,21 +493,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_feature" + "shortName": "create_membership_binding" }, - "description": "Sample for DeleteFeature", - "file": "gkehub_v1_generated_gke_hub_delete_feature_sync.py", + "description": "Sample for CreateMembershipBinding", + "file": "gkehub_v1_generated_gke_hub_create_membership_binding_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "gkehub_v1_generated_GkeHub_DeleteFeature_sync", + "regionTag": "gkehub_v1_generated_GkeHub_CreateMembershipBinding_sync", "segments": [ { - "end": 54, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 60, "start": 27, "type": "SHORT" }, @@ -509,22 +517,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 45, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "gkehub_v1_generated_gke_hub_delete_feature_sync.py" + "title": "gkehub_v1_generated_gke_hub_create_membership_binding_sync.py" }, { "canonical": true, @@ -534,22 +542,30 @@ "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", "shortName": "GkeHubAsyncClient" }, - "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.delete_membership", + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.create_membership_rbac_role_binding", "method": { - "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteMembership", + "fullName": "google.cloud.gkehub.v1.GkeHub.CreateMembershipRBACRoleBinding", "service": { "fullName": "google.cloud.gkehub.v1.GkeHub", "shortName": "GkeHub" }, - "shortName": "DeleteMembership" + "shortName": "CreateMembershipRBACRoleBinding" }, "parameters": [ { "name": "request", - "type": "google.cloud.gkehub_v1.types.DeleteMembershipRequest" + "type": "google.cloud.gkehub_v1.types.CreateMembershipRBACRoleBindingRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "rbacrolebinding", + "type": "google.cloud.gkehub_v1.types.RBACRoleBinding" + }, + { + "name": "rbacrolebinding_id", "type": "str" }, { @@ -566,21 +582,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_membership" + "shortName": "create_membership_rbac_role_binding" }, - "description": "Sample for DeleteMembership", - "file": "gkehub_v1_generated_gke_hub_delete_membership_async.py", + "description": "Sample for CreateMembershipRBACRoleBinding", + "file": "gkehub_v1_generated_gke_hub_create_membership_rbac_role_binding_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "gkehub_v1_generated_GkeHub_DeleteMembership_async", + "regionTag": "gkehub_v1_generated_GkeHub_CreateMembershipRBACRoleBinding_async", "segments": [ { - "end": 55, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 60, "start": 27, "type": "SHORT" }, @@ -590,22 +606,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "gkehub_v1_generated_gke_hub_delete_membership_async.py" + "title": "gkehub_v1_generated_gke_hub_create_membership_rbac_role_binding_async.py" }, { "canonical": true, @@ -614,22 +630,30 @@ "fullName": "google.cloud.gkehub_v1.GkeHubClient", "shortName": "GkeHubClient" }, - "fullName": "google.cloud.gkehub_v1.GkeHubClient.delete_membership", + "fullName": "google.cloud.gkehub_v1.GkeHubClient.create_membership_rbac_role_binding", "method": { - "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteMembership", + "fullName": "google.cloud.gkehub.v1.GkeHub.CreateMembershipRBACRoleBinding", "service": { "fullName": "google.cloud.gkehub.v1.GkeHub", "shortName": "GkeHub" }, - "shortName": "DeleteMembership" + "shortName": "CreateMembershipRBACRoleBinding" }, "parameters": [ { "name": "request", - "type": "google.cloud.gkehub_v1.types.DeleteMembershipRequest" + "type": "google.cloud.gkehub_v1.types.CreateMembershipRBACRoleBindingRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "rbacrolebinding", + "type": "google.cloud.gkehub_v1.types.RBACRoleBinding" + }, + { + "name": "rbacrolebinding_id", "type": "str" }, { @@ -646,21 +670,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_membership" + "shortName": "create_membership_rbac_role_binding" }, - "description": "Sample for DeleteMembership", - "file": "gkehub_v1_generated_gke_hub_delete_membership_sync.py", + "description": "Sample for CreateMembershipRBACRoleBinding", + "file": "gkehub_v1_generated_gke_hub_create_membership_rbac_role_binding_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "gkehub_v1_generated_GkeHub_DeleteMembership_sync", + "regionTag": "gkehub_v1_generated_GkeHub_CreateMembershipRBACRoleBinding_sync", "segments": [ { - "end": 55, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 60, "start": 27, "type": "SHORT" }, @@ -670,22 +694,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "gkehub_v1_generated_gke_hub_delete_membership_sync.py" + "title": "gkehub_v1_generated_gke_hub_create_membership_rbac_role_binding_sync.py" }, { "canonical": true, @@ -695,19 +719,31 @@ "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", "shortName": "GkeHubAsyncClient" }, - "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.generate_connect_manifest", + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.create_membership", "method": { - "fullName": "google.cloud.gkehub.v1.GkeHub.GenerateConnectManifest", + "fullName": "google.cloud.gkehub.v1.GkeHub.CreateMembership", "service": { "fullName": "google.cloud.gkehub.v1.GkeHub", "shortName": "GkeHub" }, - "shortName": "GenerateConnectManifest" + "shortName": "CreateMembership" }, "parameters": [ { "name": "request", - "type": "google.cloud.gkehub_v1.types.GenerateConnectManifestRequest" + "type": "google.cloud.gkehub_v1.types.CreateMembershipRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource", + "type": "google.cloud.gkehub_v1.types.Membership" + }, + { + "name": "membership_id", + "type": "str" }, { "name": "retry", @@ -722,22 +758,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.gkehub_v1.types.GenerateConnectManifestResponse", - "shortName": "generate_connect_manifest" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_membership" }, - "description": "Sample for GenerateConnectManifest", - "file": "gkehub_v1_generated_gke_hub_generate_connect_manifest_async.py", + "description": "Sample for CreateMembership", + "file": "gkehub_v1_generated_gke_hub_create_membership_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "gkehub_v1_generated_GkeHub_GenerateConnectManifest_async", + "regionTag": "gkehub_v1_generated_GkeHub_CreateMembership_async", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -747,22 +783,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "gkehub_v1_generated_gke_hub_generate_connect_manifest_async.py" + "title": "gkehub_v1_generated_gke_hub_create_membership_async.py" }, { "canonical": true, @@ -771,19 +807,31 @@ "fullName": "google.cloud.gkehub_v1.GkeHubClient", "shortName": "GkeHubClient" }, - "fullName": "google.cloud.gkehub_v1.GkeHubClient.generate_connect_manifest", + "fullName": "google.cloud.gkehub_v1.GkeHubClient.create_membership", "method": { - "fullName": "google.cloud.gkehub.v1.GkeHub.GenerateConnectManifest", + "fullName": "google.cloud.gkehub.v1.GkeHub.CreateMembership", "service": { "fullName": "google.cloud.gkehub.v1.GkeHub", "shortName": "GkeHub" }, - "shortName": "GenerateConnectManifest" + "shortName": "CreateMembership" }, "parameters": [ { "name": "request", - "type": "google.cloud.gkehub_v1.types.GenerateConnectManifestRequest" + "type": "google.cloud.gkehub_v1.types.CreateMembershipRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource", + "type": "google.cloud.gkehub_v1.types.Membership" + }, + { + "name": "membership_id", + "type": "str" }, { "name": "retry", @@ -798,22 +846,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.gkehub_v1.types.GenerateConnectManifestResponse", - "shortName": "generate_connect_manifest" + "resultType": "google.api_core.operation.Operation", + "shortName": "create_membership" }, - "description": "Sample for GenerateConnectManifest", - "file": "gkehub_v1_generated_gke_hub_generate_connect_manifest_sync.py", + "description": "Sample for CreateMembership", + "file": "gkehub_v1_generated_gke_hub_create_membership_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "gkehub_v1_generated_GkeHub_GenerateConnectManifest_sync", + "regionTag": "gkehub_v1_generated_GkeHub_CreateMembership_sync", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -823,22 +871,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "gkehub_v1_generated_gke_hub_generate_connect_manifest_sync.py" + "title": "gkehub_v1_generated_gke_hub_create_membership_sync.py" }, { "canonical": true, @@ -848,24 +896,5228 @@ "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", "shortName": "GkeHubAsyncClient" }, - "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.get_feature", + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.create_scope_namespace", "method": { - "fullName": "google.cloud.gkehub.v1.GkeHub.GetFeature", + "fullName": "google.cloud.gkehub.v1.GkeHub.CreateScopeNamespace", "service": { "fullName": "google.cloud.gkehub.v1.GkeHub", "shortName": "GkeHub" }, - "shortName": "GetFeature" + "shortName": "CreateScopeNamespace" }, "parameters": [ { "name": "request", - "type": "google.cloud.gkehub_v1.types.GetFeatureRequest" + "type": "google.cloud.gkehub_v1.types.CreateScopeNamespaceRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "scope_namespace", + "type": "google.cloud.gkehub_v1.types.Namespace" + }, + { + "name": "scope_namespace_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_scope_namespace" + }, + "description": "Sample for CreateScopeNamespace", + "file": "gkehub_v1_generated_gke_hub_create_scope_namespace_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_CreateScopeNamespace_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_create_scope_namespace_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.create_scope_namespace", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.CreateScopeNamespace", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "CreateScopeNamespace" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.CreateScopeNamespaceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "scope_namespace", + "type": "google.cloud.gkehub_v1.types.Namespace" + }, + { + "name": "scope_namespace_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_scope_namespace" + }, + "description": "Sample for CreateScopeNamespace", + "file": "gkehub_v1_generated_gke_hub_create_scope_namespace_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_CreateScopeNamespace_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_create_scope_namespace_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.create_scope_rbac_role_binding", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.CreateScopeRBACRoleBinding", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "CreateScopeRBACRoleBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.CreateScopeRBACRoleBindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "rbacrolebinding", + "type": "google.cloud.gkehub_v1.types.RBACRoleBinding" + }, + { + "name": "rbacrolebinding_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_scope_rbac_role_binding" + }, + "description": "Sample for CreateScopeRBACRoleBinding", + "file": "gkehub_v1_generated_gke_hub_create_scope_rbac_role_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_CreateScopeRBACRoleBinding_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_create_scope_rbac_role_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.create_scope_rbac_role_binding", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.CreateScopeRBACRoleBinding", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "CreateScopeRBACRoleBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.CreateScopeRBACRoleBindingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "rbacrolebinding", + "type": "google.cloud.gkehub_v1.types.RBACRoleBinding" + }, + { + "name": "rbacrolebinding_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_scope_rbac_role_binding" + }, + "description": "Sample for CreateScopeRBACRoleBinding", + "file": "gkehub_v1_generated_gke_hub_create_scope_rbac_role_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_CreateScopeRBACRoleBinding_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_create_scope_rbac_role_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.create_scope", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.CreateScope", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "CreateScope" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.CreateScopeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "scope", + "type": "google.cloud.gkehub_v1.types.Scope" + }, + { + "name": "scope_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_scope" + }, + "description": "Sample for CreateScope", + "file": "gkehub_v1_generated_gke_hub_create_scope_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_CreateScope_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_create_scope_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.create_scope", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.CreateScope", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "CreateScope" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.CreateScopeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "scope", + "type": "google.cloud.gkehub_v1.types.Scope" + }, + { + "name": "scope_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_scope" + }, + "description": "Sample for CreateScope", + "file": "gkehub_v1_generated_gke_hub_create_scope_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_CreateScope_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_create_scope_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.delete_feature", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteFeature", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "DeleteFeature" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.DeleteFeatureRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_feature" + }, + "description": "Sample for DeleteFeature", + "file": "gkehub_v1_generated_gke_hub_delete_feature_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_DeleteFeature_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_delete_feature_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.delete_feature", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteFeature", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "DeleteFeature" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.DeleteFeatureRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_feature" + }, + "description": "Sample for DeleteFeature", + "file": "gkehub_v1_generated_gke_hub_delete_feature_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_DeleteFeature_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_delete_feature_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.delete_fleet", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteFleet", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "DeleteFleet" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.DeleteFleetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_fleet" + }, + "description": "Sample for DeleteFleet", + "file": "gkehub_v1_generated_gke_hub_delete_fleet_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_DeleteFleet_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_delete_fleet_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.delete_fleet", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteFleet", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "DeleteFleet" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.DeleteFleetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_fleet" + }, + "description": "Sample for DeleteFleet", + "file": "gkehub_v1_generated_gke_hub_delete_fleet_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_DeleteFleet_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_delete_fleet_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.delete_membership_binding", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteMembershipBinding", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "DeleteMembershipBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.DeleteMembershipBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_membership_binding" + }, + "description": "Sample for DeleteMembershipBinding", + "file": "gkehub_v1_generated_gke_hub_delete_membership_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_DeleteMembershipBinding_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_delete_membership_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.delete_membership_binding", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteMembershipBinding", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "DeleteMembershipBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.DeleteMembershipBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_membership_binding" + }, + "description": "Sample for DeleteMembershipBinding", + "file": "gkehub_v1_generated_gke_hub_delete_membership_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_DeleteMembershipBinding_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_delete_membership_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.delete_membership_rbac_role_binding", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteMembershipRBACRoleBinding", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "DeleteMembershipRBACRoleBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.DeleteMembershipRBACRoleBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_membership_rbac_role_binding" + }, + "description": "Sample for DeleteMembershipRBACRoleBinding", + "file": "gkehub_v1_generated_gke_hub_delete_membership_rbac_role_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_DeleteMembershipRBACRoleBinding_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_delete_membership_rbac_role_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.delete_membership_rbac_role_binding", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteMembershipRBACRoleBinding", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "DeleteMembershipRBACRoleBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.DeleteMembershipRBACRoleBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_membership_rbac_role_binding" + }, + "description": "Sample for DeleteMembershipRBACRoleBinding", + "file": "gkehub_v1_generated_gke_hub_delete_membership_rbac_role_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_DeleteMembershipRBACRoleBinding_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_delete_membership_rbac_role_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.delete_membership", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteMembership", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "DeleteMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.DeleteMembershipRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_membership" + }, + "description": "Sample for DeleteMembership", + "file": "gkehub_v1_generated_gke_hub_delete_membership_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_DeleteMembership_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_delete_membership_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.delete_membership", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteMembership", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "DeleteMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.DeleteMembershipRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_membership" + }, + "description": "Sample for DeleteMembership", + "file": "gkehub_v1_generated_gke_hub_delete_membership_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_DeleteMembership_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_delete_membership_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.delete_scope_namespace", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteScopeNamespace", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "DeleteScopeNamespace" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.DeleteScopeNamespaceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_scope_namespace" + }, + "description": "Sample for DeleteScopeNamespace", + "file": "gkehub_v1_generated_gke_hub_delete_scope_namespace_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_DeleteScopeNamespace_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_delete_scope_namespace_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.delete_scope_namespace", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteScopeNamespace", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "DeleteScopeNamespace" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.DeleteScopeNamespaceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_scope_namespace" + }, + "description": "Sample for DeleteScopeNamespace", + "file": "gkehub_v1_generated_gke_hub_delete_scope_namespace_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_DeleteScopeNamespace_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_delete_scope_namespace_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.delete_scope_rbac_role_binding", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteScopeRBACRoleBinding", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "DeleteScopeRBACRoleBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.DeleteScopeRBACRoleBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_scope_rbac_role_binding" + }, + "description": "Sample for DeleteScopeRBACRoleBinding", + "file": "gkehub_v1_generated_gke_hub_delete_scope_rbac_role_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_DeleteScopeRBACRoleBinding_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_delete_scope_rbac_role_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.delete_scope_rbac_role_binding", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteScopeRBACRoleBinding", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "DeleteScopeRBACRoleBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.DeleteScopeRBACRoleBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_scope_rbac_role_binding" + }, + "description": "Sample for DeleteScopeRBACRoleBinding", + "file": "gkehub_v1_generated_gke_hub_delete_scope_rbac_role_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_DeleteScopeRBACRoleBinding_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_delete_scope_rbac_role_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.delete_scope", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteScope", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "DeleteScope" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.DeleteScopeRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_scope" + }, + "description": "Sample for DeleteScope", + "file": "gkehub_v1_generated_gke_hub_delete_scope_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_DeleteScope_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_delete_scope_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.delete_scope", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.DeleteScope", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "DeleteScope" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.DeleteScopeRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_scope" + }, + "description": "Sample for DeleteScope", + "file": "gkehub_v1_generated_gke_hub_delete_scope_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_DeleteScope_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_delete_scope_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.generate_connect_manifest", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GenerateConnectManifest", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GenerateConnectManifest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GenerateConnectManifestRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.GenerateConnectManifestResponse", + "shortName": "generate_connect_manifest" + }, + "description": "Sample for GenerateConnectManifest", + "file": "gkehub_v1_generated_gke_hub_generate_connect_manifest_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GenerateConnectManifest_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_generate_connect_manifest_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.generate_connect_manifest", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GenerateConnectManifest", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GenerateConnectManifest" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GenerateConnectManifestRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.GenerateConnectManifestResponse", + "shortName": "generate_connect_manifest" + }, + "description": "Sample for GenerateConnectManifest", + "file": "gkehub_v1_generated_gke_hub_generate_connect_manifest_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GenerateConnectManifest_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_generate_connect_manifest_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.generate_membership_rbac_role_binding_yaml", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GenerateMembershipRBACRoleBindingYAML", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GenerateMembershipRBACRoleBindingYAML" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GenerateMembershipRBACRoleBindingYAMLRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.GenerateMembershipRBACRoleBindingYAMLResponse", + "shortName": "generate_membership_rbac_role_binding_yaml" + }, + "description": "Sample for GenerateMembershipRBACRoleBindingYAML", + "file": "gkehub_v1_generated_gke_hub_generate_membership_rbac_role_binding_yaml_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GenerateMembershipRBACRoleBindingYAML_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_generate_membership_rbac_role_binding_yaml_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.generate_membership_rbac_role_binding_yaml", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GenerateMembershipRBACRoleBindingYAML", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GenerateMembershipRBACRoleBindingYAML" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GenerateMembershipRBACRoleBindingYAMLRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.GenerateMembershipRBACRoleBindingYAMLResponse", + "shortName": "generate_membership_rbac_role_binding_yaml" + }, + "description": "Sample for GenerateMembershipRBACRoleBindingYAML", + "file": "gkehub_v1_generated_gke_hub_generate_membership_rbac_role_binding_yaml_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GenerateMembershipRBACRoleBindingYAML_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_generate_membership_rbac_role_binding_yaml_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.get_feature", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GetFeature", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GetFeature" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GetFeatureRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.Feature", + "shortName": "get_feature" + }, + "description": "Sample for GetFeature", + "file": "gkehub_v1_generated_gke_hub_get_feature_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GetFeature_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": "gkehub_v1_generated_gke_hub_get_feature_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.get_feature", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GetFeature", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GetFeature" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GetFeatureRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.Feature", + "shortName": "get_feature" + }, + "description": "Sample for GetFeature", + "file": "gkehub_v1_generated_gke_hub_get_feature_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GetFeature_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": "gkehub_v1_generated_gke_hub_get_feature_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.get_fleet", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GetFleet", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GetFleet" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GetFleetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.Fleet", + "shortName": "get_fleet" + }, + "description": "Sample for GetFleet", + "file": "gkehub_v1_generated_gke_hub_get_fleet_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GetFleet_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_get_fleet_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.get_fleet", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GetFleet", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GetFleet" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GetFleetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.Fleet", + "shortName": "get_fleet" + }, + "description": "Sample for GetFleet", + "file": "gkehub_v1_generated_gke_hub_get_fleet_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GetFleet_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_get_fleet_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.get_membership_binding", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GetMembershipBinding", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GetMembershipBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GetMembershipBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.MembershipBinding", + "shortName": "get_membership_binding" + }, + "description": "Sample for GetMembershipBinding", + "file": "gkehub_v1_generated_gke_hub_get_membership_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GetMembershipBinding_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_get_membership_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.get_membership_binding", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GetMembershipBinding", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GetMembershipBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GetMembershipBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.MembershipBinding", + "shortName": "get_membership_binding" + }, + "description": "Sample for GetMembershipBinding", + "file": "gkehub_v1_generated_gke_hub_get_membership_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GetMembershipBinding_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_get_membership_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.get_membership_rbac_role_binding", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GetMembershipRBACRoleBinding", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GetMembershipRBACRoleBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GetMembershipRBACRoleBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.RBACRoleBinding", + "shortName": "get_membership_rbac_role_binding" + }, + "description": "Sample for GetMembershipRBACRoleBinding", + "file": "gkehub_v1_generated_gke_hub_get_membership_rbac_role_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GetMembershipRBACRoleBinding_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_get_membership_rbac_role_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.get_membership_rbac_role_binding", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GetMembershipRBACRoleBinding", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GetMembershipRBACRoleBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GetMembershipRBACRoleBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.RBACRoleBinding", + "shortName": "get_membership_rbac_role_binding" + }, + "description": "Sample for GetMembershipRBACRoleBinding", + "file": "gkehub_v1_generated_gke_hub_get_membership_rbac_role_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GetMembershipRBACRoleBinding_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_get_membership_rbac_role_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.get_membership", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GetMembership", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GetMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GetMembershipRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.Membership", + "shortName": "get_membership" + }, + "description": "Sample for GetMembership", + "file": "gkehub_v1_generated_gke_hub_get_membership_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GetMembership_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_get_membership_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.get_membership", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GetMembership", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GetMembership" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GetMembershipRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.Membership", + "shortName": "get_membership" + }, + "description": "Sample for GetMembership", + "file": "gkehub_v1_generated_gke_hub_get_membership_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GetMembership_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_get_membership_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.get_scope_namespace", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GetScopeNamespace", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GetScopeNamespace" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GetScopeNamespaceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.Namespace", + "shortName": "get_scope_namespace" + }, + "description": "Sample for GetScopeNamespace", + "file": "gkehub_v1_generated_gke_hub_get_scope_namespace_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GetScopeNamespace_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_get_scope_namespace_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.get_scope_namespace", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GetScopeNamespace", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GetScopeNamespace" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GetScopeNamespaceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.Namespace", + "shortName": "get_scope_namespace" + }, + "description": "Sample for GetScopeNamespace", + "file": "gkehub_v1_generated_gke_hub_get_scope_namespace_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GetScopeNamespace_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_get_scope_namespace_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.get_scope_rbac_role_binding", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GetScopeRBACRoleBinding", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GetScopeRBACRoleBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GetScopeRBACRoleBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.RBACRoleBinding", + "shortName": "get_scope_rbac_role_binding" + }, + "description": "Sample for GetScopeRBACRoleBinding", + "file": "gkehub_v1_generated_gke_hub_get_scope_rbac_role_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GetScopeRBACRoleBinding_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_get_scope_rbac_role_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.get_scope_rbac_role_binding", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GetScopeRBACRoleBinding", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GetScopeRBACRoleBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GetScopeRBACRoleBindingRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.RBACRoleBinding", + "shortName": "get_scope_rbac_role_binding" + }, + "description": "Sample for GetScopeRBACRoleBinding", + "file": "gkehub_v1_generated_gke_hub_get_scope_rbac_role_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GetScopeRBACRoleBinding_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_get_scope_rbac_role_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.get_scope", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GetScope", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GetScope" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GetScopeRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.Scope", + "shortName": "get_scope" + }, + "description": "Sample for GetScope", + "file": "gkehub_v1_generated_gke_hub_get_scope_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GetScope_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_get_scope_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.get_scope", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.GetScope", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "GetScope" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.GetScopeRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.types.Scope", + "shortName": "get_scope" + }, + "description": "Sample for GetScope", + "file": "gkehub_v1_generated_gke_hub_get_scope_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_GetScope_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_get_scope_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.list_bound_memberships", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListBoundMemberships", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListBoundMemberships" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListBoundMembershipsRequest" + }, + { + "name": "scope_name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListBoundMembershipsAsyncPager", + "shortName": "list_bound_memberships" + }, + "description": "Sample for ListBoundMemberships", + "file": "gkehub_v1_generated_gke_hub_list_bound_memberships_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListBoundMemberships_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": "gkehub_v1_generated_gke_hub_list_bound_memberships_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.list_bound_memberships", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListBoundMemberships", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListBoundMemberships" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListBoundMembershipsRequest" + }, + { + "name": "scope_name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListBoundMembershipsPager", + "shortName": "list_bound_memberships" + }, + "description": "Sample for ListBoundMemberships", + "file": "gkehub_v1_generated_gke_hub_list_bound_memberships_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListBoundMemberships_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": "gkehub_v1_generated_gke_hub_list_bound_memberships_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.list_features", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListFeatures", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListFeatures" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListFeaturesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListFeaturesAsyncPager", + "shortName": "list_features" + }, + "description": "Sample for ListFeatures", + "file": "gkehub_v1_generated_gke_hub_list_features_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListFeatures_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_list_features_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.list_features", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListFeatures", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListFeatures" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListFeaturesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListFeaturesPager", + "shortName": "list_features" + }, + "description": "Sample for ListFeatures", + "file": "gkehub_v1_generated_gke_hub_list_features_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListFeatures_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_list_features_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.list_fleets", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListFleets", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListFleets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListFleetsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListFleetsAsyncPager", + "shortName": "list_fleets" + }, + "description": "Sample for ListFleets", + "file": "gkehub_v1_generated_gke_hub_list_fleets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListFleets_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": "gkehub_v1_generated_gke_hub_list_fleets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.list_fleets", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListFleets", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListFleets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListFleetsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListFleetsPager", + "shortName": "list_fleets" + }, + "description": "Sample for ListFleets", + "file": "gkehub_v1_generated_gke_hub_list_fleets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListFleets_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": "gkehub_v1_generated_gke_hub_list_fleets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.list_membership_bindings", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListMembershipBindings", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListMembershipBindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListMembershipBindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListMembershipBindingsAsyncPager", + "shortName": "list_membership_bindings" + }, + "description": "Sample for ListMembershipBindings", + "file": "gkehub_v1_generated_gke_hub_list_membership_bindings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListMembershipBindings_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": "gkehub_v1_generated_gke_hub_list_membership_bindings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.list_membership_bindings", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListMembershipBindings", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListMembershipBindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListMembershipBindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListMembershipBindingsPager", + "shortName": "list_membership_bindings" + }, + "description": "Sample for ListMembershipBindings", + "file": "gkehub_v1_generated_gke_hub_list_membership_bindings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListMembershipBindings_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": "gkehub_v1_generated_gke_hub_list_membership_bindings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.list_membership_rbac_role_bindings", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListMembershipRBACRoleBindings", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListMembershipRBACRoleBindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListMembershipRBACRoleBindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListMembershipRBACRoleBindingsAsyncPager", + "shortName": "list_membership_rbac_role_bindings" + }, + "description": "Sample for ListMembershipRBACRoleBindings", + "file": "gkehub_v1_generated_gke_hub_list_membership_rbac_role_bindings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListMembershipRBACRoleBindings_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": "gkehub_v1_generated_gke_hub_list_membership_rbac_role_bindings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.list_membership_rbac_role_bindings", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListMembershipRBACRoleBindings", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListMembershipRBACRoleBindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListMembershipRBACRoleBindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListMembershipRBACRoleBindingsPager", + "shortName": "list_membership_rbac_role_bindings" + }, + "description": "Sample for ListMembershipRBACRoleBindings", + "file": "gkehub_v1_generated_gke_hub_list_membership_rbac_role_bindings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListMembershipRBACRoleBindings_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": "gkehub_v1_generated_gke_hub_list_membership_rbac_role_bindings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.list_memberships", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListMemberships", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListMemberships" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListMembershipsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListMembershipsAsyncPager", + "shortName": "list_memberships" + }, + "description": "Sample for ListMemberships", + "file": "gkehub_v1_generated_gke_hub_list_memberships_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListMemberships_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": "gkehub_v1_generated_gke_hub_list_memberships_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.list_memberships", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListMemberships", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListMemberships" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListMembershipsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListMembershipsPager", + "shortName": "list_memberships" + }, + "description": "Sample for ListMemberships", + "file": "gkehub_v1_generated_gke_hub_list_memberships_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListMemberships_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": "gkehub_v1_generated_gke_hub_list_memberships_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.list_permitted_scopes", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListPermittedScopes", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListPermittedScopes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListPermittedScopesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListPermittedScopesAsyncPager", + "shortName": "list_permitted_scopes" + }, + "description": "Sample for ListPermittedScopes", + "file": "gkehub_v1_generated_gke_hub_list_permitted_scopes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListPermittedScopes_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": "gkehub_v1_generated_gke_hub_list_permitted_scopes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.list_permitted_scopes", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListPermittedScopes", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListPermittedScopes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListPermittedScopesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListPermittedScopesPager", + "shortName": "list_permitted_scopes" + }, + "description": "Sample for ListPermittedScopes", + "file": "gkehub_v1_generated_gke_hub_list_permitted_scopes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListPermittedScopes_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": "gkehub_v1_generated_gke_hub_list_permitted_scopes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.list_scope_namespaces", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListScopeNamespaces", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListScopeNamespaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListScopeNamespacesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListScopeNamespacesAsyncPager", + "shortName": "list_scope_namespaces" + }, + "description": "Sample for ListScopeNamespaces", + "file": "gkehub_v1_generated_gke_hub_list_scope_namespaces_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListScopeNamespaces_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": "gkehub_v1_generated_gke_hub_list_scope_namespaces_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.list_scope_namespaces", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListScopeNamespaces", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListScopeNamespaces" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListScopeNamespacesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListScopeNamespacesPager", + "shortName": "list_scope_namespaces" + }, + "description": "Sample for ListScopeNamespaces", + "file": "gkehub_v1_generated_gke_hub_list_scope_namespaces_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListScopeNamespaces_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": "gkehub_v1_generated_gke_hub_list_scope_namespaces_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.list_scope_rbac_role_bindings", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListScopeRBACRoleBindings", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListScopeRBACRoleBindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListScopeRBACRoleBindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListScopeRBACRoleBindingsAsyncPager", + "shortName": "list_scope_rbac_role_bindings" + }, + "description": "Sample for ListScopeRBACRoleBindings", + "file": "gkehub_v1_generated_gke_hub_list_scope_rbac_role_bindings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListScopeRBACRoleBindings_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": "gkehub_v1_generated_gke_hub_list_scope_rbac_role_bindings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.list_scope_rbac_role_bindings", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListScopeRBACRoleBindings", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListScopeRBACRoleBindings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListScopeRBACRoleBindingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListScopeRBACRoleBindingsPager", + "shortName": "list_scope_rbac_role_bindings" + }, + "description": "Sample for ListScopeRBACRoleBindings", + "file": "gkehub_v1_generated_gke_hub_list_scope_rbac_role_bindings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListScopeRBACRoleBindings_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": "gkehub_v1_generated_gke_hub_list_scope_rbac_role_bindings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.list_scopes", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListScopes", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListScopes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListScopesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListScopesAsyncPager", + "shortName": "list_scopes" + }, + "description": "Sample for ListScopes", + "file": "gkehub_v1_generated_gke_hub_list_scopes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListScopes_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": "gkehub_v1_generated_gke_hub_list_scopes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.list_scopes", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.ListScopes", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "ListScopes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.ListScopesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListScopesPager", + "shortName": "list_scopes" + }, + "description": "Sample for ListScopes", + "file": "gkehub_v1_generated_gke_hub_list_scopes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_ListScopes_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": "gkehub_v1_generated_gke_hub_list_scopes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.update_feature", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateFeature", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "UpdateFeature" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.UpdateFeatureRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "resource", + "type": "google.cloud.gkehub_v1.types.Feature" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_feature" + }, + "description": "Sample for UpdateFeature", + "file": "gkehub_v1_generated_gke_hub_update_feature_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_UpdateFeature_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_update_feature_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.update_feature", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateFeature", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "UpdateFeature" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.UpdateFeatureRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "resource", + "type": "google.cloud.gkehub_v1.types.Feature" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_feature" + }, + "description": "Sample for UpdateFeature", + "file": "gkehub_v1_generated_gke_hub_update_feature_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_UpdateFeature_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_update_feature_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.update_fleet", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateFleet", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "UpdateFleet" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.UpdateFleetRequest" + }, + { + "name": "fleet", + "type": "google.cloud.gkehub_v1.types.Fleet" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -879,22 +6131,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.gkehub_v1.types.Feature", - "shortName": "get_feature" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_fleet" }, - "description": "Sample for GetFeature", - "file": "gkehub_v1_generated_gke_hub_get_feature_async.py", + "description": "Sample for UpdateFleet", + "file": "gkehub_v1_generated_gke_hub_update_fleet_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "gkehub_v1_generated_GkeHub_GetFeature_async", + "regionTag": "gkehub_v1_generated_GkeHub_UpdateFleet_async", "segments": [ { - "end": 50, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 54, "start": 27, "type": "SHORT" }, @@ -909,17 +6161,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 47, + "end": 51, "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "gkehub_v1_generated_gke_hub_get_feature_async.py" + "title": "gkehub_v1_generated_gke_hub_update_fleet_async.py" }, { "canonical": true, @@ -928,23 +6180,27 @@ "fullName": "google.cloud.gkehub_v1.GkeHubClient", "shortName": "GkeHubClient" }, - "fullName": "google.cloud.gkehub_v1.GkeHubClient.get_feature", + "fullName": "google.cloud.gkehub_v1.GkeHubClient.update_fleet", "method": { - "fullName": "google.cloud.gkehub.v1.GkeHub.GetFeature", + "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateFleet", "service": { "fullName": "google.cloud.gkehub.v1.GkeHub", "shortName": "GkeHub" }, - "shortName": "GetFeature" + "shortName": "UpdateFleet" }, "parameters": [ { "name": "request", - "type": "google.cloud.gkehub_v1.types.GetFeatureRequest" + "type": "google.cloud.gkehub_v1.types.UpdateFleetRequest" }, { - "name": "name", - "type": "str" + "name": "fleet", + "type": "google.cloud.gkehub_v1.types.Fleet" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -959,22 +6215,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.gkehub_v1.types.Feature", - "shortName": "get_feature" + "resultType": "google.api_core.operation.Operation", + "shortName": "update_fleet" }, - "description": "Sample for GetFeature", - "file": "gkehub_v1_generated_gke_hub_get_feature_sync.py", + "description": "Sample for UpdateFleet", + "file": "gkehub_v1_generated_gke_hub_update_fleet_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "gkehub_v1_generated_GkeHub_GetFeature_sync", + "regionTag": "gkehub_v1_generated_GkeHub_UpdateFleet_sync", "segments": [ { - "end": 50, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 54, "start": 27, "type": "SHORT" }, @@ -989,17 +6245,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 47, + "end": 51, "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "gkehub_v1_generated_gke_hub_get_feature_sync.py" + "title": "gkehub_v1_generated_gke_hub_update_fleet_sync.py" }, { "canonical": true, @@ -1009,23 +6265,27 @@ "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", "shortName": "GkeHubAsyncClient" }, - "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.get_membership", + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.update_membership_binding", "method": { - "fullName": "google.cloud.gkehub.v1.GkeHub.GetMembership", + "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateMembershipBinding", "service": { "fullName": "google.cloud.gkehub.v1.GkeHub", "shortName": "GkeHub" }, - "shortName": "GetMembership" + "shortName": "UpdateMembershipBinding" }, "parameters": [ { "name": "request", - "type": "google.cloud.gkehub_v1.types.GetMembershipRequest" + "type": "google.cloud.gkehub_v1.types.UpdateMembershipBindingRequest" }, { - "name": "name", - "type": "str" + "name": "membership_binding", + "type": "google.cloud.gkehub_v1.types.MembershipBinding" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -1040,22 +6300,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.gkehub_v1.types.Membership", - "shortName": "get_membership" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_membership_binding" }, - "description": "Sample for GetMembership", - "file": "gkehub_v1_generated_gke_hub_get_membership_async.py", + "description": "Sample for UpdateMembershipBinding", + "file": "gkehub_v1_generated_gke_hub_update_membership_binding_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "gkehub_v1_generated_GkeHub_GetMembership_async", + "regionTag": "gkehub_v1_generated_GkeHub_UpdateMembershipBinding_async", "segments": [ { - "end": 51, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 58, "start": 27, "type": "SHORT" }, @@ -1065,22 +6325,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 55, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "gkehub_v1_generated_gke_hub_get_membership_async.py" + "title": "gkehub_v1_generated_gke_hub_update_membership_binding_async.py" }, { "canonical": true, @@ -1089,23 +6349,27 @@ "fullName": "google.cloud.gkehub_v1.GkeHubClient", "shortName": "GkeHubClient" }, - "fullName": "google.cloud.gkehub_v1.GkeHubClient.get_membership", + "fullName": "google.cloud.gkehub_v1.GkeHubClient.update_membership_binding", "method": { - "fullName": "google.cloud.gkehub.v1.GkeHub.GetMembership", + "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateMembershipBinding", "service": { "fullName": "google.cloud.gkehub.v1.GkeHub", "shortName": "GkeHub" }, - "shortName": "GetMembership" + "shortName": "UpdateMembershipBinding" }, "parameters": [ { "name": "request", - "type": "google.cloud.gkehub_v1.types.GetMembershipRequest" + "type": "google.cloud.gkehub_v1.types.UpdateMembershipBindingRequest" }, { - "name": "name", - "type": "str" + "name": "membership_binding", + "type": "google.cloud.gkehub_v1.types.MembershipBinding" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -1120,22 +6384,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.gkehub_v1.types.Membership", - "shortName": "get_membership" + "resultType": "google.api_core.operation.Operation", + "shortName": "update_membership_binding" }, - "description": "Sample for GetMembership", - "file": "gkehub_v1_generated_gke_hub_get_membership_sync.py", + "description": "Sample for UpdateMembershipBinding", + "file": "gkehub_v1_generated_gke_hub_update_membership_binding_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "gkehub_v1_generated_GkeHub_GetMembership_sync", + "regionTag": "gkehub_v1_generated_GkeHub_UpdateMembershipBinding_sync", "segments": [ { - "end": 51, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 58, "start": 27, "type": "SHORT" }, @@ -1145,22 +6409,191 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, + { + "end": 55, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_update_membership_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", + "shortName": "GkeHubAsyncClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.update_membership_rbac_role_binding", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateMembershipRBACRoleBinding", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "UpdateMembershipRBACRoleBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.UpdateMembershipRBACRoleBindingRequest" + }, + { + "name": "rbacrolebinding", + "type": "google.cloud.gkehub_v1.types.RBACRoleBinding" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_membership_rbac_role_binding" + }, + "description": "Sample for UpdateMembershipRBACRoleBinding", + "file": "gkehub_v1_generated_gke_hub_update_membership_rbac_role_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_UpdateMembershipRBACRoleBinding_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, { "end": 48, - "start": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "gkehub_v1_generated_gke_hub_update_membership_rbac_role_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.gkehub_v1.GkeHubClient", + "shortName": "GkeHubClient" + }, + "fullName": "google.cloud.gkehub_v1.GkeHubClient.update_membership_rbac_role_binding", + "method": { + "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateMembershipRBACRoleBinding", + "service": { + "fullName": "google.cloud.gkehub.v1.GkeHub", + "shortName": "GkeHub" + }, + "shortName": "UpdateMembershipRBACRoleBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.gkehub_v1.types.UpdateMembershipRBACRoleBindingRequest" + }, + { + "name": "rbacrolebinding", + "type": "google.cloud.gkehub_v1.types.RBACRoleBinding" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_membership_rbac_role_binding" + }, + "description": "Sample for UpdateMembershipRBACRoleBinding", + "file": "gkehub_v1_generated_gke_hub_update_membership_rbac_role_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "gkehub_v1_generated_GkeHub_UpdateMembershipRBACRoleBinding_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "gkehub_v1_generated_gke_hub_get_membership_sync.py" + "title": "gkehub_v1_generated_gke_hub_update_membership_rbac_role_binding_sync.py" }, { "canonical": true, @@ -1170,24 +6603,32 @@ "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", "shortName": "GkeHubAsyncClient" }, - "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.list_features", + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.update_membership", "method": { - "fullName": "google.cloud.gkehub.v1.GkeHub.ListFeatures", + "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateMembership", "service": { "fullName": "google.cloud.gkehub.v1.GkeHub", "shortName": "GkeHub" }, - "shortName": "ListFeatures" + "shortName": "UpdateMembership" }, "parameters": [ { "name": "request", - "type": "google.cloud.gkehub_v1.types.ListFeaturesRequest" + "type": "google.cloud.gkehub_v1.types.UpdateMembershipRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, + { + "name": "resource", + "type": "google.cloud.gkehub_v1.types.Membership" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1201,22 +6642,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListFeaturesAsyncPager", - "shortName": "list_features" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_membership" }, - "description": "Sample for ListFeatures", - "file": "gkehub_v1_generated_gke_hub_list_features_async.py", + "description": "Sample for UpdateMembership", + "file": "gkehub_v1_generated_gke_hub_update_membership_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "gkehub_v1_generated_GkeHub_ListFeatures_async", + "regionTag": "gkehub_v1_generated_GkeHub_UpdateMembership_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -1226,22 +6667,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 48, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "gkehub_v1_generated_gke_hub_list_features_async.py" + "title": "gkehub_v1_generated_gke_hub_update_membership_async.py" }, { "canonical": true, @@ -1250,24 +6691,32 @@ "fullName": "google.cloud.gkehub_v1.GkeHubClient", "shortName": "GkeHubClient" }, - "fullName": "google.cloud.gkehub_v1.GkeHubClient.list_features", + "fullName": "google.cloud.gkehub_v1.GkeHubClient.update_membership", "method": { - "fullName": "google.cloud.gkehub.v1.GkeHub.ListFeatures", + "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateMembership", "service": { "fullName": "google.cloud.gkehub.v1.GkeHub", "shortName": "GkeHub" }, - "shortName": "ListFeatures" + "shortName": "UpdateMembership" }, "parameters": [ { "name": "request", - "type": "google.cloud.gkehub_v1.types.ListFeaturesRequest" + "type": "google.cloud.gkehub_v1.types.UpdateMembershipRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, + { + "name": "resource", + "type": "google.cloud.gkehub_v1.types.Membership" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1281,22 +6730,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListFeaturesPager", - "shortName": "list_features" + "resultType": "google.api_core.operation.Operation", + "shortName": "update_membership" }, - "description": "Sample for ListFeatures", - "file": "gkehub_v1_generated_gke_hub_list_features_sync.py", + "description": "Sample for UpdateMembership", + "file": "gkehub_v1_generated_gke_hub_update_membership_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "gkehub_v1_generated_GkeHub_ListFeatures_sync", + "regionTag": "gkehub_v1_generated_GkeHub_UpdateMembership_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -1306,22 +6755,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 48, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "gkehub_v1_generated_gke_hub_list_features_sync.py" + "title": "gkehub_v1_generated_gke_hub_update_membership_sync.py" }, { "canonical": true, @@ -1331,23 +6780,27 @@ "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", "shortName": "GkeHubAsyncClient" }, - "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.list_memberships", + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.update_scope_namespace", "method": { - "fullName": "google.cloud.gkehub.v1.GkeHub.ListMemberships", + "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateScopeNamespace", "service": { "fullName": "google.cloud.gkehub.v1.GkeHub", "shortName": "GkeHub" }, - "shortName": "ListMemberships" + "shortName": "UpdateScopeNamespace" }, "parameters": [ { "name": "request", - "type": "google.cloud.gkehub_v1.types.ListMembershipsRequest" + "type": "google.cloud.gkehub_v1.types.UpdateScopeNamespaceRequest" }, { - "name": "parent", - "type": "str" + "name": "scope_namespace", + "type": "google.cloud.gkehub_v1.types.Namespace" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -1362,22 +6815,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListMembershipsAsyncPager", - "shortName": "list_memberships" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_scope_namespace" }, - "description": "Sample for ListMemberships", - "file": "gkehub_v1_generated_gke_hub_list_memberships_async.py", + "description": "Sample for UpdateScopeNamespace", + "file": "gkehub_v1_generated_gke_hub_update_scope_namespace_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "gkehub_v1_generated_GkeHub_ListMemberships_async", + "regionTag": "gkehub_v1_generated_GkeHub_UpdateScopeNamespace_async", "segments": [ { - "end": 52, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 58, "start": 27, "type": "SHORT" }, @@ -1387,22 +6840,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 55, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "gkehub_v1_generated_gke_hub_list_memberships_async.py" + "title": "gkehub_v1_generated_gke_hub_update_scope_namespace_async.py" }, { "canonical": true, @@ -1411,23 +6864,27 @@ "fullName": "google.cloud.gkehub_v1.GkeHubClient", "shortName": "GkeHubClient" }, - "fullName": "google.cloud.gkehub_v1.GkeHubClient.list_memberships", + "fullName": "google.cloud.gkehub_v1.GkeHubClient.update_scope_namespace", "method": { - "fullName": "google.cloud.gkehub.v1.GkeHub.ListMemberships", + "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateScopeNamespace", "service": { "fullName": "google.cloud.gkehub.v1.GkeHub", "shortName": "GkeHub" }, - "shortName": "ListMemberships" + "shortName": "UpdateScopeNamespace" }, "parameters": [ { "name": "request", - "type": "google.cloud.gkehub_v1.types.ListMembershipsRequest" + "type": "google.cloud.gkehub_v1.types.UpdateScopeNamespaceRequest" }, { - "name": "parent", - "type": "str" + "name": "scope_namespace", + "type": "google.cloud.gkehub_v1.types.Namespace" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -1442,22 +6899,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.gkehub_v1.services.gke_hub.pagers.ListMembershipsPager", - "shortName": "list_memberships" + "resultType": "google.api_core.operation.Operation", + "shortName": "update_scope_namespace" }, - "description": "Sample for ListMemberships", - "file": "gkehub_v1_generated_gke_hub_list_memberships_sync.py", + "description": "Sample for UpdateScopeNamespace", + "file": "gkehub_v1_generated_gke_hub_update_scope_namespace_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "gkehub_v1_generated_GkeHub_ListMemberships_sync", + "regionTag": "gkehub_v1_generated_GkeHub_UpdateScopeNamespace_sync", "segments": [ { - "end": 52, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 58, "start": 27, "type": "SHORT" }, @@ -1467,22 +6924,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 55, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "gkehub_v1_generated_gke_hub_list_memberships_sync.py" + "title": "gkehub_v1_generated_gke_hub_update_scope_namespace_sync.py" }, { "canonical": true, @@ -1492,27 +6949,23 @@ "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", "shortName": "GkeHubAsyncClient" }, - "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.update_feature", + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.update_scope_rbac_role_binding", "method": { - "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateFeature", + "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateScopeRBACRoleBinding", "service": { "fullName": "google.cloud.gkehub.v1.GkeHub", "shortName": "GkeHub" }, - "shortName": "UpdateFeature" + "shortName": "UpdateScopeRBACRoleBinding" }, "parameters": [ { "name": "request", - "type": "google.cloud.gkehub_v1.types.UpdateFeatureRequest" + "type": "google.cloud.gkehub_v1.types.UpdateScopeRBACRoleBindingRequest" }, { - "name": "name", - "type": "str" - }, - { - "name": "resource", - "type": "google.cloud.gkehub_v1.types.Feature" + "name": "rbacrolebinding", + "type": "google.cloud.gkehub_v1.types.RBACRoleBinding" }, { "name": "update_mask", @@ -1532,21 +6985,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_feature" + "shortName": "update_scope_rbac_role_binding" }, - "description": "Sample for UpdateFeature", - "file": "gkehub_v1_generated_gke_hub_update_feature_async.py", + "description": "Sample for UpdateScopeRBACRoleBinding", + "file": "gkehub_v1_generated_gke_hub_update_scope_rbac_role_binding_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "gkehub_v1_generated_GkeHub_UpdateFeature_async", + "regionTag": "gkehub_v1_generated_GkeHub_UpdateScopeRBACRoleBinding_async", "segments": [ { - "end": 54, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 58, "start": 27, "type": "SHORT" }, @@ -1556,22 +7009,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 45, + "end": 55, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "gkehub_v1_generated_gke_hub_update_feature_async.py" + "title": "gkehub_v1_generated_gke_hub_update_scope_rbac_role_binding_async.py" }, { "canonical": true, @@ -1580,27 +7033,23 @@ "fullName": "google.cloud.gkehub_v1.GkeHubClient", "shortName": "GkeHubClient" }, - "fullName": "google.cloud.gkehub_v1.GkeHubClient.update_feature", + "fullName": "google.cloud.gkehub_v1.GkeHubClient.update_scope_rbac_role_binding", "method": { - "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateFeature", + "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateScopeRBACRoleBinding", "service": { "fullName": "google.cloud.gkehub.v1.GkeHub", "shortName": "GkeHub" }, - "shortName": "UpdateFeature" + "shortName": "UpdateScopeRBACRoleBinding" }, "parameters": [ { "name": "request", - "type": "google.cloud.gkehub_v1.types.UpdateFeatureRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.gkehub_v1.types.UpdateScopeRBACRoleBindingRequest" }, { - "name": "resource", - "type": "google.cloud.gkehub_v1.types.Feature" + "name": "rbacrolebinding", + "type": "google.cloud.gkehub_v1.types.RBACRoleBinding" }, { "name": "update_mask", @@ -1620,21 +7069,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "update_feature" + "shortName": "update_scope_rbac_role_binding" }, - "description": "Sample for UpdateFeature", - "file": "gkehub_v1_generated_gke_hub_update_feature_sync.py", + "description": "Sample for UpdateScopeRBACRoleBinding", + "file": "gkehub_v1_generated_gke_hub_update_scope_rbac_role_binding_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "gkehub_v1_generated_GkeHub_UpdateFeature_sync", + "regionTag": "gkehub_v1_generated_GkeHub_UpdateScopeRBACRoleBinding_sync", "segments": [ { - "end": 54, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 58, "start": 27, "type": "SHORT" }, @@ -1644,22 +7093,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 45, + "end": 55, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "gkehub_v1_generated_gke_hub_update_feature_sync.py" + "title": "gkehub_v1_generated_gke_hub_update_scope_rbac_role_binding_sync.py" }, { "canonical": true, @@ -1669,27 +7118,23 @@ "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient", "shortName": "GkeHubAsyncClient" }, - "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.update_membership", + "fullName": "google.cloud.gkehub_v1.GkeHubAsyncClient.update_scope", "method": { - "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateMembership", + "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateScope", "service": { "fullName": "google.cloud.gkehub.v1.GkeHub", "shortName": "GkeHub" }, - "shortName": "UpdateMembership" + "shortName": "UpdateScope" }, "parameters": [ { "name": "request", - "type": "google.cloud.gkehub_v1.types.UpdateMembershipRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.gkehub_v1.types.UpdateScopeRequest" }, { - "name": "resource", - "type": "google.cloud.gkehub_v1.types.Membership" + "name": "scope", + "type": "google.cloud.gkehub_v1.types.Scope" }, { "name": "update_mask", @@ -1709,21 +7154,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_membership" + "shortName": "update_scope" }, - "description": "Sample for UpdateMembership", - "file": "gkehub_v1_generated_gke_hub_update_membership_async.py", + "description": "Sample for UpdateScope", + "file": "gkehub_v1_generated_gke_hub_update_scope_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "gkehub_v1_generated_GkeHub_UpdateMembership_async", + "regionTag": "gkehub_v1_generated_GkeHub_UpdateScope_async", "segments": [ { - "end": 55, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 54, "start": 27, "type": "SHORT" }, @@ -1733,22 +7178,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 51, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "gkehub_v1_generated_gke_hub_update_membership_async.py" + "title": "gkehub_v1_generated_gke_hub_update_scope_async.py" }, { "canonical": true, @@ -1757,27 +7202,23 @@ "fullName": "google.cloud.gkehub_v1.GkeHubClient", "shortName": "GkeHubClient" }, - "fullName": "google.cloud.gkehub_v1.GkeHubClient.update_membership", + "fullName": "google.cloud.gkehub_v1.GkeHubClient.update_scope", "method": { - "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateMembership", + "fullName": "google.cloud.gkehub.v1.GkeHub.UpdateScope", "service": { "fullName": "google.cloud.gkehub.v1.GkeHub", "shortName": "GkeHub" }, - "shortName": "UpdateMembership" + "shortName": "UpdateScope" }, "parameters": [ { "name": "request", - "type": "google.cloud.gkehub_v1.types.UpdateMembershipRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.gkehub_v1.types.UpdateScopeRequest" }, { - "name": "resource", - "type": "google.cloud.gkehub_v1.types.Membership" + "name": "scope", + "type": "google.cloud.gkehub_v1.types.Scope" }, { "name": "update_mask", @@ -1797,21 +7238,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "update_membership" + "shortName": "update_scope" }, - "description": "Sample for UpdateMembership", - "file": "gkehub_v1_generated_gke_hub_update_membership_sync.py", + "description": "Sample for UpdateScope", + "file": "gkehub_v1_generated_gke_hub_update_scope_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "gkehub_v1_generated_GkeHub_UpdateMembership_sync", + "regionTag": "gkehub_v1_generated_GkeHub_UpdateScope_sync", "segments": [ { - "end": 55, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 54, "start": 27, "type": "SHORT" }, @@ -1821,22 +7262,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 51, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "gkehub_v1_generated_gke_hub_update_membership_sync.py" + "title": "gkehub_v1_generated_gke_hub_update_scope_sync.py" } ] } diff --git a/packages/google-cloud-gke-hub/tests/unit/gapic/gkehub_v1/test_gke_hub.py b/packages/google-cloud-gke-hub/tests/unit/gapic/gkehub_v1/test_gke_hub.py index 6e50337581ba..b1f4672f78f9 100644 --- a/packages/google-cloud-gke-hub/tests/unit/gapic/gkehub_v1/test_gke_hub.py +++ b/packages/google-cloud-gke-hub/tests/unit/gapic/gkehub_v1/test_gke_hub.py @@ -71,7 +71,10 @@ pagers, transports, ) -from google.cloud.gkehub_v1.types import feature, membership, service +from google.cloud.gkehub_v1.types import feature +from google.cloud.gkehub_v1.types import fleet +from google.cloud.gkehub_v1.types import fleet as gcg_fleet +from google.cloud.gkehub_v1.types import membership, service CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -1783,11 +1786,11 @@ async def test_list_memberships_async_pages(): @pytest.mark.parametrize( "request_type", [ - service.ListFeaturesRequest, + service.ListBoundMembershipsRequest, dict, ], ) -def test_list_features(request_type, transport: str = "grpc"): +def test_list_bound_memberships(request_type, transport: str = "grpc"): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1798,25 +1801,29 @@ def test_list_features(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_features), "__call__") as call: + with mock.patch.object( + type(client.transport.list_bound_memberships), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.ListFeaturesResponse( + call.return_value = service.ListBoundMembershipsResponse( + unreachable=["unreachable_value"], next_page_token="next_page_token_value", ) - response = client.list_features(request) + response = client.list_bound_memberships(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.ListFeaturesRequest() + request = service.ListBoundMembershipsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFeaturesPager) + assert isinstance(response, pagers.ListBoundMembershipsPager) + assert response.unreachable == ["unreachable_value"] assert response.next_page_token == "next_page_token_value" -def test_list_features_non_empty_request_with_auto_populated_field(): +def test_list_bound_memberships_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = GkeHubClient( @@ -1827,30 +1834,30 @@ def test_list_features_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.ListFeaturesRequest( - parent="parent_value", - page_token="page_token_value", + request = service.ListBoundMembershipsRequest( + scope_name="scope_name_value", filter="filter_value", - order_by="order_by_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_features), "__call__") as call: + with mock.patch.object( + type(client.transport.list_bound_memberships), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_features(request=request) + client.list_bound_memberships(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.ListFeaturesRequest( - parent="parent_value", - page_token="page_token_value", + assert args[0] == service.ListBoundMembershipsRequest( + scope_name="scope_name_value", filter="filter_value", - order_by="order_by_value", + page_token="page_token_value", ) -def test_list_features_use_cached_wrapped_rpc(): +def test_list_bound_memberships_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -1864,21 +1871,26 @@ def test_list_features_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_features in client._transport._wrapped_methods + assert ( + client._transport.list_bound_memberships + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_features] = mock_rpc + client._transport._wrapped_methods[ + client._transport.list_bound_memberships + ] = mock_rpc request = {} - client.list_features(request) + client.list_bound_memberships(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_features(request) + client.list_bound_memberships(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -1886,7 +1898,7 @@ def test_list_features_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_features_async_use_cached_wrapped_rpc( +async def test_list_bound_memberships_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1903,7 +1915,7 @@ async def test_list_features_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_features + client._client._transport.list_bound_memberships in client._client._transport._wrapped_methods ) @@ -1911,16 +1923,16 @@ async def test_list_features_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_features + client._client._transport.list_bound_memberships ] = mock_rpc request = {} - await client.list_features(request) + await client.list_bound_memberships(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_features(request) + await client.list_bound_memberships(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -1928,8 +1940,8 @@ async def test_list_features_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_features_async( - transport: str = "grpc_asyncio", request_type=service.ListFeaturesRequest +async def test_list_bound_memberships_async( + transport: str = "grpc_asyncio", request_type=service.ListBoundMembershipsRequest ): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), @@ -1941,46 +1953,52 @@ async def test_list_features_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_features), "__call__") as call: + with mock.patch.object( + type(client.transport.list_bound_memberships), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListFeaturesResponse( + service.ListBoundMembershipsResponse( + unreachable=["unreachable_value"], next_page_token="next_page_token_value", ) ) - response = await client.list_features(request) + response = await client.list_bound_memberships(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.ListFeaturesRequest() + request = service.ListBoundMembershipsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFeaturesAsyncPager) + assert isinstance(response, pagers.ListBoundMembershipsAsyncPager) + assert response.unreachable == ["unreachable_value"] assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio -async def test_list_features_async_from_dict(): - await test_list_features_async(request_type=dict) +async def test_list_bound_memberships_async_from_dict(): + await test_list_bound_memberships_async(request_type=dict) -def test_list_features_field_headers(): +def test_list_bound_memberships_field_headers(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.ListFeaturesRequest() + request = service.ListBoundMembershipsRequest() - request.parent = "parent_value" + request.scope_name = "scope_name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_features), "__call__") as call: - call.return_value = service.ListFeaturesResponse() - client.list_features(request) + with mock.patch.object( + type(client.transport.list_bound_memberships), "__call__" + ) as call: + call.return_value = service.ListBoundMembershipsResponse() + client.list_bound_memberships(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -1991,28 +2009,30 @@ def test_list_features_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "scope_name=scope_name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_features_field_headers_async(): +async def test_list_bound_memberships_field_headers_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.ListFeaturesRequest() + request = service.ListBoundMembershipsRequest() - request.parent = "parent_value" + request.scope_name = "scope_name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_features), "__call__") as call: + with mock.patch.object( + type(client.transport.list_bound_memberships), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListFeaturesResponse() + service.ListBoundMembershipsResponse() ) - await client.list_features(request) + await client.list_bound_memberships(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -2023,35 +2043,37 @@ async def test_list_features_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "scope_name=scope_name_value", ) in kw["metadata"] -def test_list_features_flattened(): +def test_list_bound_memberships_flattened(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_features), "__call__") as call: + with mock.patch.object( + type(client.transport.list_bound_memberships), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.ListFeaturesResponse() + call.return_value = service.ListBoundMembershipsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_features( - parent="parent_value", + client.list_bound_memberships( + scope_name="scope_name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].scope_name + mock_val = "scope_name_value" assert arg == mock_val -def test_list_features_flattened_error(): +def test_list_bound_memberships_flattened_error(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -2059,43 +2081,45 @@ def test_list_features_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_features( - service.ListFeaturesRequest(), - parent="parent_value", + client.list_bound_memberships( + service.ListBoundMembershipsRequest(), + scope_name="scope_name_value", ) @pytest.mark.asyncio -async def test_list_features_flattened_async(): +async def test_list_bound_memberships_flattened_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_features), "__call__") as call: + with mock.patch.object( + type(client.transport.list_bound_memberships), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.ListFeaturesResponse() + call.return_value = service.ListBoundMembershipsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListFeaturesResponse() + service.ListBoundMembershipsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_features( - parent="parent_value", + response = await client.list_bound_memberships( + scope_name="scope_name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].scope_name + mock_val = "scope_name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_list_features_flattened_error_async(): +async def test_list_bound_memberships_flattened_error_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) @@ -2103,44 +2127,46 @@ async def test_list_features_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_features( - service.ListFeaturesRequest(), - parent="parent_value", + await client.list_bound_memberships( + service.ListBoundMembershipsRequest(), + scope_name="scope_name_value", ) -def test_list_features_pager(transport_name: str = "grpc"): +def test_list_bound_memberships_pager(transport_name: str = "grpc"): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_features), "__call__") as call: + with mock.patch.object( + type(client.transport.list_bound_memberships), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( - service.ListFeaturesResponse( - resources=[ - feature.Feature(), - feature.Feature(), - feature.Feature(), + service.ListBoundMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), ], next_page_token="abc", ), - service.ListFeaturesResponse( - resources=[], + service.ListBoundMembershipsResponse( + memberships=[], next_page_token="def", ), - service.ListFeaturesResponse( - resources=[ - feature.Feature(), + service.ListBoundMembershipsResponse( + memberships=[ + membership.Membership(), ], next_page_token="ghi", ), - service.ListFeaturesResponse( - resources=[ - feature.Feature(), - feature.Feature(), + service.ListBoundMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), ], ), RuntimeError, @@ -2150,9 +2176,9 @@ def test_list_features_pager(transport_name: str = "grpc"): retry = retries.Retry() timeout = 5 expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + gapic_v1.routing_header.to_grpc_metadata((("scope_name", ""),)), ) - pager = client.list_features(request={}, retry=retry, timeout=timeout) + pager = client.list_bound_memberships(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -2160,89 +2186,93 @@ def test_list_features_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, feature.Feature) for i in results) + assert all(isinstance(i, membership.Membership) for i in results) -def test_list_features_pages(transport_name: str = "grpc"): +def test_list_bound_memberships_pages(transport_name: str = "grpc"): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_features), "__call__") as call: + with mock.patch.object( + type(client.transport.list_bound_memberships), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( - service.ListFeaturesResponse( - resources=[ - feature.Feature(), - feature.Feature(), - feature.Feature(), + service.ListBoundMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), ], next_page_token="abc", ), - service.ListFeaturesResponse( - resources=[], + service.ListBoundMembershipsResponse( + memberships=[], next_page_token="def", ), - service.ListFeaturesResponse( - resources=[ - feature.Feature(), + service.ListBoundMembershipsResponse( + memberships=[ + membership.Membership(), ], next_page_token="ghi", ), - service.ListFeaturesResponse( - resources=[ - feature.Feature(), - feature.Feature(), + service.ListBoundMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), ], ), RuntimeError, ) - pages = list(client.list_features(request={}).pages) + pages = list(client.list_bound_memberships(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_features_async_pager(): +async def test_list_bound_memberships_async_pager(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_features), "__call__", new_callable=mock.AsyncMock + type(client.transport.list_bound_memberships), + "__call__", + new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - service.ListFeaturesResponse( - resources=[ - feature.Feature(), - feature.Feature(), - feature.Feature(), + service.ListBoundMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), ], next_page_token="abc", ), - service.ListFeaturesResponse( - resources=[], + service.ListBoundMembershipsResponse( + memberships=[], next_page_token="def", ), - service.ListFeaturesResponse( - resources=[ - feature.Feature(), + service.ListBoundMembershipsResponse( + memberships=[ + membership.Membership(), ], next_page_token="ghi", ), - service.ListFeaturesResponse( - resources=[ - feature.Feature(), - feature.Feature(), + service.ListBoundMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), ], ), RuntimeError, ) - async_pager = await client.list_features( + async_pager = await client.list_bound_memberships( request={}, ) assert async_pager.next_page_token == "abc" @@ -2251,43 +2281,45 @@ async def test_list_features_async_pager(): responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, feature.Feature) for i in responses) + assert all(isinstance(i, membership.Membership) for i in responses) @pytest.mark.asyncio -async def test_list_features_async_pages(): +async def test_list_bound_memberships_async_pages(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_features), "__call__", new_callable=mock.AsyncMock + type(client.transport.list_bound_memberships), + "__call__", + new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - service.ListFeaturesResponse( - resources=[ - feature.Feature(), - feature.Feature(), - feature.Feature(), + service.ListBoundMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), ], next_page_token="abc", ), - service.ListFeaturesResponse( - resources=[], + service.ListBoundMembershipsResponse( + memberships=[], next_page_token="def", ), - service.ListFeaturesResponse( - resources=[ - feature.Feature(), + service.ListBoundMembershipsResponse( + memberships=[ + membership.Membership(), ], next_page_token="ghi", ), - service.ListFeaturesResponse( - resources=[ - feature.Feature(), - feature.Feature(), + service.ListBoundMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), ], ), RuntimeError, @@ -2296,7 +2328,7 @@ async def test_list_features_async_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_features(request={}) + await client.list_bound_memberships(request={}) ).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): @@ -2306,11 +2338,11 @@ async def test_list_features_async_pages(): @pytest.mark.parametrize( "request_type", [ - service.GetMembershipRequest, + service.ListFeaturesRequest, dict, ], ) -def test_get_membership(request_type, transport: str = "grpc"): +def test_list_features(request_type, transport: str = "grpc"): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2321,31 +2353,25 @@ def test_get_membership(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_membership), "__call__") as call: + with mock.patch.object(type(client.transport.list_features), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = membership.Membership( - name="name_value", - description="description_value", - external_id="external_id_value", - unique_id="unique_id_value", + call.return_value = service.ListFeaturesResponse( + next_page_token="next_page_token_value", ) - response = client.get_membership(request) + response = client.list_features(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.GetMembershipRequest() + request = service.ListFeaturesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, membership.Membership) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.external_id == "external_id_value" - assert response.unique_id == "unique_id_value" + assert isinstance(response, pagers.ListFeaturesPager) + assert response.next_page_token == "next_page_token_value" -def test_get_membership_non_empty_request_with_auto_populated_field(): +def test_list_features_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = GkeHubClient( @@ -2356,24 +2382,30 @@ def test_get_membership_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.GetMembershipRequest( - name="name_value", + request = service.ListFeaturesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_membership), "__call__") as call: + with mock.patch.object(type(client.transport.list_features), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_membership(request=request) + client.list_features(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.GetMembershipRequest( - name="name_value", + assert args[0] == service.ListFeaturesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) -def test_get_membership_use_cached_wrapped_rpc(): +def test_list_features_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -2387,21 +2419,21 @@ def test_get_membership_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_membership in client._transport._wrapped_methods + assert client._transport.list_features in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_membership] = mock_rpc + client._transport._wrapped_methods[client._transport.list_features] = mock_rpc request = {} - client.get_membership(request) + client.list_features(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_membership(request) + client.list_features(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -2409,7 +2441,7 @@ def test_get_membership_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_membership_async_use_cached_wrapped_rpc( +async def test_list_features_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -2426,7 +2458,7 @@ async def test_get_membership_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_membership + client._client._transport.list_features in client._client._transport._wrapped_methods ) @@ -2434,16 +2466,16 @@ async def test_get_membership_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_membership + client._client._transport.list_features ] = mock_rpc request = {} - await client.get_membership(request) + await client.list_features(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_membership(request) + await client.list_features(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -2451,8 +2483,8 @@ async def test_get_membership_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_membership_async( - transport: str = "grpc_asyncio", request_type=service.GetMembershipRequest +async def test_list_features_async( + transport: str = "grpc_asyncio", request_type=service.ListFeaturesRequest ): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), @@ -2464,52 +2496,46 @@ async def test_get_membership_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_membership), "__call__") as call: + with mock.patch.object(type(client.transport.list_features), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - membership.Membership( - name="name_value", - description="description_value", - external_id="external_id_value", - unique_id="unique_id_value", + service.ListFeaturesResponse( + next_page_token="next_page_token_value", ) ) - response = await client.get_membership(request) + response = await client.list_features(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.GetMembershipRequest() + request = service.ListFeaturesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, membership.Membership) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.external_id == "external_id_value" - assert response.unique_id == "unique_id_value" + assert isinstance(response, pagers.ListFeaturesAsyncPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio -async def test_get_membership_async_from_dict(): - await test_get_membership_async(request_type=dict) +async def test_list_features_async_from_dict(): + await test_list_features_async(request_type=dict) -def test_get_membership_field_headers(): +def test_list_features_field_headers(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.GetMembershipRequest() + request = service.ListFeaturesRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_membership), "__call__") as call: - call.return_value = membership.Membership() - client.get_membership(request) + with mock.patch.object(type(client.transport.list_features), "__call__") as call: + call.return_value = service.ListFeaturesResponse() + client.list_features(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -2520,28 +2546,28 @@ def test_get_membership_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_membership_field_headers_async(): +async def test_list_features_field_headers_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.GetMembershipRequest() + request = service.ListFeaturesRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_membership), "__call__") as call: + with mock.patch.object(type(client.transport.list_features), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - membership.Membership() + service.ListFeaturesResponse() ) - await client.get_membership(request) + await client.list_features(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -2552,35 +2578,35 @@ async def test_get_membership_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_get_membership_flattened(): +def test_list_features_flattened(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_membership), "__call__") as call: + with mock.patch.object(type(client.transport.list_features), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = membership.Membership() + call.return_value = service.ListFeaturesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_membership( - name="name_value", + client.list_features( + 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].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_get_membership_flattened_error(): +def test_list_features_flattened_error(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -2588,43 +2614,43 @@ def test_get_membership_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_membership( - service.GetMembershipRequest(), - name="name_value", + client.list_features( + service.ListFeaturesRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_get_membership_flattened_async(): +async def test_list_features_flattened_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_membership), "__call__") as call: + with mock.patch.object(type(client.transport.list_features), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = membership.Membership() + call.return_value = service.ListFeaturesResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - membership.Membership() + service.ListFeaturesResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_membership( - name="name_value", + response = await client.list_features( + 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].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_get_membership_flattened_error_async(): +async def test_list_features_flattened_error_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) @@ -2632,105 +2658,305 @@ async def test_get_membership_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_membership( - service.GetMembershipRequest(), - name="name_value", + await client.list_features( + service.ListFeaturesRequest(), + parent="parent_value", ) -@pytest.mark.parametrize( - "request_type", - [ - service.GetFeatureRequest, - dict, - ], -) -def test_get_feature(request_type, transport: str = "grpc"): +def test_list_features_pager(transport_name: str = "grpc"): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_feature), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = feature.Feature( - name="name_value", + with mock.patch.object(type(client.transport.list_features), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + feature.Feature(), + ], + next_page_token="abc", + ), + service.ListFeaturesResponse( + resources=[], + next_page_token="def", + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + ], + next_page_token="ghi", + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + ], + ), + RuntimeError, ) - response = client.get_feature(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.GetFeatureRequest() - assert args[0] == request + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_features(request={}, retry=retry, timeout=timeout) - # Establish that the response is the type that we expect. - assert isinstance(response, feature.Feature) - assert response.name == "name_value" + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, feature.Feature) for i in results) -def test_get_feature_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. + +def test_list_features_pages(transport_name: str = "grpc"): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.GetFeatureRequest( - name="name_value", + transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_feature), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_feature(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetFeatureRequest( - name="name_value", - ) - - -def test_get_feature_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + with mock.patch.object(type(client.transport.list_features), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + feature.Feature(), + ], + next_page_token="abc", + ), + service.ListFeaturesResponse( + resources=[], + next_page_token="def", + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + ], + next_page_token="ghi", + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + ], + ), + RuntimeError, ) + pages = list(client.list_features(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - # Ensure method has been cached - assert client._transport.get_feature in client._transport._wrapped_methods +@pytest.mark.asyncio +async def test_list_features_async_pager(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_features), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + feature.Feature(), + ], + next_page_token="abc", + ), + service.ListFeaturesResponse( + resources=[], + next_page_token="def", + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + ], + next_page_token="ghi", + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_features( + 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, feature.Feature) for i in responses) + + +@pytest.mark.asyncio +async def test_list_features_async_pages(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_features), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + feature.Feature(), + ], + next_page_token="abc", + ), + service.ListFeaturesResponse( + resources=[], + next_page_token="def", + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + ], + next_page_token="ghi", + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + ], + ), + 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_features(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", + [ + service.GetMembershipRequest, + dict, + ], +) +def test_get_membership(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_membership), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = membership.Membership( + name="name_value", + description="description_value", + external_id="external_id_value", + unique_id="unique_id_value", + ) + response = client.get_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GetMembershipRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.external_id == "external_id_value" + assert response.unique_id == "unique_id_value" + + +def test_get_membership_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GetMembershipRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_membership), "__call__") as call: + call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_feature] = mock_rpc + client.get_membership(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetMembershipRequest( + name="name_value", + ) + + +def test_get_membership_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_membership in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_membership] = mock_rpc request = {} - client.get_feature(request) + client.get_membership(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_feature(request) + client.get_membership(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -2738,7 +2964,7 @@ def test_get_feature_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_feature_async_use_cached_wrapped_rpc( +async def test_get_membership_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -2755,7 +2981,7 @@ async def test_get_feature_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_feature + client._client._transport.get_membership in client._client._transport._wrapped_methods ) @@ -2763,16 +2989,16 @@ async def test_get_feature_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_feature + client._client._transport.get_membership ] = mock_rpc request = {} - await client.get_feature(request) + await client.get_membership(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_feature(request) + await client.get_membership(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -2780,8 +3006,8 @@ async def test_get_feature_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_feature_async( - transport: str = "grpc_asyncio", request_type=service.GetFeatureRequest +async def test_get_membership_async( + transport: str = "grpc_asyncio", request_type=service.GetMembershipRequest ): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), @@ -2793,46 +3019,52 @@ async def test_get_feature_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_feature), "__call__") as call: + with mock.patch.object(type(client.transport.get_membership), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - feature.Feature( + membership.Membership( name="name_value", + description="description_value", + external_id="external_id_value", + unique_id="unique_id_value", ) ) - response = await client.get_feature(request) + response = await client.get_membership(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.GetFeatureRequest() + request = service.GetMembershipRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, feature.Feature) + assert isinstance(response, membership.Membership) assert response.name == "name_value" + assert response.description == "description_value" + assert response.external_id == "external_id_value" + assert response.unique_id == "unique_id_value" @pytest.mark.asyncio -async def test_get_feature_async_from_dict(): - await test_get_feature_async(request_type=dict) +async def test_get_membership_async_from_dict(): + await test_get_membership_async(request_type=dict) -def test_get_feature_field_headers(): +def test_get_membership_field_headers(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.GetFeatureRequest() + request = service.GetMembershipRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_feature), "__call__") as call: - call.return_value = feature.Feature() - client.get_feature(request) + with mock.patch.object(type(client.transport.get_membership), "__call__") as call: + call.return_value = membership.Membership() + client.get_membership(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -2848,21 +3080,23 @@ def test_get_feature_field_headers(): @pytest.mark.asyncio -async def test_get_feature_field_headers_async(): +async def test_get_membership_field_headers_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.GetFeatureRequest() + request = service.GetMembershipRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_feature), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(feature.Feature()) - await client.get_feature(request) + with mock.patch.object(type(client.transport.get_membership), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + membership.Membership() + ) + await client.get_membership(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -2877,18 +3111,18 @@ async def test_get_feature_field_headers_async(): ) in kw["metadata"] -def test_get_feature_flattened(): +def test_get_membership_flattened(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_feature), "__call__") as call: + with mock.patch.object(type(client.transport.get_membership), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = feature.Feature() + call.return_value = membership.Membership() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_feature( + client.get_membership( name="name_value", ) @@ -2901,7 +3135,7 @@ def test_get_feature_flattened(): assert arg == mock_val -def test_get_feature_flattened_error(): +def test_get_membership_flattened_error(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -2909,27 +3143,29 @@ def test_get_feature_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_feature( - service.GetFeatureRequest(), + client.get_membership( + service.GetMembershipRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_feature_flattened_async(): +async def test_get_membership_flattened_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_feature), "__call__") as call: + with mock.patch.object(type(client.transport.get_membership), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = feature.Feature() + call.return_value = membership.Membership() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(feature.Feature()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + membership.Membership() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_feature( + response = await client.get_membership( name="name_value", ) @@ -2943,7 +3179,7 @@ async def test_get_feature_flattened_async(): @pytest.mark.asyncio -async def test_get_feature_flattened_error_async(): +async def test_get_membership_flattened_error_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) @@ -2951,8 +3187,8 @@ async def test_get_feature_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_feature( - service.GetFeatureRequest(), + await client.get_membership( + service.GetMembershipRequest(), name="name_value", ) @@ -2960,11 +3196,11 @@ async def test_get_feature_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - service.CreateMembershipRequest, + service.GetFeatureRequest, dict, ], ) -def test_create_membership(request_type, transport: str = "grpc"): +def test_get_feature(request_type, transport: str = "grpc"): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2975,24 +3211,27 @@ def test_create_membership(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_membership), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_feature), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_membership(request) + call.return_value = feature.Feature( + name="name_value", + unreachable=["unreachable_value"], + ) + response = client.get_feature(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.CreateMembershipRequest() + request = service.GetFeatureRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, feature.Feature) + assert response.name == "name_value" + assert response.unreachable == ["unreachable_value"] -def test_create_membership_non_empty_request_with_auto_populated_field(): +def test_get_feature_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = GkeHubClient( @@ -3003,30 +3242,24 @@ def test_create_membership_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.CreateMembershipRequest( - parent="parent_value", - membership_id="membership_id_value", - request_id="request_id_value", + request = service.GetFeatureRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_membership), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_feature), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_membership(request=request) + client.get_feature(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateMembershipRequest( - parent="parent_value", - membership_id="membership_id_value", - request_id="request_id_value", + assert args[0] == service.GetFeatureRequest( + name="name_value", ) -def test_create_membership_use_cached_wrapped_rpc(): +def test_get_feature_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -3040,28 +3273,21 @@ def test_create_membership_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_membership in client._transport._wrapped_methods + assert client._transport.get_feature in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.create_membership - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_feature] = mock_rpc request = {} - client.create_membership(request) + client.get_feature(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_membership(request) + client.get_feature(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3069,7 +3295,7 @@ def test_create_membership_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_membership_async_use_cached_wrapped_rpc( +async def test_get_feature_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -3086,7 +3312,7 @@ async def test_create_membership_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_membership + client._client._transport.get_feature in client._client._transport._wrapped_methods ) @@ -3094,21 +3320,16 @@ async def test_create_membership_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_membership + client._client._transport.get_feature ] = mock_rpc request = {} - await client.create_membership(request) + await client.get_feature(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_membership(request) + await client.get_feature(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3116,8 +3337,8 @@ async def test_create_membership_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_membership_async( - transport: str = "grpc_asyncio", request_type=service.CreateMembershipRequest +async def test_get_feature_async( + transport: str = "grpc_asyncio", request_type=service.GetFeatureRequest ): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), @@ -3129,47 +3350,48 @@ async def test_create_membership_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_membership), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_feature), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + feature.Feature( + name="name_value", + unreachable=["unreachable_value"], + ) ) - response = await client.create_membership(request) + response = await client.get_feature(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.CreateMembershipRequest() + request = service.GetFeatureRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, feature.Feature) + assert response.name == "name_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.asyncio -async def test_create_membership_async_from_dict(): - await test_create_membership_async(request_type=dict) +async def test_get_feature_async_from_dict(): + await test_get_feature_async(request_type=dict) -def test_create_membership_field_headers(): +def test_get_feature_field_headers(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.CreateMembershipRequest() + request = service.GetFeatureRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_membership), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_membership(request) + with mock.patch.object(type(client.transport.get_feature), "__call__") as call: + call.return_value = feature.Feature() + client.get_feature(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3180,30 +3402,26 @@ def test_create_membership_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_membership_field_headers_async(): +async def test_get_feature_field_headers_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.CreateMembershipRequest() + request = service.GetFeatureRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_membership), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") - ) - await client.create_membership(request) + with mock.patch.object(type(client.transport.get_feature), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(feature.Feature()) + await client.get_feature(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -3214,55 +3432,35 @@ async def test_create_membership_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_create_membership_flattened(): +def test_get_feature_flattened(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_membership), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_feature), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = feature.Feature() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_membership( - parent="parent_value", - resource=membership.Membership( - endpoint=membership.MembershipEndpoint( - gke_cluster=membership.GkeCluster( - resource_link="resource_link_value" - ) - ) - ), - membership_id="membership_id_value", + client.get_feature( + name="name_value", ) # Establish that the underlying call was made with the expected # request object 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].resource - mock_val = membership.Membership( - endpoint=membership.MembershipEndpoint( - gke_cluster=membership.GkeCluster(resource_link="resource_link_value") - ) - ) - assert arg == mock_val - arg = args[0].membership_id - mock_val = "membership_id_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_create_membership_flattened_error(): +def test_get_feature_flattened_error(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -3270,71 +3468,41 @@ def test_create_membership_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_membership( - service.CreateMembershipRequest(), - parent="parent_value", - resource=membership.Membership( - endpoint=membership.MembershipEndpoint( - gke_cluster=membership.GkeCluster( - resource_link="resource_link_value" - ) - ) - ), - membership_id="membership_id_value", + client.get_feature( + service.GetFeatureRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_create_membership_flattened_async(): +async def test_get_feature_flattened_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_membership), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_feature), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = feature.Feature() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(feature.Feature()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_membership( - parent="parent_value", - resource=membership.Membership( - endpoint=membership.MembershipEndpoint( - gke_cluster=membership.GkeCluster( - resource_link="resource_link_value" - ) - ) - ), - membership_id="membership_id_value", + response = await client.get_feature( + name="name_value", ) # Establish that the underlying call was made with the expected # request 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].resource - mock_val = membership.Membership( - endpoint=membership.MembershipEndpoint( - gke_cluster=membership.GkeCluster(resource_link="resource_link_value") - ) - ) - assert arg == mock_val - arg = args[0].membership_id - mock_val = "membership_id_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_create_membership_flattened_error_async(): +async def test_get_feature_flattened_error_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) @@ -3342,28 +3510,20 @@ async def test_create_membership_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_membership( - service.CreateMembershipRequest(), - parent="parent_value", - resource=membership.Membership( - endpoint=membership.MembershipEndpoint( - gke_cluster=membership.GkeCluster( - resource_link="resource_link_value" - ) - ) - ), - membership_id="membership_id_value", + await client.get_feature( + service.GetFeatureRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - service.CreateFeatureRequest, + service.CreateMembershipRequest, dict, ], ) -def test_create_feature(request_type, transport: str = "grpc"): +def test_create_membership(request_type, transport: str = "grpc"): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3374,22 +3534,24 @@ def test_create_feature(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.create_membership), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_feature(request) + response = client.create_membership(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.CreateFeatureRequest() + request = service.CreateMembershipRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_create_feature_non_empty_request_with_auto_populated_field(): +def test_create_membership_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = GkeHubClient( @@ -3400,28 +3562,30 @@ def test_create_feature_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.CreateFeatureRequest( + request = service.CreateMembershipRequest( parent="parent_value", - feature_id="feature_id_value", + membership_id="membership_id_value", request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.create_membership), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_feature(request=request) + client.create_membership(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateFeatureRequest( + assert args[0] == service.CreateMembershipRequest( parent="parent_value", - feature_id="feature_id_value", + membership_id="membership_id_value", request_id="request_id_value", ) -def test_create_feature_use_cached_wrapped_rpc(): +def test_create_membership_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -3435,16 +3599,18 @@ def test_create_feature_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_feature in client._transport._wrapped_methods + assert client._transport.create_membership in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_feature] = mock_rpc + client._transport._wrapped_methods[ + client._transport.create_membership + ] = mock_rpc request = {} - client.create_feature(request) + client.create_membership(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -3454,7 +3620,7 @@ def test_create_feature_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_feature(request) + client.create_membership(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3462,7 +3628,7 @@ def test_create_feature_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_feature_async_use_cached_wrapped_rpc( +async def test_create_membership_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -3479,7 +3645,7 @@ async def test_create_feature_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_feature + client._client._transport.create_membership in client._client._transport._wrapped_methods ) @@ -3487,11 +3653,11 @@ async def test_create_feature_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_feature + client._client._transport.create_membership ] = mock_rpc request = {} - await client.create_feature(request) + await client.create_membership(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -3501,7 +3667,7 @@ async def test_create_feature_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.create_feature(request) + await client.create_membership(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3509,8 +3675,8 @@ async def test_create_feature_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_feature_async( - transport: str = "grpc_asyncio", request_type=service.CreateFeatureRequest +async def test_create_membership_async( + transport: str = "grpc_asyncio", request_type=service.CreateMembershipRequest ): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), @@ -3522,17 +3688,19 @@ async def test_create_feature_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.create_membership), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_feature(request) + response = await client.create_membership(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.CreateFeatureRequest() + request = service.CreateMembershipRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -3540,25 +3708,27 @@ async def test_create_feature_async( @pytest.mark.asyncio -async def test_create_feature_async_from_dict(): - await test_create_feature_async(request_type=dict) +async def test_create_membership_async_from_dict(): + await test_create_membership_async(request_type=dict) -def test_create_feature_field_headers(): +def test_create_membership_field_headers(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.CreateFeatureRequest() + request = service.CreateMembershipRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.create_membership), "__call__" + ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_feature(request) + client.create_membership(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3574,23 +3744,25 @@ def test_create_feature_field_headers(): @pytest.mark.asyncio -async def test_create_feature_field_headers_async(): +async def test_create_membership_field_headers_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.CreateFeatureRequest() + request = service.CreateMembershipRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.create_membership), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_feature(request) + await client.create_membership(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -3605,21 +3777,29 @@ async def test_create_feature_field_headers_async(): ) in kw["metadata"] -def test_create_feature_flattened(): +def test_create_membership_flattened(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.create_membership), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_feature( + client.create_membership( parent="parent_value", - resource=feature.Feature(name="name_value"), - feature_id="feature_id_value", + resource=membership.Membership( + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster( + resource_link="resource_link_value" + ) + ) + ), + membership_id="membership_id_value", ) # Establish that the underlying call was made with the expected @@ -3630,14 +3810,18 @@ def test_create_feature_flattened(): mock_val = "parent_value" assert arg == mock_val arg = args[0].resource - mock_val = feature.Feature(name="name_value") + mock_val = membership.Membership( + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster(resource_link="resource_link_value") + ) + ) assert arg == mock_val - arg = args[0].feature_id - mock_val = "feature_id_value" + arg = args[0].membership_id + mock_val = "membership_id_value" assert arg == mock_val -def test_create_feature_flattened_error(): +def test_create_membership_flattened_error(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -3645,22 +3829,30 @@ def test_create_feature_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_feature( - service.CreateFeatureRequest(), + client.create_membership( + service.CreateMembershipRequest(), parent="parent_value", - resource=feature.Feature(name="name_value"), - feature_id="feature_id_value", + resource=membership.Membership( + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster( + resource_link="resource_link_value" + ) + ) + ), + membership_id="membership_id_value", ) @pytest.mark.asyncio -async def test_create_feature_flattened_async(): +async def test_create_membership_flattened_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.create_membership), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -3669,10 +3861,16 @@ async def test_create_feature_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_feature( + response = await client.create_membership( parent="parent_value", - resource=feature.Feature(name="name_value"), - feature_id="feature_id_value", + resource=membership.Membership( + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster( + resource_link="resource_link_value" + ) + ) + ), + membership_id="membership_id_value", ) # Establish that the underlying call was made with the expected @@ -3683,15 +3881,19 @@ async def test_create_feature_flattened_async(): mock_val = "parent_value" assert arg == mock_val arg = args[0].resource - mock_val = feature.Feature(name="name_value") + mock_val = membership.Membership( + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster(resource_link="resource_link_value") + ) + ) assert arg == mock_val - arg = args[0].feature_id - mock_val = "feature_id_value" + arg = args[0].membership_id + mock_val = "membership_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_create_feature_flattened_error_async(): +async def test_create_membership_flattened_error_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) @@ -3699,22 +3901,28 @@ async def test_create_feature_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_feature( - service.CreateFeatureRequest(), + await client.create_membership( + service.CreateMembershipRequest(), parent="parent_value", - resource=feature.Feature(name="name_value"), - feature_id="feature_id_value", + resource=membership.Membership( + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster( + resource_link="resource_link_value" + ) + ) + ), + membership_id="membership_id_value", ) @pytest.mark.parametrize( "request_type", [ - service.DeleteMembershipRequest, + service.CreateFeatureRequest, dict, ], ) -def test_delete_membership(request_type, transport: str = "grpc"): +def test_create_feature(request_type, transport: str = "grpc"): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3725,24 +3933,22 @@ def test_delete_membership(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_membership), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_feature), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_membership(request) + response = client.create_feature(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.DeleteMembershipRequest() + request = service.CreateFeatureRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_delete_membership_non_empty_request_with_auto_populated_field(): +def test_create_feature_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = GkeHubClient( @@ -3753,28 +3959,28 @@ def test_delete_membership_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.DeleteMembershipRequest( - name="name_value", + request = service.CreateFeatureRequest( + parent="parent_value", + feature_id="feature_id_value", request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_membership), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_feature), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_membership(request=request) + client.create_feature(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteMembershipRequest( - name="name_value", + assert args[0] == service.CreateFeatureRequest( + parent="parent_value", + feature_id="feature_id_value", request_id="request_id_value", ) -def test_delete_membership_use_cached_wrapped_rpc(): +def test_create_feature_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -3788,18 +3994,16 @@ def test_delete_membership_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_membership in client._transport._wrapped_methods + assert client._transport.create_feature in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.delete_membership - ] = mock_rpc + client._transport._wrapped_methods[client._transport.create_feature] = mock_rpc request = {} - client.delete_membership(request) + client.create_feature(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -3809,7 +4013,7 @@ def test_delete_membership_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_membership(request) + client.create_feature(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3817,7 +4021,7 @@ def test_delete_membership_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_membership_async_use_cached_wrapped_rpc( +async def test_create_feature_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -3834,7 +4038,7 @@ async def test_delete_membership_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_membership + client._client._transport.create_feature in client._client._transport._wrapped_methods ) @@ -3842,11 +4046,11 @@ async def test_delete_membership_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_membership + client._client._transport.create_feature ] = mock_rpc request = {} - await client.delete_membership(request) + await client.create_feature(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -3856,7 +4060,7 @@ async def test_delete_membership_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.delete_membership(request) + await client.create_feature(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3864,8 +4068,8 @@ async def test_delete_membership_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_membership_async( - transport: str = "grpc_asyncio", request_type=service.DeleteMembershipRequest +async def test_create_feature_async( + transport: str = "grpc_asyncio", request_type=service.CreateFeatureRequest ): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), @@ -3877,19 +4081,17 @@ async def test_delete_membership_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_membership), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_feature), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.delete_membership(request) + response = await client.create_feature(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.DeleteMembershipRequest() + request = service.CreateFeatureRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -3897,27 +4099,25 @@ async def test_delete_membership_async( @pytest.mark.asyncio -async def test_delete_membership_async_from_dict(): - await test_delete_membership_async(request_type=dict) +async def test_create_feature_async_from_dict(): + await test_create_feature_async(request_type=dict) -def test_delete_membership_field_headers(): +def test_create_feature_field_headers(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.DeleteMembershipRequest() + request = service.CreateFeatureRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_membership), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_feature), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_membership(request) + client.create_feature(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3928,30 +4128,28 @@ def test_delete_membership_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_delete_membership_field_headers_async(): +async def test_create_feature_field_headers_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.DeleteMembershipRequest() + request = service.CreateFeatureRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_membership), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_feature), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.delete_membership(request) + await client.create_feature(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -3962,37 +4160,43 @@ async def test_delete_membership_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_delete_membership_flattened(): +def test_create_feature_flattened(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_membership), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_feature), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_membership( - name="name_value", + client.create_feature( + parent="parent_value", + resource=feature.Feature(name="name_value"), + feature_id="feature_id_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].resource + mock_val = feature.Feature(name="name_value") + assert arg == mock_val + arg = args[0].feature_id + mock_val = "feature_id_value" assert arg == mock_val -def test_delete_membership_flattened_error(): +def test_create_feature_flattened_error(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -4000,22 +4204,22 @@ def test_delete_membership_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_membership( - service.DeleteMembershipRequest(), - name="name_value", + client.create_feature( + service.CreateFeatureRequest(), + parent="parent_value", + resource=feature.Feature(name="name_value"), + feature_id="feature_id_value", ) @pytest.mark.asyncio -async def test_delete_membership_flattened_async(): +async def test_create_feature_flattened_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_membership), "__call__" - ) as call: + with mock.patch.object(type(client.transport.create_feature), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -4024,21 +4228,29 @@ async def test_delete_membership_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_membership( - name="name_value", + response = await client.create_feature( + parent="parent_value", + resource=feature.Feature(name="name_value"), + feature_id="feature_id_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].resource + mock_val = feature.Feature(name="name_value") + assert arg == mock_val + arg = args[0].feature_id + mock_val = "feature_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_delete_membership_flattened_error_async(): +async def test_create_feature_flattened_error_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) @@ -4046,20 +4258,22 @@ async def test_delete_membership_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_membership( - service.DeleteMembershipRequest(), - name="name_value", + await client.create_feature( + service.CreateFeatureRequest(), + parent="parent_value", + resource=feature.Feature(name="name_value"), + feature_id="feature_id_value", ) @pytest.mark.parametrize( "request_type", [ - service.DeleteFeatureRequest, + service.DeleteMembershipRequest, dict, ], ) -def test_delete_feature(request_type, transport: str = "grpc"): +def test_delete_membership(request_type, transport: str = "grpc"): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4070,22 +4284,24 @@ def test_delete_feature(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_membership), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_feature(request) + response = client.delete_membership(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.DeleteFeatureRequest() + request = service.DeleteMembershipRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_delete_feature_non_empty_request_with_auto_populated_field(): +def test_delete_membership_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = GkeHubClient( @@ -4096,26 +4312,28 @@ def test_delete_feature_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.DeleteFeatureRequest( + request = service.DeleteMembershipRequest( name="name_value", request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_membership), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_feature(request=request) + client.delete_membership(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteFeatureRequest( + assert args[0] == service.DeleteMembershipRequest( name="name_value", request_id="request_id_value", ) -def test_delete_feature_use_cached_wrapped_rpc(): +def test_delete_membership_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -4129,16 +4347,18 @@ def test_delete_feature_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_feature in client._transport._wrapped_methods + assert client._transport.delete_membership in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_feature] = mock_rpc + client._transport._wrapped_methods[ + client._transport.delete_membership + ] = mock_rpc request = {} - client.delete_feature(request) + client.delete_membership(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -4148,7 +4368,7 @@ def test_delete_feature_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_feature(request) + client.delete_membership(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4156,7 +4376,7 @@ def test_delete_feature_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_feature_async_use_cached_wrapped_rpc( +async def test_delete_membership_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4173,7 +4393,7 @@ async def test_delete_feature_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_feature + client._client._transport.delete_membership in client._client._transport._wrapped_methods ) @@ -4181,11 +4401,11 @@ async def test_delete_feature_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_feature + client._client._transport.delete_membership ] = mock_rpc request = {} - await client.delete_feature(request) + await client.delete_membership(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -4195,7 +4415,7 @@ async def test_delete_feature_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.delete_feature(request) + await client.delete_membership(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4203,8 +4423,8 @@ async def test_delete_feature_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_feature_async( - transport: str = "grpc_asyncio", request_type=service.DeleteFeatureRequest +async def test_delete_membership_async( + transport: str = "grpc_asyncio", request_type=service.DeleteMembershipRequest ): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), @@ -4216,17 +4436,19 @@ async def test_delete_feature_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_membership), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.delete_feature(request) + response = await client.delete_membership(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.DeleteFeatureRequest() + request = service.DeleteMembershipRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -4234,25 +4456,27 @@ async def test_delete_feature_async( @pytest.mark.asyncio -async def test_delete_feature_async_from_dict(): - await test_delete_feature_async(request_type=dict) +async def test_delete_membership_async_from_dict(): + await test_delete_membership_async(request_type=dict) -def test_delete_feature_field_headers(): +def test_delete_membership_field_headers(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.DeleteFeatureRequest() + request = service.DeleteMembershipRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_membership), "__call__" + ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_feature(request) + client.delete_membership(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -4268,23 +4492,25 @@ def test_delete_feature_field_headers(): @pytest.mark.asyncio -async def test_delete_feature_field_headers_async(): +async def test_delete_membership_field_headers_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.DeleteFeatureRequest() + request = service.DeleteMembershipRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_membership), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.delete_feature(request) + await client.delete_membership(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -4299,18 +4525,20 @@ async def test_delete_feature_field_headers_async(): ) in kw["metadata"] -def test_delete_feature_flattened(): +def test_delete_membership_flattened(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_membership), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_feature( + client.delete_membership( name="name_value", ) @@ -4323,7 +4551,7 @@ def test_delete_feature_flattened(): assert arg == mock_val -def test_delete_feature_flattened_error(): +def test_delete_membership_flattened_error(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -4331,20 +4559,22 @@ def test_delete_feature_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_feature( - service.DeleteFeatureRequest(), + client.delete_membership( + service.DeleteMembershipRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_delete_feature_flattened_async(): +async def test_delete_membership_flattened_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_membership), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -4353,7 +4583,7 @@ async def test_delete_feature_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_feature( + response = await client.delete_membership( name="name_value", ) @@ -4367,7 +4597,7 @@ async def test_delete_feature_flattened_async(): @pytest.mark.asyncio -async def test_delete_feature_flattened_error_async(): +async def test_delete_membership_flattened_error_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) @@ -4375,8 +4605,8 @@ async def test_delete_feature_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_feature( - service.DeleteFeatureRequest(), + await client.delete_membership( + service.DeleteMembershipRequest(), name="name_value", ) @@ -4384,11 +4614,11 @@ async def test_delete_feature_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - service.UpdateMembershipRequest, + service.DeleteFeatureRequest, dict, ], ) -def test_update_membership(request_type, transport: str = "grpc"): +def test_delete_feature(request_type, transport: str = "grpc"): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4399,24 +4629,22 @@ def test_update_membership(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_membership), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_feature), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_membership(request) + response = client.delete_feature(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.UpdateMembershipRequest() + request = service.DeleteFeatureRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_update_membership_non_empty_request_with_auto_populated_field(): +def test_delete_feature_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = GkeHubClient( @@ -4427,28 +4655,26 @@ def test_update_membership_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.UpdateMembershipRequest( + request = service.DeleteFeatureRequest( name="name_value", request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_membership), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_feature), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_membership(request=request) + client.delete_feature(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateMembershipRequest( + assert args[0] == service.DeleteFeatureRequest( name="name_value", request_id="request_id_value", ) -def test_update_membership_use_cached_wrapped_rpc(): +def test_delete_feature_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -4462,18 +4688,16 @@ def test_update_membership_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_membership in client._transport._wrapped_methods + assert client._transport.delete_feature in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.update_membership - ] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_feature] = mock_rpc request = {} - client.update_membership(request) + client.delete_feature(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -4483,7 +4707,7 @@ def test_update_membership_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_membership(request) + client.delete_feature(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4491,7 +4715,7 @@ def test_update_membership_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_membership_async_use_cached_wrapped_rpc( +async def test_delete_feature_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4508,7 +4732,7 @@ async def test_update_membership_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_membership + client._client._transport.delete_feature in client._client._transport._wrapped_methods ) @@ -4516,11 +4740,11 @@ async def test_update_membership_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_membership + client._client._transport.delete_feature ] = mock_rpc request = {} - await client.update_membership(request) + await client.delete_feature(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -4530,7 +4754,7 @@ async def test_update_membership_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.update_membership(request) + await client.delete_feature(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4538,8 +4762,8 @@ async def test_update_membership_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_membership_async( - transport: str = "grpc_asyncio", request_type=service.UpdateMembershipRequest +async def test_delete_feature_async( + transport: str = "grpc_asyncio", request_type=service.DeleteFeatureRequest ): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), @@ -4551,19 +4775,17 @@ async def test_update_membership_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_membership), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_feature), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.update_membership(request) + response = await client.delete_feature(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.UpdateMembershipRequest() + request = service.DeleteFeatureRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -4571,27 +4793,25 @@ async def test_update_membership_async( @pytest.mark.asyncio -async def test_update_membership_async_from_dict(): - await test_update_membership_async(request_type=dict) +async def test_delete_feature_async_from_dict(): + await test_delete_feature_async(request_type=dict) -def test_update_membership_field_headers(): +def test_delete_feature_field_headers(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.UpdateMembershipRequest() + request = service.DeleteFeatureRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_membership), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_feature), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_membership(request) + client.delete_feature(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -4607,25 +4827,23 @@ def test_update_membership_field_headers(): @pytest.mark.asyncio -async def test_update_membership_field_headers_async(): +async def test_delete_feature_field_headers_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.UpdateMembershipRequest() + request = service.DeleteFeatureRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_membership), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_feature), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_membership(request) + await client.delete_feature(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -4640,29 +4858,19 @@ async def test_update_membership_field_headers_async(): ) in kw["metadata"] -def test_update_membership_flattened(): +def test_delete_feature_flattened(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_membership), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_feature), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_membership( + client.delete_feature( name="name_value", - resource=membership.Membership( - endpoint=membership.MembershipEndpoint( - gke_cluster=membership.GkeCluster( - resource_link="resource_link_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -4672,19 +4880,9 @@ def test_update_membership_flattened(): arg = args[0].name mock_val = "name_value" assert arg == mock_val - arg = args[0].resource - mock_val = membership.Membership( - endpoint=membership.MembershipEndpoint( - gke_cluster=membership.GkeCluster(resource_link="resource_link_value") - ) - ) - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) - assert arg == mock_val -def test_update_membership_flattened_error(): +def test_delete_feature_flattened_error(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -4692,30 +4890,20 @@ def test_update_membership_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_membership( - service.UpdateMembershipRequest(), + client.delete_feature( + service.DeleteFeatureRequest(), name="name_value", - resource=membership.Membership( - endpoint=membership.MembershipEndpoint( - gke_cluster=membership.GkeCluster( - resource_link="resource_link_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_update_membership_flattened_async(): +async def test_delete_feature_flattened_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_membership), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_feature), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -4724,16 +4912,8 @@ async def test_update_membership_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_membership( + response = await client.delete_feature( name="name_value", - resource=membership.Membership( - endpoint=membership.MembershipEndpoint( - gke_cluster=membership.GkeCluster( - resource_link="resource_link_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -4743,20 +4923,10 @@ async def test_update_membership_flattened_async(): arg = args[0].name mock_val = "name_value" assert arg == mock_val - arg = args[0].resource - mock_val = membership.Membership( - endpoint=membership.MembershipEndpoint( - gke_cluster=membership.GkeCluster(resource_link="resource_link_value") - ) - ) - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) - assert arg == mock_val @pytest.mark.asyncio -async def test_update_membership_flattened_error_async(): +async def test_delete_feature_flattened_error_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) @@ -4764,28 +4934,20 @@ async def test_update_membership_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_membership( - service.UpdateMembershipRequest(), + await client.delete_feature( + service.DeleteFeatureRequest(), name="name_value", - resource=membership.Membership( - endpoint=membership.MembershipEndpoint( - gke_cluster=membership.GkeCluster( - resource_link="resource_link_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - service.UpdateFeatureRequest, + service.UpdateMembershipRequest, dict, ], ) -def test_update_feature(request_type, transport: str = "grpc"): +def test_update_membership(request_type, transport: str = "grpc"): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4796,22 +4958,24 @@ def test_update_feature(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.update_membership), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_feature(request) + response = client.update_membership(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.UpdateFeatureRequest() + request = service.UpdateMembershipRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_update_feature_non_empty_request_with_auto_populated_field(): +def test_update_membership_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = GkeHubClient( @@ -4822,26 +4986,28 @@ def test_update_feature_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.UpdateFeatureRequest( + request = service.UpdateMembershipRequest( name="name_value", request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.update_membership), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_feature(request=request) + client.update_membership(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateFeatureRequest( + assert args[0] == service.UpdateMembershipRequest( name="name_value", request_id="request_id_value", ) -def test_update_feature_use_cached_wrapped_rpc(): +def test_update_membership_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -4855,16 +5021,18 @@ def test_update_feature_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_feature in client._transport._wrapped_methods + assert client._transport.update_membership in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_feature] = mock_rpc + client._transport._wrapped_methods[ + client._transport.update_membership + ] = mock_rpc request = {} - client.update_feature(request) + client.update_membership(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -4874,7 +5042,7 @@ def test_update_feature_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_feature(request) + client.update_membership(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4882,7 +5050,7 @@ def test_update_feature_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_feature_async_use_cached_wrapped_rpc( +async def test_update_membership_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4899,7 +5067,7 @@ async def test_update_feature_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_feature + client._client._transport.update_membership in client._client._transport._wrapped_methods ) @@ -4907,11 +5075,11 @@ async def test_update_feature_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_feature + client._client._transport.update_membership ] = mock_rpc request = {} - await client.update_feature(request) + await client.update_membership(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -4921,7 +5089,7 @@ async def test_update_feature_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.update_feature(request) + await client.update_membership(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4929,8 +5097,8 @@ async def test_update_feature_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_feature_async( - transport: str = "grpc_asyncio", request_type=service.UpdateFeatureRequest +async def test_update_membership_async( + transport: str = "grpc_asyncio", request_type=service.UpdateMembershipRequest ): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), @@ -4942,17 +5110,19 @@ async def test_update_feature_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.update_membership), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.update_feature(request) + response = await client.update_membership(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.UpdateFeatureRequest() + request = service.UpdateMembershipRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -4960,25 +5130,27 @@ async def test_update_feature_async( @pytest.mark.asyncio -async def test_update_feature_async_from_dict(): - await test_update_feature_async(request_type=dict) +async def test_update_membership_async_from_dict(): + await test_update_membership_async(request_type=dict) -def test_update_feature_field_headers(): +def test_update_membership_field_headers(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.UpdateFeatureRequest() + request = service.UpdateMembershipRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.update_membership), "__call__" + ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_feature(request) + client.update_membership(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -4994,23 +5166,25 @@ def test_update_feature_field_headers(): @pytest.mark.asyncio -async def test_update_feature_field_headers_async(): +async def test_update_membership_field_headers_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.UpdateFeatureRequest() + request = service.UpdateMembershipRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.update_membership), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_feature(request) + await client.update_membership(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -5025,20 +5199,28 @@ async def test_update_feature_field_headers_async(): ) in kw["metadata"] -def test_update_feature_flattened(): +def test_update_membership_flattened(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.update_membership), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_feature( + client.update_membership( name="name_value", - resource=feature.Feature(name="name_value"), + resource=membership.Membership( + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster( + resource_link="resource_link_value" + ) + ) + ), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -5050,14 +5232,18 @@ def test_update_feature_flattened(): mock_val = "name_value" assert arg == mock_val arg = args[0].resource - mock_val = feature.Feature(name="name_value") + mock_val = membership.Membership( + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster(resource_link="resource_link_value") + ) + ) assert arg == mock_val arg = args[0].update_mask mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_update_feature_flattened_error(): +def test_update_membership_flattened_error(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -5065,22 +5251,30 @@ def test_update_feature_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_feature( - service.UpdateFeatureRequest(), + client.update_membership( + service.UpdateMembershipRequest(), name="name_value", - resource=feature.Feature(name="name_value"), + resource=membership.Membership( + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster( + resource_link="resource_link_value" + ) + ) + ), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_update_feature_flattened_async(): +async def test_update_membership_flattened_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_feature), "__call__") as call: + with mock.patch.object( + type(client.transport.update_membership), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -5089,9 +5283,15 @@ async def test_update_feature_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_feature( + response = await client.update_membership( name="name_value", - resource=feature.Feature(name="name_value"), + resource=membership.Membership( + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster( + resource_link="resource_link_value" + ) + ) + ), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -5103,7 +5303,11 @@ async def test_update_feature_flattened_async(): mock_val = "name_value" assert arg == mock_val arg = args[0].resource - mock_val = feature.Feature(name="name_value") + mock_val = membership.Membership( + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster(resource_link="resource_link_value") + ) + ) assert arg == mock_val arg = args[0].update_mask mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) @@ -5111,7 +5315,7 @@ async def test_update_feature_flattened_async(): @pytest.mark.asyncio -async def test_update_feature_flattened_error_async(): +async def test_update_membership_flattened_error_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) @@ -5119,10 +5323,16 @@ async def test_update_feature_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_feature( - service.UpdateFeatureRequest(), + await client.update_membership( + service.UpdateMembershipRequest(), name="name_value", - resource=feature.Feature(name="name_value"), + resource=membership.Membership( + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster( + resource_link="resource_link_value" + ) + ) + ), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -5130,11 +5340,11 @@ async def test_update_feature_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - service.GenerateConnectManifestRequest, + service.UpdateFeatureRequest, dict, ], ) -def test_generate_connect_manifest(request_type, transport: str = "grpc"): +def test_update_feature(request_type, transport: str = "grpc"): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5145,24 +5355,22 @@ def test_generate_connect_manifest(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_connect_manifest), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_feature), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.GenerateConnectManifestResponse() - response = client.generate_connect_manifest(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_feature(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.GenerateConnectManifestRequest() + request = service.UpdateFeatureRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.GenerateConnectManifestResponse) + assert isinstance(response, future.Future) -def test_generate_connect_manifest_non_empty_request_with_auto_populated_field(): +def test_update_feature_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = GkeHubClient( @@ -5173,32 +5381,26 @@ def test_generate_connect_manifest_non_empty_request_with_auto_populated_field() # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.GenerateConnectManifestRequest( + request = service.UpdateFeatureRequest( name="name_value", - namespace="namespace_value", - version="version_value", - registry="registry_value", + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_connect_manifest), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_feature), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.generate_connect_manifest(request=request) + client.update_feature(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.GenerateConnectManifestRequest( + assert args[0] == service.UpdateFeatureRequest( name="name_value", - namespace="namespace_value", - version="version_value", - registry="registry_value", + request_id="request_id_value", ) -def test_generate_connect_manifest_use_cached_wrapped_rpc(): +def test_update_feature_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5212,26 +5414,26 @@ def test_generate_connect_manifest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.generate_connect_manifest - in client._transport._wrapped_methods - ) + assert client._transport.update_feature in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.generate_connect_manifest - ] = mock_rpc + client._transport._wrapped_methods[client._transport.update_feature] = mock_rpc request = {} - client.generate_connect_manifest(request) + client.update_feature(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.generate_connect_manifest(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_feature(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5239,7 +5441,7 @@ def test_generate_connect_manifest_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_generate_connect_manifest_async_use_cached_wrapped_rpc( +async def test_update_feature_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -5256,7 +5458,7 @@ async def test_generate_connect_manifest_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.generate_connect_manifest + client._client._transport.update_feature in client._client._transport._wrapped_methods ) @@ -5264,16 +5466,21 @@ async def test_generate_connect_manifest_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.generate_connect_manifest + client._client._transport.update_feature ] = mock_rpc request = {} - await client.generate_connect_manifest(request) + await client.update_feature(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.generate_connect_manifest(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_feature(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5281,8 +5488,8 @@ async def test_generate_connect_manifest_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_generate_connect_manifest_async( - transport: str = "grpc_asyncio", request_type=service.GenerateConnectManifestRequest +async def test_update_feature_async( + transport: str = "grpc_asyncio", request_type=service.UpdateFeatureRequest ): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), @@ -5294,47 +5501,43 @@ async def test_generate_connect_manifest_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_connect_manifest), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_feature), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.GenerateConnectManifestResponse() + operations_pb2.Operation(name="operations/spam") ) - response = await client.generate_connect_manifest(request) + response = await client.update_feature(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.GenerateConnectManifestRequest() + request = service.UpdateFeatureRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.GenerateConnectManifestResponse) + assert isinstance(response, future.Future) @pytest.mark.asyncio -async def test_generate_connect_manifest_async_from_dict(): - await test_generate_connect_manifest_async(request_type=dict) +async def test_update_feature_async_from_dict(): + await test_update_feature_async(request_type=dict) -def test_generate_connect_manifest_field_headers(): +def test_update_feature_field_headers(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.GenerateConnectManifestRequest() + request = service.UpdateFeatureRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_connect_manifest), "__call__" - ) as call: - call.return_value = service.GenerateConnectManifestResponse() - client.generate_connect_manifest(request) + with mock.patch.object(type(client.transport.update_feature), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_feature(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -5350,25 +5553,23 @@ def test_generate_connect_manifest_field_headers(): @pytest.mark.asyncio -async def test_generate_connect_manifest_field_headers_async(): +async def test_update_feature_field_headers_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.GenerateConnectManifestRequest() + request = service.UpdateFeatureRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_connect_manifest), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_feature), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.GenerateConnectManifestResponse() + operations_pb2.Operation(name="operations/op") ) - await client.generate_connect_manifest(request) + await client.update_feature(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -5383,273 +5584,186 @@ async def test_generate_connect_manifest_field_headers_async(): ) in kw["metadata"] -def test_list_memberships_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +def test_update_feature_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_feature), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_feature( + name="name_value", + resource=feature.Feature(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].resource + mock_val = feature.Feature(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val - # Ensure method has been cached - assert client._transport.list_memberships in client._transport._wrapped_methods - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. +def test_update_feature_flattened_error(): + client = GkeHubClient( + credentials=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_feature( + service.UpdateFeatureRequest(), + name="name_value", + resource=feature.Feature(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - client._transport._wrapped_methods[ - client._transport.list_memberships - ] = mock_rpc - request = {} - client.list_memberships(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 +@pytest.mark.asyncio +async def test_update_feature_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) - client.list_memberships(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_feature), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_feature( + name="name_value", + resource=feature.Feature(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].resource + mock_val = feature.Feature(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val -def test_list_memberships_rest_required_fields( - request_type=service.ListMembershipsRequest, -): - transport_class = transports.GkeHubRestTransport - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +@pytest.mark.asyncio +async def test_update_feature_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), ) - # verify fields with default values are dropped + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_feature( + service.UpdateFeatureRequest(), + name="name_value", + resource=feature.Feature(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_memberships._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - # verify required fields with default values are now present +@pytest.mark.parametrize( + "request_type", + [ + service.GenerateConnectManifestRequest, + dict, + ], +) +def test_generate_connect_manifest(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - jsonified_request["parent"] = "parent_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_memberships._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "order_by", - "page_size", - "page_token", - ) - ) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.ListMembershipsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.ListMembershipsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_memberships(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_connect_manifest), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.GenerateConnectManifestResponse() + response = client.generate_connect_manifest(request) -def test_list_memberships_rest_unset_required_fields(): - transport = transports.GkeHubRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GenerateConnectManifestRequest() + assert args[0] == request - unset_fields = transport.list_memberships._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateConnectManifestResponse) -def test_list_memberships_rest_flattened(): +def test_generate_connect_manifest_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = service.ListMembershipsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListMembershipsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_memberships(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/memberships" - % client.transport._host, - args[1], - ) - - -def test_list_memberships_rest_flattened_error(transport: str = "rest"): - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GenerateConnectManifestRequest( + name="name_value", + namespace="namespace_value", + version="version_value", + registry="registry_value", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_memberships( - service.ListMembershipsRequest(), - parent="parent_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_connect_manifest), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - - -def test_list_memberships_rest_pager(transport: str = "rest"): - client = GkeHubClient( - 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 = ( - service.ListMembershipsResponse( - resources=[ - membership.Membership(), - membership.Membership(), - membership.Membership(), - ], - next_page_token="abc", - ), - service.ListMembershipsResponse( - resources=[], - next_page_token="def", - ), - service.ListMembershipsResponse( - resources=[ - membership.Membership(), - ], - next_page_token="ghi", - ), - service.ListMembershipsResponse( - resources=[ - membership.Membership(), - membership.Membership(), - ], - ), + client.generate_connect_manifest(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GenerateConnectManifestRequest( + name="name_value", + namespace="namespace_value", + version="version_value", + registry="registry_value", ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListMembershipsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "projects/sample1/locations/sample2"} - - pager = client.list_memberships(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, membership.Membership) for i in results) - - pages = list(client.list_memberships(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token -def test_list_features_rest_use_cached_wrapped_rpc(): +def test_generate_connect_manifest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -5657,153 +5771,245 @@ def test_list_features_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_features in client._transport._wrapped_methods + assert ( + client._transport.generate_connect_manifest + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_features] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.generate_connect_manifest + ] = mock_rpc request = {} - client.list_features(request) + client.generate_connect_manifest(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_features(request) + client.generate_connect_manifest(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_list_features_rest_flattened(): - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.asyncio +async def test_generate_connect_manifest_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = service.ListFeaturesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", + # Ensure method has been cached + assert ( + client._client._transport.generate_connect_manifest + in client._client._transport._wrapped_methods ) - mock_args.update(sample_request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListFeaturesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.generate_connect_manifest + ] = mock_rpc - client.list_features(**mock_args) + request = {} + await client.generate_connect_manifest(request) - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/features" % client.transport._host, - args[1], + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.generate_connect_manifest(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_generate_connect_manifest_async( + transport: str = "grpc_asyncio", request_type=service.GenerateConnectManifestRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_connect_manifest), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.GenerateConnectManifestResponse() ) + response = await client.generate_connect_manifest(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.GenerateConnectManifestRequest() + assert args[0] == request -def test_list_features_rest_flattened_error(transport: str = "rest"): + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateConnectManifestResponse) + + +@pytest.mark.asyncio +async def test_generate_connect_manifest_async_from_dict(): + await test_generate_connect_manifest_async(request_type=dict) + + +def test_generate_connect_manifest_field_headers(): client = GkeHubClient( credentials=ga_credentials.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_features( - service.ListFeaturesRequest(), - parent="parent_value", + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GenerateConnectManifestRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_connect_manifest), "__call__" + ) as call: + call.return_value = service.GenerateConnectManifestResponse() + client.generate_connect_manifest(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_generate_connect_manifest_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GenerateConnectManifestRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_connect_manifest), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.GenerateConnectManifestResponse() ) + await client.generate_connect_manifest(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -def test_list_features_rest_pager(transport: str = "rest"): + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateFleetRequest, + dict, + ], +) +def test_create_fleet(request_type, transport: str = "grpc"): client = GkeHubClient( 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 = ( - service.ListFeaturesResponse( - resources=[ - feature.Feature(), - feature.Feature(), - feature.Feature(), - ], - next_page_token="abc", - ), - service.ListFeaturesResponse( - resources=[], - next_page_token="def", - ), - service.ListFeaturesResponse( - resources=[ - feature.Feature(), - ], - next_page_token="ghi", - ), - service.ListFeaturesResponse( - resources=[ - feature.Feature(), - feature.Feature(), - ], - ), - ) - # Two responses for two calls - response = response + response + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # Wrap the values into proper Response objs - response = tuple(service.ListFeaturesResponse.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 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_fleet), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_fleet(request) - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.CreateFleetRequest() + assert args[0] == request - pager = client.list_features(request=sample_request) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, feature.Feature) for i in results) - pages = list(client.list_features(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token +def test_create_fleet_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.CreateFleetRequest( + parent="parent_value", + ) -def test_get_membership_rest_use_cached_wrapped_rpc(): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_fleet), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_fleet(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateFleetRequest( + parent="parent_value", + ) + + +def test_create_fleet_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -5811,270 +6017,343 @@ def test_get_membership_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_membership in client._transport._wrapped_methods + assert client._transport.create_fleet in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_membership] = mock_rpc - + client._transport._wrapped_methods[client._transport.create_fleet] = mock_rpc request = {} - client.get_membership(request) + client.create_fleet(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_membership(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_fleet(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_membership_rest_required_fields(request_type=service.GetMembershipRequest): - transport_class = transports.GkeHubRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) +@pytest.mark.asyncio +async def test_create_fleet_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # verify fields with default values are dropped + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_membership._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Ensure method has been cached + assert ( + client._client._transport.create_fleet + in client._client._transport._wrapped_methods + ) - # verify required fields with default values are now present + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_fleet + ] = mock_rpc - jsonified_request["name"] = "name_value" + request = {} + await client.create_fleet(request) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_membership._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + await client.create_fleet(request) - # Designate an appropriate value for the returned response. - return_value = membership.Membership() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = membership.Membership.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +async def test_create_fleet_async( + transport: str = "grpc_asyncio", request_type=service.CreateFleetRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response = client.get_membership(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_fleet), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_fleet(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.CreateFleetRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_get_membership_rest_unset_required_fields(): - transport = transports.GkeHubRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - unset_fields = transport.get_membership._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) +@pytest.mark.asyncio +async def test_create_fleet_async_from_dict(): + await test_create_fleet_async(request_type=dict) -def test_get_membership_rest_flattened(): +def test_create_fleet_field_headers(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = membership.Membership() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateFleetRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/memberships/sample3" - } + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_fleet), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_fleet(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_fleet_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateFleetRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_fleet), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) + await client.create_fleet(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = membership.Membership.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.get_membership(**mock_args) + # Establish 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_fleet_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_fleet), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_fleet( + parent="parent_value", + fleet=gcg_fleet.Fleet(name="name_value"), + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/memberships/*}" - % client.transport._host, - args[1], - ) + 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].fleet + mock_val = gcg_fleet.Fleet(name="name_value") + assert arg == mock_val -def test_get_membership_rest_flattened_error(transport: str = "rest"): +def test_create_fleet_flattened_error(): client = GkeHubClient( credentials=ga_credentials.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_membership( - service.GetMembershipRequest(), - name="name_value", + client.create_fleet( + service.CreateFleetRequest(), + parent="parent_value", + fleet=gcg_fleet.Fleet(name="name_value"), ) -def test_get_feature_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.asyncio +async def test_create_fleet_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.get_feature in client._transport._wrapped_methods + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_fleet), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_fleet( + parent="parent_value", + fleet=gcg_fleet.Fleet(name="name_value"), ) - client._transport._wrapped_methods[client._transport.get_feature] = mock_rpc - request = {} - client.get_feature(request) + # Establish that the underlying call was made with the expected + # request 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].fleet + mock_val = gcg_fleet.Fleet(name="name_value") + assert arg == mock_val - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - client.get_feature(request) +@pytest.mark.asyncio +async def test_create_fleet_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_fleet( + service.CreateFleetRequest(), + parent="parent_value", + fleet=gcg_fleet.Fleet(name="name_value"), + ) -def test_get_feature_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + service.GetFleetRequest, + dict, + ], +) +def test_get_fleet(request_type, transport: str = "grpc"): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = feature.Feature() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/features/sample3"} + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # get truthy value for each flattened field - mock_args = dict( + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_fleet), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = fleet.Fleet( name="name_value", + display_name="display_name_value", + uid="uid_value", ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = feature.Feature.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_fleet(request) - client.get_feature(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GetFleetRequest() + assert args[0] == request - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/features/*}" % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, fleet.Fleet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.uid == "uid_value" -def test_get_feature_rest_flattened_error(transport: str = "rest"): +def test_get_fleet_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_feature( - service.GetFeatureRequest(), + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GetFleetRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_fleet), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_fleet(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetFleetRequest( name="name_value", ) -def test_create_membership_rest_use_cached_wrapped_rpc(): +def test_get_fleet_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -6082,328 +6361,313 @@ def test_create_membership_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_membership in client._transport._wrapped_methods + assert client._transport.get_fleet in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.create_membership - ] = mock_rpc - + client._transport._wrapped_methods[client._transport.get_fleet] = mock_rpc request = {} - client.create_membership(request) + client.get_fleet(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_membership(request) + client.get_fleet(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_membership_rest_required_fields( - request_type=service.CreateMembershipRequest, -): - transport_class = transports.GkeHubRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["membership_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) +@pytest.mark.asyncio +async def test_get_fleet_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # verify fields with default values are dropped - assert "membershipId" not in jsonified_request + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_membership._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Ensure method has been cached + assert ( + client._client._transport.get_fleet + in client._client._transport._wrapped_methods + ) - # verify required fields with default values are now present - assert "membershipId" in jsonified_request - assert jsonified_request["membershipId"] == request_init["membership_id"] + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_fleet + ] = mock_rpc - jsonified_request["parent"] = "parent_value" - jsonified_request["membershipId"] = "membership_id_value" + request = {} + await client.get_fleet(request) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_membership._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "membership_id", - "request_id", - ) - ) - jsonified_request.update(unset_fields) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "membershipId" in jsonified_request - assert jsonified_request["membershipId"] == "membership_id_value" + await client.get_fleet(request) - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +async def test_get_fleet_async( + transport: str = "grpc_asyncio", request_type=service.GetFleetRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response = client.create_membership(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_fleet), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fleet.Fleet( + name="name_value", + display_name="display_name_value", + uid="uid_value", + ) + ) + response = await client.get_fleet(request) - expected_params = [ - ( - "membershipId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.GetFleetRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, fleet.Fleet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.uid == "uid_value" -def test_create_membership_rest_unset_required_fields(): - transport = transports.GkeHubRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - unset_fields = transport.create_membership._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "membershipId", - "requestId", - ) - ) - & set( - ( - "parent", - "membershipId", - "resource", - ) - ) - ) +@pytest.mark.asyncio +async def test_get_fleet_async_from_dict(): + await test_get_fleet_async(request_type=dict) -def test_create_membership_rest_flattened(): +def test_get_fleet_field_headers(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetFleetRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + request.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - resource=membership.Membership( - endpoint=membership.MembershipEndpoint( - gke_cluster=membership.GkeCluster( - resource_link="resource_link_value" - ) - ) - ), - membership_id="membership_id_value", - ) - mock_args.update(sample_request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_fleet), "__call__") as call: + call.return_value = fleet.Fleet() + client.get_fleet(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.create_membership(**mock_args) + # Establish that the field header 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_fleet_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetFleetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_fleet), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fleet.Fleet()) + await client.get_fleet(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_fleet_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_fleet), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = fleet.Fleet() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_fleet( + name="name_value", + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/memberships" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_create_membership_rest_flattened_error(transport: str = "rest"): +def test_get_fleet_flattened_error(): client = GkeHubClient( credentials=ga_credentials.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_membership( - service.CreateMembershipRequest(), - parent="parent_value", - resource=membership.Membership( - endpoint=membership.MembershipEndpoint( - gke_cluster=membership.GkeCluster( - resource_link="resource_link_value" - ) - ) - ), - membership_id="membership_id_value", + client.get_fleet( + service.GetFleetRequest(), + name="name_value", ) -def test_create_feature_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.asyncio +async def test_get_fleet_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.create_feature in client._transport._wrapped_methods + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_fleet), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = fleet.Fleet() - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fleet.Fleet()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_fleet( + name="name_value", ) - client._transport._wrapped_methods[client._transport.create_feature] = mock_rpc - - request = {} - client.create_feature(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - client.create_feature(request) +@pytest.mark.asyncio +async def test_get_fleet_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_fleet( + service.GetFleetRequest(), + name="name_value", + ) -def test_create_feature_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateFleetRequest, + dict, + ], +) +def test_update_fleet(request_type, transport: str = "grpc"): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - resource=feature.Feature(name="name_value"), - feature_id="feature_id_value", - ) - mock_args.update(sample_request) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_fleet), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_fleet(request) - client.create_feature(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.UpdateFleetRequest() + assert args[0] == request - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/features" % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_create_feature_rest_flattened_error(transport: str = "rest"): +def test_update_fleet_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_feature( - service.CreateFeatureRequest(), - parent="parent_value", - resource=feature.Feature(name="name_value"), - feature_id="feature_id_value", + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.UpdateFleetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_fleet), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client.update_fleet(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateFleetRequest() -def test_delete_membership_rest_use_cached_wrapped_rpc(): +def test_update_fleet_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -6411,290 +6675,336 @@ def test_delete_membership_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_membership in client._transport._wrapped_methods + assert client._transport.update_fleet in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.delete_membership - ] = mock_rpc - + client._transport._wrapped_methods[client._transport.update_fleet] = mock_rpc request = {} - client.delete_membership(request) + client.update_fleet(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_membership(request) + client.update_fleet(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_membership_rest_required_fields( - request_type=service.DeleteMembershipRequest, +@pytest.mark.asyncio +async def test_update_fleet_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.GkeHubRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.update_fleet + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_membership._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_fleet + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.update_fleet(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_membership._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "force", - "request_id", - ) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_fleet(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_fleet_async( + transport: str = "grpc_asyncio", request_type=service.UpdateFleetRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_fleet), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_fleet(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.UpdateFleetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + +@pytest.mark.asyncio +async def test_update_fleet_async_from_dict(): + await test_update_fleet_async(request_type=dict) + + +def test_update_fleet_field_headers(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "delete", - "query_params": pb_request, - } - transcode.return_value = transcode_result + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateFleetRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.fleet.name = "name_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_fleet), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_fleet(request) - response = client.delete_membership(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "fleet.name=name_value", + ) in kw["metadata"] -def test_delete_membership_rest_unset_required_fields(): - transport = transports.GkeHubRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_update_fleet_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.delete_membership._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "force", - "requestId", - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateFleetRequest() + + request.fleet.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_fleet), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - & set(("name",)) - ) + await client.update_fleet(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_delete_membership_rest_flattened(): + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "fleet.name=name_value", + ) in kw["metadata"] + + +def test_update_fleet_flattened(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/memberships/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_fleet), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_fleet( + fleet=gcg_fleet.Fleet(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_membership(**mock_args) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/memberships/*}" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].fleet + mock_val = gcg_fleet.Fleet(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val -def test_delete_membership_rest_flattened_error(transport: str = "rest"): +def test_update_fleet_flattened_error(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_membership( - service.DeleteMembershipRequest(), - name="name_value", + client.update_fleet( + service.UpdateFleetRequest(), + fleet=gcg_fleet.Fleet(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_delete_feature_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.asyncio +async def test_update_fleet_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.delete_feature in client._transport._wrapped_methods + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_fleet), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_fleet( + fleet=gcg_fleet.Fleet(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - client._transport._wrapped_methods[client._transport.delete_feature] = mock_rpc - - request = {} - client.delete_feature(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].fleet + mock_val = gcg_fleet.Fleet(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - client.delete_feature(request) +@pytest.mark.asyncio +async def test_update_fleet_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_fleet( + service.UpdateFleetRequest(), + fleet=gcg_fleet.Fleet(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) -def test_delete_feature_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteFleetRequest, + dict, + ], +) +def test_delete_fleet(request_type, transport: str = "grpc"): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/features/sample3"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_fleet), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_fleet(request) - client.delete_feature(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.DeleteFleetRequest() + assert args[0] == request - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/features/*}" % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_delete_feature_rest_flattened_error(transport: str = "rest"): +def test_delete_fleet_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_feature( - service.DeleteFeatureRequest(), + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.DeleteFleetRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_fleet), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_fleet(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteFleetRequest( name="name_value", ) -def test_update_membership_rest_use_cached_wrapped_rpc(): +def test_delete_fleet_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -6702,317 +7012,331 @@ def test_update_membership_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_membership in client._transport._wrapped_methods + assert client._transport.delete_fleet in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.update_membership - ] = mock_rpc - + client._transport._wrapped_methods[client._transport.delete_fleet] = mock_rpc request = {} - client.update_membership(request) + client.delete_fleet(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_membership(request) + client.delete_fleet(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_membership_rest_required_fields( - request_type=service.UpdateMembershipRequest, +@pytest.mark.asyncio +async def test_delete_fleet_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.GkeHubRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.delete_fleet + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_membership._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_fleet + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.delete_fleet(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_membership._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "request_id", - "update_mask", - ) - ) - jsonified_request.update(unset_fields) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + await client.delete_fleet(request) - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "patch", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +async def test_delete_fleet_async( + transport: str = "grpc_asyncio", request_type=service.DeleteFleetRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - response = client.update_membership(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_fleet), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_fleet(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.DeleteFleetRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_update_membership_rest_unset_required_fields(): - transport = transports.GkeHubRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - unset_fields = transport.update_membership._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "requestId", - "updateMask", - ) - ) - & set( - ( - "name", - "updateMask", - "resource", - ) - ) - ) +@pytest.mark.asyncio +async def test_delete_fleet_async_from_dict(): + await test_delete_fleet_async(request_type=dict) -def test_update_membership_rest_flattened(): +def test_delete_fleet_field_headers(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/memberships/sample3" - } + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteFleetRequest() - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - resource=membership.Membership( - endpoint=membership.MembershipEndpoint( - gke_cluster=membership.GkeCluster( - resource_link="resource_link_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - mock_args.update(sample_request) + request.name = "name_value" - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_fleet), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_fleet(request) - client.update_membership(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_fleet_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteFleetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_fleet), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_fleet(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_fleet_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_fleet), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_fleet( + name="name_value", + ) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/memberships/*}" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_update_membership_rest_flattened_error(transport: str = "rest"): +def test_delete_fleet_flattened_error(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_membership( - service.UpdateMembershipRequest(), + client.delete_fleet( + service.DeleteFleetRequest(), name="name_value", - resource=membership.Membership( - endpoint=membership.MembershipEndpoint( - gke_cluster=membership.GkeCluster( - resource_link="resource_link_value" - ) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_update_feature_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.asyncio +async def test_delete_fleet_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.update_feature in client._transport._wrapped_methods + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_fleet), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_fleet( + name="name_value", ) - client._transport._wrapped_methods[client._transport.update_feature] = mock_rpc - - request = {} - client.update_feature(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - client.update_feature(request) +@pytest.mark.asyncio +async def test_delete_fleet_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_fleet( + service.DeleteFleetRequest(), + name="name_value", + ) -def test_update_feature_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + service.ListFleetsRequest, + dict, + ], +) +def test_list_fleets(request_type, transport: str = "grpc"): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/features/sample3"} + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - resource=feature.Feature(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_fleets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListFleetsResponse( + next_page_token="next_page_token_value", ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_fleets(request) - client.update_feature(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.ListFleetsRequest() + assert args[0] == request - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/features/*}" % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFleetsPager) + assert response.next_page_token == "next_page_token_value" -def test_update_feature_rest_flattened_error(transport: str = "rest"): +def test_list_fleets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_feature( - service.UpdateFeatureRequest(), - name="name_value", - resource=feature.Feature(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.ListFleetsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_fleets), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_fleets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListFleetsRequest( + parent="parent_value", + page_token="page_token_value", ) -def test_generate_connect_manifest_rest_use_cached_wrapped_rpc(): +def test_list_fleets_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -7020,1285 +7344,28359 @@ def test_generate_connect_manifest_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.generate_connect_manifest - in client._transport._wrapped_methods - ) + assert client._transport.list_fleets in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.generate_connect_manifest - ] = mock_rpc - + client._transport._wrapped_methods[client._transport.list_fleets] = mock_rpc request = {} - client.generate_connect_manifest(request) + client.list_fleets(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.generate_connect_manifest(request) + client.list_fleets(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_generate_connect_manifest_rest_required_fields( - request_type=service.GenerateConnectManifestRequest, +@pytest.mark.asyncio +async def test_list_fleets_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.GkeHubRestTransport + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.list_fleets + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).generate_connect_manifest._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_fleets + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.list_fleets(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).generate_connect_manifest._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "image_pull_secret_content", - "is_upgrade", - "namespace", - "proxy", - "registry", - "version", - ) + await client.list_fleets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_fleets_async( + transport: str = "grpc_asyncio", request_type=service.ListFleetsRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_fleets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListFleetsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_fleets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.ListFleetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFleetsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_fleets_async_from_dict(): + await test_list_fleets_async(request_type=dict) + +def test_list_fleets_field_headers(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.GenerateConnectManifestResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result - response_value = Response() - response_value.status_code = 200 + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListFleetsRequest() - # Convert return value to protobuf type - return_value = service.GenerateConnectManifestResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_fleets), "__call__") as call: + call.return_value = service.ListFleetsResponse() + client.list_fleets(request) - response = client.generate_connect_manifest(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -def test_generate_connect_manifest_rest_unset_required_fields(): - transport = transports.GkeHubRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_list_fleets_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.generate_connect_manifest._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "imagePullSecretContent", - "isUpgrade", - "namespace", - "proxy", - "registry", - "version", - ) - ) - & set(("name",)) - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListFleetsRequest() + request.parent = "parent_value" -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.GkeHubGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_fleets), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListFleetsResponse() ) + await client.list_fleets(request) - # It is an error to provide a credentials file and a transport instance. - transport = transports.GkeHubGrpcTransport( + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_fleets_flattened(): + client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) - with pytest.raises(ValueError): - client = GkeHubClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_fleets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListFleetsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_fleets( + parent="parent_value", ) - # It is an error to provide an api_key and a transport instance. - transport = transports.GkeHubGrpcTransport( + # Establish that the underlying call was made with the expected + # request object 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_fleets_flattened_error(): + client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = GkeHubClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" + # Attempting to call a method with both a request object and flattened + # fields is an error. with pytest.raises(ValueError): - client = GkeHubClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + client.list_fleets( + service.ListFleetsRequest(), + parent="parent_value", ) - # It is an error to provide scopes and a transport instance. - transport = transports.GkeHubGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + +@pytest.mark.asyncio +async def test_list_fleets_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), ) - with pytest.raises(ValueError): - client = GkeHubClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_fleets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListFleetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListFleetsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_fleets( + 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 + -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.GkeHubGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), +@pytest.mark.asyncio +async def test_list_fleets_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), ) - client = GkeHubClient(transport=transport) - assert client.transport is transport + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_fleets( + service.ListFleetsRequest(), + parent="parent_value", + ) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.GkeHubGrpcTransport( +def test_list_fleets_pager(transport_name: str = "grpc"): + client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - channel = transport.grpc_channel - assert channel - - transport = transports.GkeHubGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.GkeHubGrpcTransport, - transports.GkeHubGrpcAsyncIOTransport, - transports.GkeHubRestTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_fleets), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListFleetsResponse( + fleets=[ + fleet.Fleet(), + fleet.Fleet(), + fleet.Fleet(), + ], + next_page_token="abc", + ), + service.ListFleetsResponse( + fleets=[], + next_page_token="def", + ), + service.ListFleetsResponse( + fleets=[ + fleet.Fleet(), + ], + next_page_token="ghi", + ), + service.ListFleetsResponse( + fleets=[ + fleet.Fleet(), + fleet.Fleet(), + ], + ), + RuntimeError, + ) -def test_transport_kind_grpc(): - transport = GkeHubClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_fleets(request={}, retry=retry, timeout=timeout) + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout -def test_initialize_client_w_grpc(): - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" - ) - assert client is not None + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, fleet.Fleet) for i in results) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_memberships_empty_call_grpc(): +def test_list_fleets_pages(transport_name: str = "grpc"): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport_name, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_memberships), "__call__") as call: - call.return_value = service.ListMembershipsResponse() - client.list_memberships(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListMembershipsRequest() - - assert args[0] == request_msg + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_fleets), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListFleetsResponse( + fleets=[ + fleet.Fleet(), + fleet.Fleet(), + fleet.Fleet(), + ], + next_page_token="abc", + ), + service.ListFleetsResponse( + fleets=[], + next_page_token="def", + ), + service.ListFleetsResponse( + fleets=[ + fleet.Fleet(), + ], + next_page_token="ghi", + ), + service.ListFleetsResponse( + fleets=[ + fleet.Fleet(), + fleet.Fleet(), + ], + ), + RuntimeError, + ) + pages = list(client.list_fleets(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_features_empty_call_grpc(): - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_list_fleets_async_pager(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_features), "__call__") as call: - call.return_value = service.ListFeaturesResponse() - client.list_features(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListFeaturesRequest() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_fleets), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListFleetsResponse( + fleets=[ + fleet.Fleet(), + fleet.Fleet(), + fleet.Fleet(), + ], + next_page_token="abc", + ), + service.ListFleetsResponse( + fleets=[], + next_page_token="def", + ), + service.ListFleetsResponse( + fleets=[ + fleet.Fleet(), + ], + next_page_token="ghi", + ), + service.ListFleetsResponse( + fleets=[ + fleet.Fleet(), + fleet.Fleet(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_fleets( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - assert args[0] == request_msg + assert len(responses) == 6 + assert all(isinstance(i, fleet.Fleet) for i in responses) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_membership_empty_call_grpc(): - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_list_fleets_async_pages(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_membership), "__call__") as call: - call.return_value = membership.Membership() - client.get_membership(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetMembershipRequest() - - assert args[0] == request_msg + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_fleets), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListFleetsResponse( + fleets=[ + fleet.Fleet(), + fleet.Fleet(), + fleet.Fleet(), + ], + next_page_token="abc", + ), + service.ListFleetsResponse( + fleets=[], + next_page_token="def", + ), + service.ListFleetsResponse( + fleets=[ + fleet.Fleet(), + ], + next_page_token="ghi", + ), + service.ListFleetsResponse( + fleets=[ + fleet.Fleet(), + fleet.Fleet(), + ], + ), + 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_fleets(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_feature_empty_call_grpc(): +@pytest.mark.parametrize( + "request_type", + [ + service.GetScopeNamespaceRequest, + dict, + ], +) +def test_get_scope_namespace(request_type, transport: str = "grpc"): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_feature), "__call__") as call: - call.return_value = feature.Feature() - client.get_feature(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetFeatureRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_membership_empty_call_grpc(): - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_membership), "__call__" + type(client.transport.get_scope_namespace), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_membership(request=None) + # Designate an appropriate return value for the call. + call.return_value = fleet.Namespace( + name="name_value", + uid="uid_value", + scope="scope_value", + ) + response = client.get_scope_namespace(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = service.CreateMembershipRequest() + request = service.GetScopeNamespaceRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the response is the type that we expect. + assert isinstance(response, fleet.Namespace) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.scope == "scope_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_feature_empty_call_grpc(): +def test_get_scope_namespace_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_feature), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_feature(request=None) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GetScopeNamespaceRequest( + name="name_value", + ) - # Establish that the underlying stub method was called. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scope_namespace), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_scope_namespace(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.CreateFeatureRequest() - - assert args[0] == request_msg + assert args[0] == service.GetScopeNamespaceRequest( + name="name_value", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_membership_empty_call_grpc(): - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) +def test_get_scope_namespace_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_membership), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_membership(request=None) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteMembershipRequest() + # Ensure method has been cached + assert ( + client._transport.get_scope_namespace in client._transport._wrapped_methods + ) - assert args[0] == request_msg + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_scope_namespace + ] = mock_rpc + request = {} + client.get_scope_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.get_scope_namespace(request) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_feature_empty_call_grpc(): - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_scope_namespace_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_scope_namespace + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_scope_namespace + ] = mock_rpc + + request = {} + await client.get_scope_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_scope_namespace(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_scope_namespace_async( + transport: str = "grpc_asyncio", request_type=service.GetScopeNamespaceRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_feature), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_feature(request=None) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # Establish that the underlying stub method was called. - call.assert_called() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scope_namespace), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fleet.Namespace( + name="name_value", + uid="uid_value", + scope="scope_value", + ) + ) + response = await client.get_scope_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = service.DeleteFeatureRequest() + request = service.GetScopeNamespaceRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the response is the type that we expect. + assert isinstance(response, fleet.Namespace) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.scope == "scope_value" -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_membership_empty_call_grpc(): +@pytest.mark.asyncio +async def test_get_scope_namespace_async_from_dict(): + await test_get_scope_namespace_async(request_type=dict) + + +def test_get_scope_namespace_field_headers(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetScopeNamespaceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_membership), "__call__" + type(client.transport.get_scope_namespace), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_membership(request=None) + call.return_value = fleet.Namespace() + client.get_scope_namespace(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = service.UpdateMembershipRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_feature_empty_call_grpc(): - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_get_scope_namespace_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_feature), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_feature(request=None) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetScopeNamespaceRequest() - # Establish that the underlying stub method was called. - call.assert_called() + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scope_namespace), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fleet.Namespace()) + await client.get_scope_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = service.UpdateFeatureRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_connect_manifest_empty_call_grpc(): +def test_get_scope_namespace_flattened(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_connect_manifest), "__call__" + type(client.transport.get_scope_namespace), "__call__" ) as call: - call.return_value = service.GenerateConnectManifestResponse() - client.generate_connect_manifest(request=None) + # Designate an appropriate return value for the call. + call.return_value = fleet.Namespace() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_scope_namespace( + name="name_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = service.GenerateConnectManifestRequest() - - assert args[0] == request_msg + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_transport_kind_grpc_asyncio(): - transport = GkeHubAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() +def test_get_scope_namespace_flattened_error(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), ) - assert transport.kind == "grpc_asyncio" - -def test_initialize_client_w_grpc_asyncio(): - client = GkeHubAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" - ) - assert client is not None + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_scope_namespace( + service.GetScopeNamespaceRequest(), + name="name_value", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_list_memberships_empty_call_grpc_asyncio(): +async def test_get_scope_namespace_flattened_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_memberships), "__call__") as call: + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scope_namespace), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListMembershipsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + call.return_value = fleet.Namespace() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fleet.Namespace()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_scope_namespace( + name="name_value", ) - await client.list_memberships(request=None) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = service.ListMembershipsRequest() - - assert args[0] == request_msg + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_list_features_empty_call_grpc_asyncio(): +async def test_get_scope_namespace_flattened_error_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_features), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListFeaturesResponse( - next_page_token="next_page_token_value", - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_scope_namespace( + service.GetScopeNamespaceRequest(), + name="name_value", ) - await client.list_features(request=None) - # Establish that the underlying stub method was called. - call.assert_called() + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateScopeNamespaceRequest, + dict, + ], +) +def test_create_scope_namespace(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scope_namespace), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_scope_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = service.ListFeaturesRequest() + request = service.CreateScopeNamespaceRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_membership_empty_call_grpc_asyncio(): - client = GkeHubAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_create_scope_namespace_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_membership), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - membership.Membership( - name="name_value", - description="description_value", - external_id="external_id_value", - unique_id="unique_id_value", - ) - ) - await client.get_membership(request=None) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.CreateScopeNamespaceRequest( + parent="parent_value", + scope_namespace_id="scope_namespace_id_value", + ) - # Establish that the underlying stub method was called. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scope_namespace), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_scope_namespace(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.GetMembershipRequest() + assert args[0] == service.CreateScopeNamespaceRequest( + parent="parent_value", + scope_namespace_id="scope_namespace_id_value", + ) - assert args[0] == request_msg + +def test_create_scope_namespace_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_scope_namespace + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_scope_namespace + ] = mock_rpc + request = {} + client.create_scope_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_scope_namespace(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_get_feature_empty_call_grpc_asyncio(): - client = GkeHubAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) +async def test_create_scope_namespace_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_feature), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - feature.Feature( - name="name_value", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_scope_namespace + in client._client._transport._wrapped_methods ) - await client.get_feature(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetFeatureRequest() + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_scope_namespace + ] = mock_rpc - assert args[0] == request_msg + request = {} + await client.create_scope_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_scope_namespace(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_create_membership_empty_call_grpc_asyncio(): +async def test_create_scope_namespace_async( + transport: str = "grpc_asyncio", request_type=service.CreateScopeNamespaceRequest +): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + transport=transport, ) - # Mock the actual call, and fake the request. + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_membership), "__call__" + type(client.transport.create_scope_namespace), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - await client.create_membership(request=None) + response = await client.create_scope_namespace(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = service.CreateMembershipRequest() + request = service.CreateScopeNamespaceRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_create_feature_empty_call_grpc_asyncio(): - client = GkeHubAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +async def test_create_scope_namespace_async_from_dict(): + await test_create_scope_namespace_async(request_type=dict) + + +def test_create_scope_namespace_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_feature), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - await client.create_feature(request=None) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateScopeNamespaceRequest() - # Establish that the underlying stub method was called. - call.assert_called() + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scope_namespace), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_scope_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = service.CreateFeatureRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_delete_membership_empty_call_grpc_asyncio(): +async def test_create_scope_namespace_field_headers_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateScopeNamespaceRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_membership), "__call__" + type(client.transport.create_scope_namespace), "__call__" ) as call: - # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name="operations/op") ) - await client.delete_membership(request=None) + await client.create_scope_namespace(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = service.DeleteMembershipRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_feature_empty_call_grpc_asyncio(): - client = GkeHubAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_create_scope_namespace_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_feature), "__call__") as call: + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scope_namespace), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_scope_namespace( + parent="parent_value", + scope_namespace=fleet.Namespace(name="name_value"), + scope_namespace_id="scope_namespace_id_value", ) - await client.delete_feature(request=None) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = service.DeleteFeatureRequest() + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].scope_namespace + mock_val = fleet.Namespace(name="name_value") + assert arg == mock_val + arg = args[0].scope_namespace_id + mock_val = "scope_namespace_id_value" + assert arg == mock_val - assert args[0] == request_msg + +def test_create_scope_namespace_flattened_error(): + client = GkeHubClient( + credentials=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_scope_namespace( + service.CreateScopeNamespaceRequest(), + parent="parent_value", + scope_namespace=fleet.Namespace(name="name_value"), + scope_namespace_id="scope_namespace_id_value", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_update_membership_empty_call_grpc_asyncio(): +async def test_create_scope_namespace_flattened_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_membership), "__call__" + type(client.transport.create_scope_namespace), "__call__" ) as call: # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - await client.update_membership(request=None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_scope_namespace( + parent="parent_value", + scope_namespace=fleet.Namespace(name="name_value"), + scope_namespace_id="scope_namespace_id_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = service.UpdateMembershipRequest() - - assert args[0] == request_msg + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].scope_namespace + mock_val = fleet.Namespace(name="name_value") + assert arg == mock_val + arg = args[0].scope_namespace_id + mock_val = "scope_namespace_id_value" + assert arg == mock_val -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_update_feature_empty_call_grpc_asyncio(): +async def test_create_scope_namespace_flattened_error_async(): client = GkeHubAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_feature), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_scope_namespace( + service.CreateScopeNamespaceRequest(), + parent="parent_value", + scope_namespace=fleet.Namespace(name="name_value"), + scope_namespace_id="scope_namespace_id_value", ) - await client.update_feature(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateFeatureRequest() - - assert args[0] == request_msg -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_generate_connect_manifest_empty_call_grpc_asyncio(): - client = GkeHubAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateScopeNamespaceRequest, + dict, + ], +) +def test_update_scope_namespace(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_connect_manifest), "__call__" + type(client.transport.update_scope_namespace), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.GenerateConnectManifestResponse() - ) - await client.generate_connect_manifest(request=None) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_scope_namespace(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = service.GenerateConnectManifestRequest() + request = service.UpdateScopeNamespaceRequest() + assert args[0] == request - assert args[0] == request_msg + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_transport_kind_rest(): - transport = GkeHubClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() +def test_update_scope_namespace_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - assert transport.kind == "rest" + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.UpdateScopeNamespaceRequest() -def test_list_memberships_rest_bad_request(request_type=service.ListMembershipsRequest): - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request = request_type(**request_init) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scope_namespace), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_scope_namespace(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateScopeNamespaceRequest() - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_memberships(request) +def test_update_scope_namespace_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) -@pytest.mark.parametrize( - "request_type", - [ - service.ListMembershipsRequest, - dict, - ], -) -def test_list_memberships_rest_call_success(request_type): - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request = request_type(**request_init) + # Ensure method has been cached + assert ( + client._transport.update_scope_namespace + in client._transport._wrapped_methods + ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = service.ListMembershipsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client._transport._wrapped_methods[ + client._transport.update_scope_namespace + ] = mock_rpc + request = {} + client.update_scope_namespace(request) - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Convert return value to protobuf type - return_value = service.ListMembershipsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_memberships(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMembershipsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + client.update_scope_namespace(request) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_memberships_rest_interceptors(null_interceptor): - transport = transports.GkeHubRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), - ) - client = GkeHubClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.GkeHubRestInterceptor, "post_list_memberships" - ) as post, mock.patch.object( - transports.GkeHubRestInterceptor, "post_list_memberships_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GkeHubRestInterceptor, "pre_list_memberships" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = service.ListMembershipsRequest.pb(service.ListMembershipsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.ListMembershipsResponse.to_json( - service.ListMembershipsResponse() +@pytest.mark.asyncio +async def test_update_scope_namespace_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - req.return_value.content = return_value - request = service.ListMembershipsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.ListMembershipsResponse() - post_with_metadata.return_value = service.ListMembershipsResponse(), metadata + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - client.list_memberships( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + # Ensure method has been cached + assert ( + client._client._transport.update_scope_namespace + in client._client._transport._wrapped_methods ) - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_scope_namespace + ] = mock_rpc + request = {} + await client.update_scope_namespace(request) -def test_list_features_rest_bad_request(request_type=service.ListFeaturesRequest): - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request = request_type(**request_init) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_features(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + await client.update_scope_namespace(request) -@pytest.mark.parametrize( - "request_type", - [ - service.ListFeaturesRequest, - dict, - ], -) -def test_list_features_rest_call_success(request_type): - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_scope_namespace_async( + transport: str = "grpc_asyncio", request_type=service.UpdateScopeNamespaceRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request = request_type(**request_init) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = service.ListFeaturesResponse( - next_page_token="next_page_token_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scope_namespace), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) + response = await client.update_scope_namespace(request) - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.ListFeaturesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_features(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.UpdateScopeNamespaceRequest() + assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFeaturesPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, future.Future) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_features_rest_interceptors(null_interceptor): - transport = transports.GkeHubRestTransport( +@pytest.mark.asyncio +async def test_update_scope_namespace_async_from_dict(): + await test_update_scope_namespace_async(request_type=dict) + + +def test_update_scope_namespace_field_headers(): + client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), ) - client = GkeHubClient(transport=transport) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateScopeNamespaceRequest() + + request.scope_namespace.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.GkeHubRestInterceptor, "post_list_features" - ) as post, mock.patch.object( - transports.GkeHubRestInterceptor, "post_list_features_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GkeHubRestInterceptor, "pre_list_features" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = service.ListFeaturesRequest.pb(service.ListFeaturesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } + type(client.transport.update_scope_namespace), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_scope_namespace(request) - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.ListFeaturesResponse.to_json( - service.ListFeaturesResponse() - ) - req.return_value.content = return_value + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - request = service.ListFeaturesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.ListFeaturesResponse() - post_with_metadata.return_value = service.ListFeaturesResponse(), metadata + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "scope_namespace.name=name_value", + ) in kw["metadata"] - client.list_features( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + +@pytest.mark.asyncio +async def test_update_scope_namespace_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateScopeNamespaceRequest() + + request.scope_namespace.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scope_namespace), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) + await client.update_scope_namespace(request) - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "scope_namespace.name=name_value", + ) in kw["metadata"] -def test_get_membership_rest_bad_request(request_type=service.GetMembershipRequest): + +def test_update_scope_namespace_flattened(): client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_membership(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scope_namespace), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_scope_namespace( + scope_namespace=fleet.Namespace(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].scope_namespace + mock_val = fleet.Namespace(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val -@pytest.mark.parametrize( - "request_type", - [ - service.GetMembershipRequest, - dict, - ], -) -def test_get_membership_rest_call_success(request_type): +def test_update_scope_namespace_flattened_error(): client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = membership.Membership( - name="name_value", - description="description_value", - external_id="external_id_value", - unique_id="unique_id_value", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_scope_namespace( + service.UpdateScopeNamespaceRequest(), + scope_namespace=fleet.Namespace(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = membership.Membership.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_membership(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, membership.Membership) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.external_id == "external_id_value" - assert response.unique_id == "unique_id_value" - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_membership_rest_interceptors(null_interceptor): - transport = transports.GkeHubRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), +@pytest.mark.asyncio +async def test_update_scope_namespace_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), ) - client = GkeHubClient(transport=transport) + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.GkeHubRestInterceptor, "post_get_membership" - ) as post, mock.patch.object( - transports.GkeHubRestInterceptor, "post_get_membership_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GkeHubRestInterceptor, "pre_get_membership" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = service.GetMembershipRequest.pb(service.GetMembershipRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = membership.Membership.to_json(membership.Membership()) - req.return_value.content = return_value - - request = service.GetMembershipRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = membership.Membership() - post_with_metadata.return_value = membership.Membership(), metadata + type(client.transport.update_scope_namespace), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - client.get_membership( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_scope_namespace( + scope_namespace=fleet.Namespace(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].scope_namespace + mock_val = fleet.Namespace(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val -def test_get_feature_rest_bad_request(request_type=service.GetFeatureRequest): - client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" +@pytest.mark.asyncio +async def test_update_scope_namespace_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/features/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_feature(request) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_scope_namespace( + service.UpdateScopeNamespaceRequest(), + scope_namespace=fleet.Namespace(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) @pytest.mark.parametrize( "request_type", [ - service.GetFeatureRequest, + service.DeleteScopeNamespaceRequest, dict, ], ) -def test_get_feature_rest_call_success(request_type): +def test_delete_scope_namespace(request_type, transport: str = "grpc"): client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/features/sample3"} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = feature.Feature( - name="name_value", - ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scope_namespace), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_scope_namespace(request) - # Convert return value to protobuf type - return_value = feature.Feature.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_feature(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.DeleteScopeNamespaceRequest() + assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, feature.Feature) - assert response.name == "name_value" + assert isinstance(response, future.Future) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_feature_rest_interceptors(null_interceptor): - transport = transports.GkeHubRestTransport( +def test_delete_scope_namespace_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.DeleteScopeNamespaceRequest( + name="name_value", ) - client = GkeHubClient(transport=transport) + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.GkeHubRestInterceptor, "post_get_feature" - ) as post, mock.patch.object( - transports.GkeHubRestInterceptor, "post_get_feature_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GkeHubRestInterceptor, "pre_get_feature" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = service.GetFeatureRequest.pb(service.GetFeatureRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } + type(client.transport.delete_scope_namespace), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_scope_namespace(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteScopeNamespaceRequest( + name="name_value", + ) - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = feature.Feature.to_json(feature.Feature()) - req.return_value.content = return_value - request = service.GetFeatureRequest() - metadata = [ - ("key", "val"), +def test_delete_scope_namespace_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_scope_namespace + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_scope_namespace + ] = mock_rpc + request = {} + client.delete_scope_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_scope_namespace(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_scope_namespace_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_scope_namespace + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_scope_namespace + ] = mock_rpc + + request = {} + await client.delete_scope_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_scope_namespace(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_scope_namespace_async( + transport: str = "grpc_asyncio", request_type=service.DeleteScopeNamespaceRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scope_namespace), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_scope_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.DeleteScopeNamespaceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_scope_namespace_async_from_dict(): + await test_delete_scope_namespace_async(request_type=dict) + + +def test_delete_scope_namespace_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteScopeNamespaceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scope_namespace), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_scope_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_scope_namespace_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteScopeNamespaceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scope_namespace), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_scope_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_scope_namespace_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scope_namespace), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_scope_namespace( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_scope_namespace_flattened_error(): + client = GkeHubClient( + credentials=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_scope_namespace( + service.DeleteScopeNamespaceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_scope_namespace_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scope_namespace), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_scope_namespace( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_scope_namespace_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_scope_namespace( + service.DeleteScopeNamespaceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListScopeNamespacesRequest, + dict, + ], +) +def test_list_scope_namespaces(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_namespaces), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListScopeNamespacesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_scope_namespaces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.ListScopeNamespacesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScopeNamespacesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_scope_namespaces_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.ListScopeNamespacesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_namespaces), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_scope_namespaces(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListScopeNamespacesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_scope_namespaces_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_scope_namespaces + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_scope_namespaces + ] = mock_rpc + request = {} + client.list_scope_namespaces(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_scope_namespaces(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_scope_namespaces_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_scope_namespaces + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_scope_namespaces + ] = mock_rpc + + request = {} + await client.list_scope_namespaces(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_scope_namespaces(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_scope_namespaces_async( + transport: str = "grpc_asyncio", request_type=service.ListScopeNamespacesRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_namespaces), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListScopeNamespacesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_scope_namespaces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.ListScopeNamespacesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScopeNamespacesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_scope_namespaces_async_from_dict(): + await test_list_scope_namespaces_async(request_type=dict) + + +def test_list_scope_namespaces_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListScopeNamespacesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_namespaces), "__call__" + ) as call: + call.return_value = service.ListScopeNamespacesResponse() + client.list_scope_namespaces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_scope_namespaces_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListScopeNamespacesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_namespaces), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListScopeNamespacesResponse() + ) + await client.list_scope_namespaces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_scope_namespaces_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_namespaces), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListScopeNamespacesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_scope_namespaces( + 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_scope_namespaces_flattened_error(): + client = GkeHubClient( + credentials=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_scope_namespaces( + service.ListScopeNamespacesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_scope_namespaces_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_namespaces), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListScopeNamespacesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListScopeNamespacesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_scope_namespaces( + 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_scope_namespaces_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_scope_namespaces( + service.ListScopeNamespacesRequest(), + parent="parent_value", + ) + + +def test_list_scope_namespaces_pager(transport_name: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_namespaces), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListScopeNamespacesResponse( + scope_namespaces=[ + fleet.Namespace(), + fleet.Namespace(), + fleet.Namespace(), + ], + next_page_token="abc", + ), + service.ListScopeNamespacesResponse( + scope_namespaces=[], + next_page_token="def", + ), + service.ListScopeNamespacesResponse( + scope_namespaces=[ + fleet.Namespace(), + ], + next_page_token="ghi", + ), + service.ListScopeNamespacesResponse( + scope_namespaces=[ + fleet.Namespace(), + fleet.Namespace(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_scope_namespaces(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, fleet.Namespace) for i in results) + + +def test_list_scope_namespaces_pages(transport_name: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_namespaces), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListScopeNamespacesResponse( + scope_namespaces=[ + fleet.Namespace(), + fleet.Namespace(), + fleet.Namespace(), + ], + next_page_token="abc", + ), + service.ListScopeNamespacesResponse( + scope_namespaces=[], + next_page_token="def", + ), + service.ListScopeNamespacesResponse( + scope_namespaces=[ + fleet.Namespace(), + ], + next_page_token="ghi", + ), + service.ListScopeNamespacesResponse( + scope_namespaces=[ + fleet.Namespace(), + fleet.Namespace(), + ], + ), + RuntimeError, + ) + pages = list(client.list_scope_namespaces(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_scope_namespaces_async_pager(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_namespaces), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListScopeNamespacesResponse( + scope_namespaces=[ + fleet.Namespace(), + fleet.Namespace(), + fleet.Namespace(), + ], + next_page_token="abc", + ), + service.ListScopeNamespacesResponse( + scope_namespaces=[], + next_page_token="def", + ), + service.ListScopeNamespacesResponse( + scope_namespaces=[ + fleet.Namespace(), + ], + next_page_token="ghi", + ), + service.ListScopeNamespacesResponse( + scope_namespaces=[ + fleet.Namespace(), + fleet.Namespace(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_scope_namespaces( + 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, fleet.Namespace) for i in responses) + + +@pytest.mark.asyncio +async def test_list_scope_namespaces_async_pages(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_namespaces), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListScopeNamespacesResponse( + scope_namespaces=[ + fleet.Namespace(), + fleet.Namespace(), + fleet.Namespace(), + ], + next_page_token="abc", + ), + service.ListScopeNamespacesResponse( + scope_namespaces=[], + next_page_token="def", + ), + service.ListScopeNamespacesResponse( + scope_namespaces=[ + fleet.Namespace(), + ], + next_page_token="ghi", + ), + service.ListScopeNamespacesResponse( + scope_namespaces=[ + fleet.Namespace(), + fleet.Namespace(), + ], + ), + 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_scope_namespaces(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", + [ + service.GetScopeRBACRoleBindingRequest, + dict, + ], +) +def test_get_scope_rbac_role_binding(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scope_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = fleet.RBACRoleBinding( + name="name_value", + uid="uid_value", + user="user_value", + ) + response = client.get_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GetScopeRBACRoleBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, fleet.RBACRoleBinding) + assert response.name == "name_value" + assert response.uid == "uid_value" + + +def test_get_scope_rbac_role_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GetScopeRBACRoleBindingRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scope_rbac_role_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_scope_rbac_role_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetScopeRBACRoleBindingRequest( + name="name_value", + ) + + +def test_get_scope_rbac_role_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_scope_rbac_role_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_scope_rbac_role_binding + ] = mock_rpc + request = {} + client.get_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_scope_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_scope_rbac_role_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_scope_rbac_role_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_scope_rbac_role_binding + ] = mock_rpc + + request = {} + await client.get_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_scope_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_scope_rbac_role_binding_async( + transport: str = "grpc_asyncio", request_type=service.GetScopeRBACRoleBindingRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scope_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fleet.RBACRoleBinding( + name="name_value", + uid="uid_value", + ) + ) + response = await client.get_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.GetScopeRBACRoleBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, fleet.RBACRoleBinding) + assert response.name == "name_value" + assert response.uid == "uid_value" + + +@pytest.mark.asyncio +async def test_get_scope_rbac_role_binding_async_from_dict(): + await test_get_scope_rbac_role_binding_async(request_type=dict) + + +def test_get_scope_rbac_role_binding_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetScopeRBACRoleBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scope_rbac_role_binding), "__call__" + ) as call: + call.return_value = fleet.RBACRoleBinding() + client.get_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_scope_rbac_role_binding_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetScopeRBACRoleBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scope_rbac_role_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fleet.RBACRoleBinding() + ) + await client.get_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_scope_rbac_role_binding_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scope_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = fleet.RBACRoleBinding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_scope_rbac_role_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_scope_rbac_role_binding_flattened_error(): + client = GkeHubClient( + credentials=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_scope_rbac_role_binding( + service.GetScopeRBACRoleBindingRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_scope_rbac_role_binding_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scope_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = fleet.RBACRoleBinding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fleet.RBACRoleBinding() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_scope_rbac_role_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_scope_rbac_role_binding_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_scope_rbac_role_binding( + service.GetScopeRBACRoleBindingRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateScopeRBACRoleBindingRequest, + dict, + ], +) +def test_create_scope_rbac_role_binding(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scope_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.CreateScopeRBACRoleBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_scope_rbac_role_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.CreateScopeRBACRoleBindingRequest( + parent="parent_value", + rbacrolebinding_id="rbacrolebinding_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scope_rbac_role_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_scope_rbac_role_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateScopeRBACRoleBindingRequest( + parent="parent_value", + rbacrolebinding_id="rbacrolebinding_id_value", + ) + + +def test_create_scope_rbac_role_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_scope_rbac_role_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_scope_rbac_role_binding + ] = mock_rpc + request = {} + client.create_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_scope_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_scope_rbac_role_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_scope_rbac_role_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_scope_rbac_role_binding + ] = mock_rpc + + request = {} + await client.create_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_scope_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_scope_rbac_role_binding_async( + transport: str = "grpc_asyncio", + request_type=service.CreateScopeRBACRoleBindingRequest, +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scope_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.CreateScopeRBACRoleBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_scope_rbac_role_binding_async_from_dict(): + await test_create_scope_rbac_role_binding_async(request_type=dict) + + +def test_create_scope_rbac_role_binding_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateScopeRBACRoleBindingRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scope_rbac_role_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_scope_rbac_role_binding_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateScopeRBACRoleBindingRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scope_rbac_role_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_scope_rbac_role_binding_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scope_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_scope_rbac_role_binding( + parent="parent_value", + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + rbacrolebinding_id="rbacrolebinding_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].rbacrolebinding + mock_val = fleet.RBACRoleBinding(user="user_value") + assert arg == mock_val + arg = args[0].rbacrolebinding_id + mock_val = "rbacrolebinding_id_value" + assert arg == mock_val + + +def test_create_scope_rbac_role_binding_flattened_error(): + client = GkeHubClient( + credentials=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_scope_rbac_role_binding( + service.CreateScopeRBACRoleBindingRequest(), + parent="parent_value", + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + rbacrolebinding_id="rbacrolebinding_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_scope_rbac_role_binding_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scope_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_scope_rbac_role_binding( + parent="parent_value", + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + rbacrolebinding_id="rbacrolebinding_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].rbacrolebinding + mock_val = fleet.RBACRoleBinding(user="user_value") + assert arg == mock_val + arg = args[0].rbacrolebinding_id + mock_val = "rbacrolebinding_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_scope_rbac_role_binding_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_scope_rbac_role_binding( + service.CreateScopeRBACRoleBindingRequest(), + parent="parent_value", + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + rbacrolebinding_id="rbacrolebinding_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateScopeRBACRoleBindingRequest, + dict, + ], +) +def test_update_scope_rbac_role_binding(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scope_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.UpdateScopeRBACRoleBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_scope_rbac_role_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.UpdateScopeRBACRoleBindingRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scope_rbac_role_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_scope_rbac_role_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateScopeRBACRoleBindingRequest() + + +def test_update_scope_rbac_role_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_scope_rbac_role_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_scope_rbac_role_binding + ] = mock_rpc + request = {} + client.update_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_scope_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_scope_rbac_role_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_scope_rbac_role_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_scope_rbac_role_binding + ] = mock_rpc + + request = {} + await client.update_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_scope_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_scope_rbac_role_binding_async( + transport: str = "grpc_asyncio", + request_type=service.UpdateScopeRBACRoleBindingRequest, +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scope_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.UpdateScopeRBACRoleBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_scope_rbac_role_binding_async_from_dict(): + await test_update_scope_rbac_role_binding_async(request_type=dict) + + +def test_update_scope_rbac_role_binding_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateScopeRBACRoleBindingRequest() + + request.rbacrolebinding.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scope_rbac_role_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "rbacrolebinding.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_scope_rbac_role_binding_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateScopeRBACRoleBindingRequest() + + request.rbacrolebinding.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scope_rbac_role_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "rbacrolebinding.name=name_value", + ) in kw["metadata"] + + +def test_update_scope_rbac_role_binding_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scope_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_scope_rbac_role_binding( + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].rbacrolebinding + mock_val = fleet.RBACRoleBinding(user="user_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_scope_rbac_role_binding_flattened_error(): + client = GkeHubClient( + credentials=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_scope_rbac_role_binding( + service.UpdateScopeRBACRoleBindingRequest(), + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_scope_rbac_role_binding_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scope_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_scope_rbac_role_binding( + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].rbacrolebinding + mock_val = fleet.RBACRoleBinding(user="user_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_scope_rbac_role_binding_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_scope_rbac_role_binding( + service.UpdateScopeRBACRoleBindingRequest(), + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteScopeRBACRoleBindingRequest, + dict, + ], +) +def test_delete_scope_rbac_role_binding(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scope_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.DeleteScopeRBACRoleBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_scope_rbac_role_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.DeleteScopeRBACRoleBindingRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scope_rbac_role_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_scope_rbac_role_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteScopeRBACRoleBindingRequest( + name="name_value", + ) + + +def test_delete_scope_rbac_role_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_scope_rbac_role_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_scope_rbac_role_binding + ] = mock_rpc + request = {} + client.delete_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_scope_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_scope_rbac_role_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_scope_rbac_role_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_scope_rbac_role_binding + ] = mock_rpc + + request = {} + await client.delete_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_scope_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_scope_rbac_role_binding_async( + transport: str = "grpc_asyncio", + request_type=service.DeleteScopeRBACRoleBindingRequest, +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scope_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.DeleteScopeRBACRoleBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_scope_rbac_role_binding_async_from_dict(): + await test_delete_scope_rbac_role_binding_async(request_type=dict) + + +def test_delete_scope_rbac_role_binding_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteScopeRBACRoleBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scope_rbac_role_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_scope_rbac_role_binding_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteScopeRBACRoleBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scope_rbac_role_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_scope_rbac_role_binding_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scope_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_scope_rbac_role_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_scope_rbac_role_binding_flattened_error(): + client = GkeHubClient( + credentials=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_scope_rbac_role_binding( + service.DeleteScopeRBACRoleBindingRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_scope_rbac_role_binding_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scope_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_scope_rbac_role_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_scope_rbac_role_binding_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_scope_rbac_role_binding( + service.DeleteScopeRBACRoleBindingRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListScopeRBACRoleBindingsRequest, + dict, + ], +) +def test_list_scope_rbac_role_bindings(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_rbac_role_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListScopeRBACRoleBindingsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_scope_rbac_role_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.ListScopeRBACRoleBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScopeRBACRoleBindingsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_scope_rbac_role_bindings_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.ListScopeRBACRoleBindingsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_rbac_role_bindings), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_scope_rbac_role_bindings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListScopeRBACRoleBindingsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_scope_rbac_role_bindings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_scope_rbac_role_bindings + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_scope_rbac_role_bindings + ] = mock_rpc + request = {} + client.list_scope_rbac_role_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_scope_rbac_role_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_scope_rbac_role_bindings_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_scope_rbac_role_bindings + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_scope_rbac_role_bindings + ] = mock_rpc + + request = {} + await client.list_scope_rbac_role_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_scope_rbac_role_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_scope_rbac_role_bindings_async( + transport: str = "grpc_asyncio", + request_type=service.ListScopeRBACRoleBindingsRequest, +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_rbac_role_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListScopeRBACRoleBindingsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_scope_rbac_role_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.ListScopeRBACRoleBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScopeRBACRoleBindingsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_scope_rbac_role_bindings_async_from_dict(): + await test_list_scope_rbac_role_bindings_async(request_type=dict) + + +def test_list_scope_rbac_role_bindings_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListScopeRBACRoleBindingsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_rbac_role_bindings), "__call__" + ) as call: + call.return_value = service.ListScopeRBACRoleBindingsResponse() + client.list_scope_rbac_role_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_scope_rbac_role_bindings_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListScopeRBACRoleBindingsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_rbac_role_bindings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListScopeRBACRoleBindingsResponse() + ) + await client.list_scope_rbac_role_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_scope_rbac_role_bindings_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_rbac_role_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListScopeRBACRoleBindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_scope_rbac_role_bindings( + 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_scope_rbac_role_bindings_flattened_error(): + client = GkeHubClient( + credentials=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_scope_rbac_role_bindings( + service.ListScopeRBACRoleBindingsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_scope_rbac_role_bindings_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_rbac_role_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListScopeRBACRoleBindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListScopeRBACRoleBindingsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_scope_rbac_role_bindings( + 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_scope_rbac_role_bindings_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_scope_rbac_role_bindings( + service.ListScopeRBACRoleBindingsRequest(), + parent="parent_value", + ) + + +def test_list_scope_rbac_role_bindings_pager(transport_name: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_rbac_role_bindings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListScopeRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + ], + next_page_token="abc", + ), + service.ListScopeRBACRoleBindingsResponse( + rbacrolebindings=[], + next_page_token="def", + ), + service.ListScopeRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + ], + next_page_token="ghi", + ), + service.ListScopeRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_scope_rbac_role_bindings( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, fleet.RBACRoleBinding) for i in results) + + +def test_list_scope_rbac_role_bindings_pages(transport_name: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_rbac_role_bindings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListScopeRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + ], + next_page_token="abc", + ), + service.ListScopeRBACRoleBindingsResponse( + rbacrolebindings=[], + next_page_token="def", + ), + service.ListScopeRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + ], + next_page_token="ghi", + ), + service.ListScopeRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + ], + ), + RuntimeError, + ) + pages = list(client.list_scope_rbac_role_bindings(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_scope_rbac_role_bindings_async_pager(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_rbac_role_bindings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListScopeRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + ], + next_page_token="abc", + ), + service.ListScopeRBACRoleBindingsResponse( + rbacrolebindings=[], + next_page_token="def", + ), + service.ListScopeRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + ], + next_page_token="ghi", + ), + service.ListScopeRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_scope_rbac_role_bindings( + 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, fleet.RBACRoleBinding) for i in responses) + + +@pytest.mark.asyncio +async def test_list_scope_rbac_role_bindings_async_pages(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_rbac_role_bindings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListScopeRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + ], + next_page_token="abc", + ), + service.ListScopeRBACRoleBindingsResponse( + rbacrolebindings=[], + next_page_token="def", + ), + service.ListScopeRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + ], + next_page_token="ghi", + ), + service.ListScopeRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + ], + ), + 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_scope_rbac_role_bindings(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", + [ + service.GetScopeRequest, + dict, + ], +) +def test_get_scope(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_scope), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = fleet.Scope( + name="name_value", + uid="uid_value", + ) + response = client.get_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GetScopeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, fleet.Scope) + assert response.name == "name_value" + assert response.uid == "uid_value" + + +def test_get_scope_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GetScopeRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_scope), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_scope(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetScopeRequest( + name="name_value", + ) + + +def test_get_scope_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_scope in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_scope] = mock_rpc + request = {} + client.get_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_scope(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_scope_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_scope + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_scope + ] = mock_rpc + + request = {} + await client.get_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_scope(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_scope_async( + transport: str = "grpc_asyncio", request_type=service.GetScopeRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_scope), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fleet.Scope( + name="name_value", + uid="uid_value", + ) + ) + response = await client.get_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.GetScopeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, fleet.Scope) + assert response.name == "name_value" + assert response.uid == "uid_value" + + +@pytest.mark.asyncio +async def test_get_scope_async_from_dict(): + await test_get_scope_async(request_type=dict) + + +def test_get_scope_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetScopeRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_scope), "__call__") as call: + call.return_value = fleet.Scope() + client.get_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_scope_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetScopeRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_scope), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fleet.Scope()) + await client.get_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_scope_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_scope), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = fleet.Scope() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_scope( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_scope_flattened_error(): + client = GkeHubClient( + credentials=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_scope( + service.GetScopeRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_scope_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_scope), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = fleet.Scope() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(fleet.Scope()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_scope( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_scope_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_scope( + service.GetScopeRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateScopeRequest, + dict, + ], +) +def test_create_scope(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scope), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.CreateScopeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_scope_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.CreateScopeRequest( + parent="parent_value", + scope_id="scope_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_scope), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_scope(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateScopeRequest( + parent="parent_value", + scope_id="scope_id_value", + ) + + +def test_create_scope_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_scope in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_scope] = mock_rpc + request = {} + client.create_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_scope(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_scope_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_scope + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_scope + ] = mock_rpc + + request = {} + await client.create_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_scope(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_scope_async( + transport: str = "grpc_asyncio", request_type=service.CreateScopeRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scope), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.CreateScopeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_scope_async_from_dict(): + await test_create_scope_async(request_type=dict) + + +def test_create_scope_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateScopeRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_scope), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_scope_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateScopeRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_scope), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_scope_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_scope), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_scope( + parent="parent_value", + scope=fleet.Scope(name="name_value"), + scope_id="scope_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].scope + mock_val = fleet.Scope(name="name_value") + assert arg == mock_val + arg = args[0].scope_id + mock_val = "scope_id_value" + assert arg == mock_val + + +def test_create_scope_flattened_error(): + client = GkeHubClient( + credentials=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_scope( + service.CreateScopeRequest(), + parent="parent_value", + scope=fleet.Scope(name="name_value"), + scope_id="scope_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_scope_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_scope), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_scope( + parent="parent_value", + scope=fleet.Scope(name="name_value"), + scope_id="scope_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].scope + mock_val = fleet.Scope(name="name_value") + assert arg == mock_val + arg = args[0].scope_id + mock_val = "scope_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_scope_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_scope( + service.CreateScopeRequest(), + parent="parent_value", + scope=fleet.Scope(name="name_value"), + scope_id="scope_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateScopeRequest, + dict, + ], +) +def test_update_scope(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_scope), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.UpdateScopeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_scope_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.UpdateScopeRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_scope), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_scope(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateScopeRequest() + + +def test_update_scope_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_scope in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_scope] = mock_rpc + request = {} + client.update_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_scope(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_scope_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_scope + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_scope + ] = mock_rpc + + request = {} + await client.update_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_scope(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_scope_async( + transport: str = "grpc_asyncio", request_type=service.UpdateScopeRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_scope), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.UpdateScopeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_scope_async_from_dict(): + await test_update_scope_async(request_type=dict) + + +def test_update_scope_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateScopeRequest() + + request.scope.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_scope), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "scope.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_scope_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateScopeRequest() + + request.scope.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_scope), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "scope.name=name_value", + ) in kw["metadata"] + + +def test_update_scope_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_scope), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_scope( + scope=fleet.Scope(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].scope + mock_val = fleet.Scope(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_scope_flattened_error(): + client = GkeHubClient( + credentials=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_scope( + service.UpdateScopeRequest(), + scope=fleet.Scope(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_scope_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_scope), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_scope( + scope=fleet.Scope(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].scope + mock_val = fleet.Scope(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_scope_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_scope( + service.UpdateScopeRequest(), + scope=fleet.Scope(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteScopeRequest, + dict, + ], +) +def test_delete_scope(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scope), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.DeleteScopeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_scope_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.DeleteScopeRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_scope), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_scope(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteScopeRequest( + name="name_value", + ) + + +def test_delete_scope_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_scope in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_scope] = mock_rpc + request = {} + client.delete_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_scope(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_scope_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_scope + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_scope + ] = mock_rpc + + request = {} + await client.delete_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_scope(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_scope_async( + transport: str = "grpc_asyncio", request_type=service.DeleteScopeRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_scope), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.DeleteScopeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_scope_async_from_dict(): + await test_delete_scope_async(request_type=dict) + + +def test_delete_scope_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteScopeRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_scope), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_scope_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteScopeRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_scope), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_scope_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_scope), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_scope( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_scope_flattened_error(): + client = GkeHubClient( + credentials=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_scope( + service.DeleteScopeRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_scope_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_scope), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_scope( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_scope_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_scope( + service.DeleteScopeRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListScopesRequest, + dict, + ], +) +def test_list_scopes(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_scopes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListScopesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_scopes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.ListScopesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScopesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_scopes_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.ListScopesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_scopes), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_scopes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListScopesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_scopes_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_scopes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_scopes] = mock_rpc + request = {} + client.list_scopes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_scopes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_scopes_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_scopes + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_scopes + ] = mock_rpc + + request = {} + await client.list_scopes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_scopes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_scopes_async( + transport: str = "grpc_asyncio", request_type=service.ListScopesRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_scopes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListScopesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_scopes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.ListScopesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScopesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_scopes_async_from_dict(): + await test_list_scopes_async(request_type=dict) + + +def test_list_scopes_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListScopesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_scopes), "__call__") as call: + call.return_value = service.ListScopesResponse() + client.list_scopes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_scopes_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListScopesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_scopes), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListScopesResponse() + ) + await client.list_scopes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_scopes_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_scopes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListScopesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_scopes( + 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_scopes_flattened_error(): + client = GkeHubClient( + credentials=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_scopes( + service.ListScopesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_scopes_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_scopes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListScopesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListScopesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_scopes( + 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_scopes_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_scopes( + service.ListScopesRequest(), + parent="parent_value", + ) + + +def test_list_scopes_pager(transport_name: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_scopes), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListScopesResponse( + scopes=[ + fleet.Scope(), + fleet.Scope(), + fleet.Scope(), + ], + next_page_token="abc", + ), + service.ListScopesResponse( + scopes=[], + next_page_token="def", + ), + service.ListScopesResponse( + scopes=[ + fleet.Scope(), + ], + next_page_token="ghi", + ), + service.ListScopesResponse( + scopes=[ + fleet.Scope(), + fleet.Scope(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_scopes(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, fleet.Scope) for i in results) + + +def test_list_scopes_pages(transport_name: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_scopes), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListScopesResponse( + scopes=[ + fleet.Scope(), + fleet.Scope(), + fleet.Scope(), + ], + next_page_token="abc", + ), + service.ListScopesResponse( + scopes=[], + next_page_token="def", + ), + service.ListScopesResponse( + scopes=[ + fleet.Scope(), + ], + next_page_token="ghi", + ), + service.ListScopesResponse( + scopes=[ + fleet.Scope(), + fleet.Scope(), + ], + ), + RuntimeError, + ) + pages = list(client.list_scopes(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_scopes_async_pager(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scopes), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListScopesResponse( + scopes=[ + fleet.Scope(), + fleet.Scope(), + fleet.Scope(), + ], + next_page_token="abc", + ), + service.ListScopesResponse( + scopes=[], + next_page_token="def", + ), + service.ListScopesResponse( + scopes=[ + fleet.Scope(), + ], + next_page_token="ghi", + ), + service.ListScopesResponse( + scopes=[ + fleet.Scope(), + fleet.Scope(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_scopes( + 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, fleet.Scope) for i in responses) + + +@pytest.mark.asyncio +async def test_list_scopes_async_pages(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scopes), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListScopesResponse( + scopes=[ + fleet.Scope(), + fleet.Scope(), + fleet.Scope(), + ], + next_page_token="abc", + ), + service.ListScopesResponse( + scopes=[], + next_page_token="def", + ), + service.ListScopesResponse( + scopes=[ + fleet.Scope(), + ], + next_page_token="ghi", + ), + service.ListScopesResponse( + scopes=[ + fleet.Scope(), + fleet.Scope(), + ], + ), + 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_scopes(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", + [ + service.ListPermittedScopesRequest, + dict, + ], +) +def test_list_permitted_scopes(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_permitted_scopes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListPermittedScopesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_permitted_scopes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.ListPermittedScopesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPermittedScopesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_permitted_scopes_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.ListPermittedScopesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_permitted_scopes), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_permitted_scopes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListPermittedScopesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_permitted_scopes_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_permitted_scopes + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_permitted_scopes + ] = mock_rpc + request = {} + client.list_permitted_scopes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_permitted_scopes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_permitted_scopes_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_permitted_scopes + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_permitted_scopes + ] = mock_rpc + + request = {} + await client.list_permitted_scopes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_permitted_scopes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_permitted_scopes_async( + transport: str = "grpc_asyncio", request_type=service.ListPermittedScopesRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_permitted_scopes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListPermittedScopesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_permitted_scopes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.ListPermittedScopesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPermittedScopesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_permitted_scopes_async_from_dict(): + await test_list_permitted_scopes_async(request_type=dict) + + +def test_list_permitted_scopes_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListPermittedScopesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_permitted_scopes), "__call__" + ) as call: + call.return_value = service.ListPermittedScopesResponse() + client.list_permitted_scopes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_permitted_scopes_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListPermittedScopesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_permitted_scopes), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListPermittedScopesResponse() + ) + await client.list_permitted_scopes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_permitted_scopes_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_permitted_scopes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListPermittedScopesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_permitted_scopes( + 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_permitted_scopes_flattened_error(): + client = GkeHubClient( + credentials=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_permitted_scopes( + service.ListPermittedScopesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_permitted_scopes_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_permitted_scopes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListPermittedScopesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListPermittedScopesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_permitted_scopes( + 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_permitted_scopes_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_permitted_scopes( + service.ListPermittedScopesRequest(), + parent="parent_value", + ) + + +def test_list_permitted_scopes_pager(transport_name: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_permitted_scopes), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListPermittedScopesResponse( + scopes=[ + fleet.Scope(), + fleet.Scope(), + fleet.Scope(), + ], + next_page_token="abc", + ), + service.ListPermittedScopesResponse( + scopes=[], + next_page_token="def", + ), + service.ListPermittedScopesResponse( + scopes=[ + fleet.Scope(), + ], + next_page_token="ghi", + ), + service.ListPermittedScopesResponse( + scopes=[ + fleet.Scope(), + fleet.Scope(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_permitted_scopes(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, fleet.Scope) for i in results) + + +def test_list_permitted_scopes_pages(transport_name: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_permitted_scopes), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListPermittedScopesResponse( + scopes=[ + fleet.Scope(), + fleet.Scope(), + fleet.Scope(), + ], + next_page_token="abc", + ), + service.ListPermittedScopesResponse( + scopes=[], + next_page_token="def", + ), + service.ListPermittedScopesResponse( + scopes=[ + fleet.Scope(), + ], + next_page_token="ghi", + ), + service.ListPermittedScopesResponse( + scopes=[ + fleet.Scope(), + fleet.Scope(), + ], + ), + RuntimeError, + ) + pages = list(client.list_permitted_scopes(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_permitted_scopes_async_pager(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_permitted_scopes), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListPermittedScopesResponse( + scopes=[ + fleet.Scope(), + fleet.Scope(), + fleet.Scope(), + ], + next_page_token="abc", + ), + service.ListPermittedScopesResponse( + scopes=[], + next_page_token="def", + ), + service.ListPermittedScopesResponse( + scopes=[ + fleet.Scope(), + ], + next_page_token="ghi", + ), + service.ListPermittedScopesResponse( + scopes=[ + fleet.Scope(), + fleet.Scope(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_permitted_scopes( + 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, fleet.Scope) for i in responses) + + +@pytest.mark.asyncio +async def test_list_permitted_scopes_async_pages(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_permitted_scopes), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListPermittedScopesResponse( + scopes=[ + fleet.Scope(), + fleet.Scope(), + fleet.Scope(), + ], + next_page_token="abc", + ), + service.ListPermittedScopesResponse( + scopes=[], + next_page_token="def", + ), + service.ListPermittedScopesResponse( + scopes=[ + fleet.Scope(), + ], + next_page_token="ghi", + ), + service.ListPermittedScopesResponse( + scopes=[ + fleet.Scope(), + fleet.Scope(), + ], + ), + 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_permitted_scopes(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", + [ + service.GetMembershipBindingRequest, + dict, + ], +) +def test_get_membership_binding(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = fleet.MembershipBinding( + name="name_value", + uid="uid_value", + scope="scope_value", + ) + response = client.get_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GetMembershipBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, fleet.MembershipBinding) + assert response.name == "name_value" + assert response.uid == "uid_value" + + +def test_get_membership_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GetMembershipBindingRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_membership_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetMembershipBindingRequest( + name="name_value", + ) + + +def test_get_membership_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_membership_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_membership_binding + ] = mock_rpc + request = {} + client.get_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_membership_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_membership_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_membership_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_membership_binding + ] = mock_rpc + + request = {} + await client.get_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_membership_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_membership_binding_async( + transport: str = "grpc_asyncio", request_type=service.GetMembershipBindingRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fleet.MembershipBinding( + name="name_value", + uid="uid_value", + ) + ) + response = await client.get_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.GetMembershipBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, fleet.MembershipBinding) + assert response.name == "name_value" + assert response.uid == "uid_value" + + +@pytest.mark.asyncio +async def test_get_membership_binding_async_from_dict(): + await test_get_membership_binding_async(request_type=dict) + + +def test_get_membership_binding_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetMembershipBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership_binding), "__call__" + ) as call: + call.return_value = fleet.MembershipBinding() + client.get_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_membership_binding_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetMembershipBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fleet.MembershipBinding() + ) + await client.get_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_membership_binding_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = fleet.MembershipBinding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_membership_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_membership_binding_flattened_error(): + client = GkeHubClient( + credentials=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_membership_binding( + service.GetMembershipBindingRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_membership_binding_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = fleet.MembershipBinding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fleet.MembershipBinding() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_membership_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_membership_binding_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_membership_binding( + service.GetMembershipBindingRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateMembershipBindingRequest, + dict, + ], +) +def test_create_membership_binding(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_membership_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.CreateMembershipBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_membership_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.CreateMembershipBindingRequest( + parent="parent_value", + membership_binding_id="membership_binding_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_membership_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateMembershipBindingRequest( + parent="parent_value", + membership_binding_id="membership_binding_id_value", + ) + + +def test_create_membership_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_membership_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_membership_binding + ] = mock_rpc + request = {} + client.create_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_membership_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_membership_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_membership_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_membership_binding + ] = mock_rpc + + request = {} + await client.create_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_membership_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_membership_binding_async( + transport: str = "grpc_asyncio", request_type=service.CreateMembershipBindingRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_membership_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.CreateMembershipBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_membership_binding_async_from_dict(): + await test_create_membership_binding_async(request_type=dict) + + +def test_create_membership_binding_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateMembershipBindingRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_membership_binding_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateMembershipBindingRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_membership_binding_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_membership_binding( + parent="parent_value", + membership_binding=fleet.MembershipBinding(scope="scope_value"), + membership_binding_id="membership_binding_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].membership_binding + mock_val = fleet.MembershipBinding(scope="scope_value") + assert arg == mock_val + arg = args[0].membership_binding_id + mock_val = "membership_binding_id_value" + assert arg == mock_val + + +def test_create_membership_binding_flattened_error(): + client = GkeHubClient( + credentials=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_membership_binding( + service.CreateMembershipBindingRequest(), + parent="parent_value", + membership_binding=fleet.MembershipBinding(scope="scope_value"), + membership_binding_id="membership_binding_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_membership_binding_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_membership_binding( + parent="parent_value", + membership_binding=fleet.MembershipBinding(scope="scope_value"), + membership_binding_id="membership_binding_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].membership_binding + mock_val = fleet.MembershipBinding(scope="scope_value") + assert arg == mock_val + arg = args[0].membership_binding_id + mock_val = "membership_binding_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_membership_binding_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_membership_binding( + service.CreateMembershipBindingRequest(), + parent="parent_value", + membership_binding=fleet.MembershipBinding(scope="scope_value"), + membership_binding_id="membership_binding_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateMembershipBindingRequest, + dict, + ], +) +def test_update_membership_binding(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.UpdateMembershipBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_membership_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.UpdateMembershipBindingRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_membership_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateMembershipBindingRequest() + + +def test_update_membership_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_membership_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_membership_binding + ] = mock_rpc + request = {} + client.update_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_membership_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_membership_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_membership_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_membership_binding + ] = mock_rpc + + request = {} + await client.update_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_membership_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_membership_binding_async( + transport: str = "grpc_asyncio", request_type=service.UpdateMembershipBindingRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.UpdateMembershipBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_membership_binding_async_from_dict(): + await test_update_membership_binding_async(request_type=dict) + + +def test_update_membership_binding_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateMembershipBindingRequest() + + request.membership_binding.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "membership_binding.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_membership_binding_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateMembershipBindingRequest() + + request.membership_binding.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "membership_binding.name=name_value", + ) in kw["metadata"] + + +def test_update_membership_binding_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_membership_binding( + membership_binding=fleet.MembershipBinding(scope="scope_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].membership_binding + mock_val = fleet.MembershipBinding(scope="scope_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_membership_binding_flattened_error(): + client = GkeHubClient( + credentials=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_membership_binding( + service.UpdateMembershipBindingRequest(), + membership_binding=fleet.MembershipBinding(scope="scope_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_membership_binding_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_membership_binding( + membership_binding=fleet.MembershipBinding(scope="scope_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].membership_binding + mock_val = fleet.MembershipBinding(scope="scope_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_membership_binding_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_membership_binding( + service.UpdateMembershipBindingRequest(), + membership_binding=fleet.MembershipBinding(scope="scope_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteMembershipBindingRequest, + dict, + ], +) +def test_delete_membership_binding(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_membership_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.DeleteMembershipBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_membership_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.DeleteMembershipBindingRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_membership_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteMembershipBindingRequest( + name="name_value", + ) + + +def test_delete_membership_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_membership_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_membership_binding + ] = mock_rpc + request = {} + client.delete_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_membership_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_membership_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_membership_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_membership_binding + ] = mock_rpc + + request = {} + await client.delete_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_membership_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_membership_binding_async( + transport: str = "grpc_asyncio", request_type=service.DeleteMembershipBindingRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_membership_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.DeleteMembershipBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_membership_binding_async_from_dict(): + await test_delete_membership_binding_async(request_type=dict) + + +def test_delete_membership_binding_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteMembershipBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_membership_binding_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteMembershipBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_membership_binding_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_membership_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_membership_binding_flattened_error(): + client = GkeHubClient( + credentials=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_membership_binding( + service.DeleteMembershipBindingRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_membership_binding_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_membership_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_membership_binding_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_membership_binding( + service.DeleteMembershipBindingRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListMembershipBindingsRequest, + dict, + ], +) +def test_list_membership_bindings(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListMembershipBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_membership_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.ListMembershipBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembershipBindingsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_membership_bindings_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.ListMembershipBindingsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_bindings), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_membership_bindings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListMembershipBindingsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + ) + + +def test_list_membership_bindings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_membership_bindings + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_membership_bindings + ] = mock_rpc + request = {} + client.list_membership_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_membership_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_membership_bindings_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_membership_bindings + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_membership_bindings + ] = mock_rpc + + request = {} + await client.list_membership_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_membership_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_membership_bindings_async( + transport: str = "grpc_asyncio", request_type=service.ListMembershipBindingsRequest +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListMembershipBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_membership_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.ListMembershipBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembershipBindingsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.asyncio +async def test_list_membership_bindings_async_from_dict(): + await test_list_membership_bindings_async(request_type=dict) + + +def test_list_membership_bindings_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListMembershipBindingsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_bindings), "__call__" + ) as call: + call.return_value = service.ListMembershipBindingsResponse() + client.list_membership_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_membership_bindings_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListMembershipBindingsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_bindings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListMembershipBindingsResponse() + ) + await client.list_membership_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_membership_bindings_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListMembershipBindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_membership_bindings( + 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_membership_bindings_flattened_error(): + client = GkeHubClient( + credentials=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_membership_bindings( + service.ListMembershipBindingsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_membership_bindings_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListMembershipBindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListMembershipBindingsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_membership_bindings( + 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_membership_bindings_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_membership_bindings( + service.ListMembershipBindingsRequest(), + parent="parent_value", + ) + + +def test_list_membership_bindings_pager(transport_name: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_bindings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListMembershipBindingsResponse( + membership_bindings=[ + fleet.MembershipBinding(), + fleet.MembershipBinding(), + fleet.MembershipBinding(), + ], + next_page_token="abc", + ), + service.ListMembershipBindingsResponse( + membership_bindings=[], + next_page_token="def", + ), + service.ListMembershipBindingsResponse( + membership_bindings=[ + fleet.MembershipBinding(), + ], + next_page_token="ghi", + ), + service.ListMembershipBindingsResponse( + membership_bindings=[ + fleet.MembershipBinding(), + fleet.MembershipBinding(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_membership_bindings( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, fleet.MembershipBinding) for i in results) + + +def test_list_membership_bindings_pages(transport_name: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_bindings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListMembershipBindingsResponse( + membership_bindings=[ + fleet.MembershipBinding(), + fleet.MembershipBinding(), + fleet.MembershipBinding(), + ], + next_page_token="abc", + ), + service.ListMembershipBindingsResponse( + membership_bindings=[], + next_page_token="def", + ), + service.ListMembershipBindingsResponse( + membership_bindings=[ + fleet.MembershipBinding(), + ], + next_page_token="ghi", + ), + service.ListMembershipBindingsResponse( + membership_bindings=[ + fleet.MembershipBinding(), + fleet.MembershipBinding(), + ], + ), + RuntimeError, + ) + pages = list(client.list_membership_bindings(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_membership_bindings_async_pager(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_bindings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListMembershipBindingsResponse( + membership_bindings=[ + fleet.MembershipBinding(), + fleet.MembershipBinding(), + fleet.MembershipBinding(), + ], + next_page_token="abc", + ), + service.ListMembershipBindingsResponse( + membership_bindings=[], + next_page_token="def", + ), + service.ListMembershipBindingsResponse( + membership_bindings=[ + fleet.MembershipBinding(), + ], + next_page_token="ghi", + ), + service.ListMembershipBindingsResponse( + membership_bindings=[ + fleet.MembershipBinding(), + fleet.MembershipBinding(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_membership_bindings( + 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, fleet.MembershipBinding) for i in responses) + + +@pytest.mark.asyncio +async def test_list_membership_bindings_async_pages(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_bindings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListMembershipBindingsResponse( + membership_bindings=[ + fleet.MembershipBinding(), + fleet.MembershipBinding(), + fleet.MembershipBinding(), + ], + next_page_token="abc", + ), + service.ListMembershipBindingsResponse( + membership_bindings=[], + next_page_token="def", + ), + service.ListMembershipBindingsResponse( + membership_bindings=[ + fleet.MembershipBinding(), + ], + next_page_token="ghi", + ), + service.ListMembershipBindingsResponse( + membership_bindings=[ + fleet.MembershipBinding(), + fleet.MembershipBinding(), + ], + ), + 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_membership_bindings(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", + [ + service.GetMembershipRBACRoleBindingRequest, + dict, + ], +) +def test_get_membership_rbac_role_binding(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = fleet.RBACRoleBinding( + name="name_value", + uid="uid_value", + user="user_value", + ) + response = client.get_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GetMembershipRBACRoleBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, fleet.RBACRoleBinding) + assert response.name == "name_value" + assert response.uid == "uid_value" + + +def test_get_membership_rbac_role_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GetMembershipRBACRoleBindingRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership_rbac_role_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_membership_rbac_role_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetMembershipRBACRoleBindingRequest( + name="name_value", + ) + + +def test_get_membership_rbac_role_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_membership_rbac_role_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_membership_rbac_role_binding + ] = mock_rpc + request = {} + client.get_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_membership_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_membership_rbac_role_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_membership_rbac_role_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_membership_rbac_role_binding + ] = mock_rpc + + request = {} + await client.get_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_membership_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_membership_rbac_role_binding_async( + transport: str = "grpc_asyncio", + request_type=service.GetMembershipRBACRoleBindingRequest, +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fleet.RBACRoleBinding( + name="name_value", + uid="uid_value", + ) + ) + response = await client.get_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.GetMembershipRBACRoleBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, fleet.RBACRoleBinding) + assert response.name == "name_value" + assert response.uid == "uid_value" + + +@pytest.mark.asyncio +async def test_get_membership_rbac_role_binding_async_from_dict(): + await test_get_membership_rbac_role_binding_async(request_type=dict) + + +def test_get_membership_rbac_role_binding_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetMembershipRBACRoleBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership_rbac_role_binding), "__call__" + ) as call: + call.return_value = fleet.RBACRoleBinding() + client.get_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_membership_rbac_role_binding_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetMembershipRBACRoleBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership_rbac_role_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fleet.RBACRoleBinding() + ) + await client.get_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_membership_rbac_role_binding_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = fleet.RBACRoleBinding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_membership_rbac_role_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_membership_rbac_role_binding_flattened_error(): + client = GkeHubClient( + credentials=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_membership_rbac_role_binding( + service.GetMembershipRBACRoleBindingRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_membership_rbac_role_binding_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_membership_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = fleet.RBACRoleBinding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fleet.RBACRoleBinding() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_membership_rbac_role_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_membership_rbac_role_binding_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_membership_rbac_role_binding( + service.GetMembershipRBACRoleBindingRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateMembershipRBACRoleBindingRequest, + dict, + ], +) +def test_create_membership_rbac_role_binding(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_membership_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.CreateMembershipRBACRoleBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_membership_rbac_role_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.CreateMembershipRBACRoleBindingRequest( + parent="parent_value", + rbacrolebinding_id="rbacrolebinding_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership_rbac_role_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_membership_rbac_role_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateMembershipRBACRoleBindingRequest( + parent="parent_value", + rbacrolebinding_id="rbacrolebinding_id_value", + ) + + +def test_create_membership_rbac_role_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_membership_rbac_role_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_membership_rbac_role_binding + ] = mock_rpc + request = {} + client.create_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_membership_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_membership_rbac_role_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_membership_rbac_role_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_membership_rbac_role_binding + ] = mock_rpc + + request = {} + await client.create_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_membership_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_membership_rbac_role_binding_async( + transport: str = "grpc_asyncio", + request_type=service.CreateMembershipRBACRoleBindingRequest, +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_membership_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.CreateMembershipRBACRoleBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_membership_rbac_role_binding_async_from_dict(): + await test_create_membership_rbac_role_binding_async(request_type=dict) + + +def test_create_membership_rbac_role_binding_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateMembershipRBACRoleBindingRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership_rbac_role_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_membership_rbac_role_binding_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateMembershipRBACRoleBindingRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership_rbac_role_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_membership_rbac_role_binding_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_membership_rbac_role_binding( + parent="parent_value", + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + rbacrolebinding_id="rbacrolebinding_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].rbacrolebinding + mock_val = fleet.RBACRoleBinding(user="user_value") + assert arg == mock_val + arg = args[0].rbacrolebinding_id + mock_val = "rbacrolebinding_id_value" + assert arg == mock_val + + +def test_create_membership_rbac_role_binding_flattened_error(): + client = GkeHubClient( + credentials=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_membership_rbac_role_binding( + service.CreateMembershipRBACRoleBindingRequest(), + parent="parent_value", + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + rbacrolebinding_id="rbacrolebinding_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_membership_rbac_role_binding_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_membership_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_membership_rbac_role_binding( + parent="parent_value", + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + rbacrolebinding_id="rbacrolebinding_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].rbacrolebinding + mock_val = fleet.RBACRoleBinding(user="user_value") + assert arg == mock_val + arg = args[0].rbacrolebinding_id + mock_val = "rbacrolebinding_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_membership_rbac_role_binding_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_membership_rbac_role_binding( + service.CreateMembershipRBACRoleBindingRequest(), + parent="parent_value", + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + rbacrolebinding_id="rbacrolebinding_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateMembershipRBACRoleBindingRequest, + dict, + ], +) +def test_update_membership_rbac_role_binding(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.UpdateMembershipRBACRoleBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_membership_rbac_role_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.UpdateMembershipRBACRoleBindingRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership_rbac_role_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_membership_rbac_role_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateMembershipRBACRoleBindingRequest() + + +def test_update_membership_rbac_role_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_membership_rbac_role_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_membership_rbac_role_binding + ] = mock_rpc + request = {} + client.update_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_membership_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_membership_rbac_role_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_membership_rbac_role_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_membership_rbac_role_binding + ] = mock_rpc + + request = {} + await client.update_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.update_membership_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_membership_rbac_role_binding_async( + transport: str = "grpc_asyncio", + request_type=service.UpdateMembershipRBACRoleBindingRequest, +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.UpdateMembershipRBACRoleBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_membership_rbac_role_binding_async_from_dict(): + await test_update_membership_rbac_role_binding_async(request_type=dict) + + +def test_update_membership_rbac_role_binding_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateMembershipRBACRoleBindingRequest() + + request.rbacrolebinding.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership_rbac_role_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "rbacrolebinding.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_membership_rbac_role_binding_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateMembershipRBACRoleBindingRequest() + + request.rbacrolebinding.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership_rbac_role_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "rbacrolebinding.name=name_value", + ) in kw["metadata"] + + +def test_update_membership_rbac_role_binding_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_membership_rbac_role_binding( + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].rbacrolebinding + mock_val = fleet.RBACRoleBinding(user="user_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_membership_rbac_role_binding_flattened_error(): + client = GkeHubClient( + credentials=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_membership_rbac_role_binding( + service.UpdateMembershipRBACRoleBindingRequest(), + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_membership_rbac_role_binding_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_membership_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_membership_rbac_role_binding( + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].rbacrolebinding + mock_val = fleet.RBACRoleBinding(user="user_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_membership_rbac_role_binding_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_membership_rbac_role_binding( + service.UpdateMembershipRBACRoleBindingRequest(), + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteMembershipRBACRoleBindingRequest, + dict, + ], +) +def test_delete_membership_rbac_role_binding(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_membership_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.DeleteMembershipRBACRoleBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_membership_rbac_role_binding_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.DeleteMembershipRBACRoleBindingRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership_rbac_role_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_membership_rbac_role_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteMembershipRBACRoleBindingRequest( + name="name_value", + ) + + +def test_delete_membership_rbac_role_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_membership_rbac_role_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_membership_rbac_role_binding + ] = mock_rpc + request = {} + client.delete_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_membership_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_membership_rbac_role_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_membership_rbac_role_binding + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_membership_rbac_role_binding + ] = mock_rpc + + request = {} + await client.delete_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_membership_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_membership_rbac_role_binding_async( + transport: str = "grpc_asyncio", + request_type=service.DeleteMembershipRBACRoleBindingRequest, +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_membership_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.DeleteMembershipRBACRoleBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_membership_rbac_role_binding_async_from_dict(): + await test_delete_membership_rbac_role_binding_async(request_type=dict) + + +def test_delete_membership_rbac_role_binding_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteMembershipRBACRoleBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership_rbac_role_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_membership_rbac_role_binding_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteMembershipRBACRoleBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership_rbac_role_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_membership_rbac_role_binding_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_membership_rbac_role_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert 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_membership_rbac_role_binding_flattened_error(): + client = GkeHubClient( + credentials=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_membership_rbac_role_binding( + service.DeleteMembershipRBACRoleBindingRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_membership_rbac_role_binding_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_membership_rbac_role_binding( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_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_membership_rbac_role_binding_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_membership_rbac_role_binding( + service.DeleteMembershipRBACRoleBindingRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListMembershipRBACRoleBindingsRequest, + dict, + ], +) +def test_list_membership_rbac_role_bindings(request_type, transport: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_rbac_role_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListMembershipRBACRoleBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_membership_rbac_role_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.ListMembershipRBACRoleBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembershipRBACRoleBindingsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_membership_rbac_role_bindings_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.ListMembershipRBACRoleBindingsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_rbac_role_bindings), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_membership_rbac_role_bindings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListMembershipRBACRoleBindingsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_membership_rbac_role_bindings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_membership_rbac_role_bindings + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_membership_rbac_role_bindings + ] = mock_rpc + request = {} + client.list_membership_rbac_role_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_membership_rbac_role_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_membership_rbac_role_bindings_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_membership_rbac_role_bindings + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_membership_rbac_role_bindings + ] = mock_rpc + + request = {} + await client.list_membership_rbac_role_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_membership_rbac_role_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_membership_rbac_role_bindings_async( + transport: str = "grpc_asyncio", + request_type=service.ListMembershipRBACRoleBindingsRequest, +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_rbac_role_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListMembershipRBACRoleBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_membership_rbac_role_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.ListMembershipRBACRoleBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembershipRBACRoleBindingsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.asyncio +async def test_list_membership_rbac_role_bindings_async_from_dict(): + await test_list_membership_rbac_role_bindings_async(request_type=dict) + + +def test_list_membership_rbac_role_bindings_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListMembershipRBACRoleBindingsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_rbac_role_bindings), "__call__" + ) as call: + call.return_value = service.ListMembershipRBACRoleBindingsResponse() + client.list_membership_rbac_role_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header 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_membership_rbac_role_bindings_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListMembershipRBACRoleBindingsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_rbac_role_bindings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListMembershipRBACRoleBindingsResponse() + ) + await client.list_membership_rbac_role_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_membership_rbac_role_bindings_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_rbac_role_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListMembershipRBACRoleBindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_membership_rbac_role_bindings( + 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_membership_rbac_role_bindings_flattened_error(): + client = GkeHubClient( + credentials=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_membership_rbac_role_bindings( + service.ListMembershipRBACRoleBindingsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_membership_rbac_role_bindings_flattened_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_rbac_role_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListMembershipRBACRoleBindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListMembershipRBACRoleBindingsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_membership_rbac_role_bindings( + 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_membership_rbac_role_bindings_flattened_error_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_membership_rbac_role_bindings( + service.ListMembershipRBACRoleBindingsRequest(), + parent="parent_value", + ) + + +def test_list_membership_rbac_role_bindings_pager(transport_name: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_rbac_role_bindings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListMembershipRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + ], + next_page_token="abc", + ), + service.ListMembershipRBACRoleBindingsResponse( + rbacrolebindings=[], + next_page_token="def", + ), + service.ListMembershipRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + ], + next_page_token="ghi", + ), + service.ListMembershipRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_membership_rbac_role_bindings( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, fleet.RBACRoleBinding) for i in results) + + +def test_list_membership_rbac_role_bindings_pages(transport_name: str = "grpc"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_rbac_role_bindings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListMembershipRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + ], + next_page_token="abc", + ), + service.ListMembershipRBACRoleBindingsResponse( + rbacrolebindings=[], + next_page_token="def", + ), + service.ListMembershipRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + ], + next_page_token="ghi", + ), + service.ListMembershipRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + ], + ), + RuntimeError, + ) + pages = list(client.list_membership_rbac_role_bindings(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_membership_rbac_role_bindings_async_pager(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_rbac_role_bindings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListMembershipRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + ], + next_page_token="abc", + ), + service.ListMembershipRBACRoleBindingsResponse( + rbacrolebindings=[], + next_page_token="def", + ), + service.ListMembershipRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + ], + next_page_token="ghi", + ), + service.ListMembershipRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_membership_rbac_role_bindings( + 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, fleet.RBACRoleBinding) for i in responses) + + +@pytest.mark.asyncio +async def test_list_membership_rbac_role_bindings_async_pages(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_rbac_role_bindings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListMembershipRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + ], + next_page_token="abc", + ), + service.ListMembershipRBACRoleBindingsResponse( + rbacrolebindings=[], + next_page_token="def", + ), + service.ListMembershipRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + ], + next_page_token="ghi", + ), + service.ListMembershipRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + ], + ), + 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_membership_rbac_role_bindings(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", + [ + service.GenerateMembershipRBACRoleBindingYAMLRequest, + dict, + ], +) +def test_generate_membership_rbac_role_binding_yaml( + request_type, transport: str = "grpc" +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_membership_rbac_role_binding_yaml), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.GenerateMembershipRBACRoleBindingYAMLResponse( + role_bindings_yaml="role_bindings_yaml_value", + ) + response = client.generate_membership_rbac_role_binding_yaml(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GenerateMembershipRBACRoleBindingYAMLRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateMembershipRBACRoleBindingYAMLResponse) + assert response.role_bindings_yaml == "role_bindings_yaml_value" + + +def test_generate_membership_rbac_role_binding_yaml_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GenerateMembershipRBACRoleBindingYAMLRequest( + parent="parent_value", + rbacrolebinding_id="rbacrolebinding_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_membership_rbac_role_binding_yaml), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.generate_membership_rbac_role_binding_yaml(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GenerateMembershipRBACRoleBindingYAMLRequest( + parent="parent_value", + rbacrolebinding_id="rbacrolebinding_id_value", + ) + + +def test_generate_membership_rbac_role_binding_yaml_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.generate_membership_rbac_role_binding_yaml + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.generate_membership_rbac_role_binding_yaml + ] = mock_rpc + request = {} + client.generate_membership_rbac_role_binding_yaml(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_membership_rbac_role_binding_yaml(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_generate_membership_rbac_role_binding_yaml_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.generate_membership_rbac_role_binding_yaml + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.generate_membership_rbac_role_binding_yaml + ] = mock_rpc + + request = {} + await client.generate_membership_rbac_role_binding_yaml(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.generate_membership_rbac_role_binding_yaml(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_generate_membership_rbac_role_binding_yaml_async( + transport: str = "grpc_asyncio", + request_type=service.GenerateMembershipRBACRoleBindingYAMLRequest, +): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_membership_rbac_role_binding_yaml), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.GenerateMembershipRBACRoleBindingYAMLResponse( + role_bindings_yaml="role_bindings_yaml_value", + ) + ) + response = await client.generate_membership_rbac_role_binding_yaml(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.GenerateMembershipRBACRoleBindingYAMLRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateMembershipRBACRoleBindingYAMLResponse) + assert response.role_bindings_yaml == "role_bindings_yaml_value" + + +@pytest.mark.asyncio +async def test_generate_membership_rbac_role_binding_yaml_async_from_dict(): + await test_generate_membership_rbac_role_binding_yaml_async(request_type=dict) + + +def test_generate_membership_rbac_role_binding_yaml_field_headers(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GenerateMembershipRBACRoleBindingYAMLRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_membership_rbac_role_binding_yaml), "__call__" + ) as call: + call.return_value = service.GenerateMembershipRBACRoleBindingYAMLResponse() + client.generate_membership_rbac_role_binding_yaml(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_generate_membership_rbac_role_binding_yaml_field_headers_async(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GenerateMembershipRBACRoleBindingYAMLRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_membership_rbac_role_binding_yaml), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.GenerateMembershipRBACRoleBindingYAMLResponse() + ) + await client.generate_membership_rbac_role_binding_yaml(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish 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_memberships_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_memberships in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_memberships + ] = mock_rpc + + request = {} + client.list_memberships(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_memberships(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_memberships_rest_required_fields( + request_type=service.ListMembershipsRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_memberships._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_memberships._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListMembershipsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListMembershipsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_memberships(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_memberships_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_memberships._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_memberships_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListMembershipsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListMembershipsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_memberships(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/memberships" + % client.transport._host, + args[1], + ) + + +def test_list_memberships_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_memberships( + service.ListMembershipsRequest(), + parent="parent_value", + ) + + +def test_list_memberships_rest_pager(transport: str = "rest"): + client = GkeHubClient( + 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 = ( + service.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token="abc", + ), + service.ListMembershipsResponse( + resources=[], + next_page_token="def", + ), + service.ListMembershipsResponse( + resources=[ + membership.Membership(), + ], + next_page_token="ghi", + ), + service.ListMembershipsResponse( + resources=[ + membership.Membership(), + membership.Membership(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListMembershipsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_memberships(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, membership.Membership) for i in results) + + pages = list(client.list_memberships(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_bound_memberships_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_bound_memberships + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_bound_memberships + ] = mock_rpc + + request = {} + client.list_bound_memberships(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_bound_memberships(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_bound_memberships_rest_required_fields( + request_type=service.ListBoundMembershipsRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["scope_name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_bound_memberships._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["scopeName"] = "scope_name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_bound_memberships._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "scopeName" in jsonified_request + assert jsonified_request["scopeName"] == "scope_name_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListBoundMembershipsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListBoundMembershipsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_bound_memberships(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_bound_memberships_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_bound_memberships._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("scopeName",)) + ) + + +def test_list_bound_memberships_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListBoundMembershipsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "scope_name": "projects/sample1/locations/sample2/scopes/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + scope_name="scope_name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListBoundMembershipsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_bound_memberships(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{scope_name=projects/*/locations/*/scopes/*}:listMemberships" + % client.transport._host, + args[1], + ) + + +def test_list_bound_memberships_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_bound_memberships( + service.ListBoundMembershipsRequest(), + scope_name="scope_name_value", + ) + + +def test_list_bound_memberships_rest_pager(transport: str = "rest"): + client = GkeHubClient( + 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 = ( + service.ListBoundMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + membership.Membership(), + ], + next_page_token="abc", + ), + service.ListBoundMembershipsResponse( + memberships=[], + next_page_token="def", + ), + service.ListBoundMembershipsResponse( + memberships=[ + membership.Membership(), + ], + next_page_token="ghi", + ), + service.ListBoundMembershipsResponse( + memberships=[ + membership.Membership(), + membership.Membership(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListBoundMembershipsResponse.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 = { + "scope_name": "projects/sample1/locations/sample2/scopes/sample3" + } + + pager = client.list_bound_memberships(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, membership.Membership) for i in results) + + pages = list(client.list_bound_memberships(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_features_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_features in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_features] = mock_rpc + + request = {} + client.list_features(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_features(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_features_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListFeaturesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListFeaturesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_features(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/features" % client.transport._host, + args[1], + ) + + +def test_list_features_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_features( + service.ListFeaturesRequest(), + parent="parent_value", + ) + + +def test_list_features_rest_pager(transport: str = "rest"): + client = GkeHubClient( + 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 = ( + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + feature.Feature(), + ], + next_page_token="abc", + ), + service.ListFeaturesResponse( + resources=[], + next_page_token="def", + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + ], + next_page_token="ghi", + ), + service.ListFeaturesResponse( + resources=[ + feature.Feature(), + feature.Feature(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListFeaturesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_features(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, feature.Feature) for i in results) + + pages = list(client.list_features(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_membership_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_membership in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_membership] = mock_rpc + + request = {} + client.get_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_membership(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_membership_rest_required_fields(request_type=service.GetMembershipRequest): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = membership.Membership() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_membership(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_membership_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_membership._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_membership_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = membership.Membership() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/memberships/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_membership(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/memberships/*}" + % client.transport._host, + args[1], + ) + + +def test_get_membership_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_membership( + service.GetMembershipRequest(), + name="name_value", + ) + + +def test_get_feature_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_feature in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_feature] = mock_rpc + + request = {} + client.get_feature(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_feature(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_feature_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = feature.Feature() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/features/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = feature.Feature.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_feature(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/features/*}" % client.transport._host, + args[1], + ) + + +def test_get_feature_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_feature( + service.GetFeatureRequest(), + name="name_value", + ) + + +def test_create_membership_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_membership in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_membership + ] = mock_rpc + + request = {} + client.create_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_membership(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_membership_rest_required_fields( + request_type=service.CreateMembershipRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["membership_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "membershipId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "membershipId" in jsonified_request + assert jsonified_request["membershipId"] == request_init["membership_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["membershipId"] = "membership_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_membership._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "membership_id", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "membershipId" in jsonified_request + assert jsonified_request["membershipId"] == "membership_id_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_membership(request) + + expected_params = [ + ( + "membershipId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_membership_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_membership._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "membershipId", + "requestId", + ) + ) + & set( + ( + "parent", + "membershipId", + "resource", + ) + ) + ) + + +def test_create_membership_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + resource=membership.Membership( + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster( + resource_link="resource_link_value" + ) + ) + ), + membership_id="membership_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_membership(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/memberships" + % client.transport._host, + args[1], + ) + + +def test_create_membership_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_membership( + service.CreateMembershipRequest(), + parent="parent_value", + resource=membership.Membership( + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster( + resource_link="resource_link_value" + ) + ) + ), + membership_id="membership_id_value", + ) + + +def test_create_feature_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_feature in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_feature] = mock_rpc + + request = {} + client.create_feature(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_feature(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_feature_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + resource=feature.Feature(name="name_value"), + feature_id="feature_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_feature(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/features" % client.transport._host, + args[1], + ) + + +def test_create_feature_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_feature( + service.CreateFeatureRequest(), + parent="parent_value", + resource=feature.Feature(name="name_value"), + feature_id="feature_id_value", + ) + + +def test_delete_membership_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_membership in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_membership + ] = mock_rpc + + request = {} + client.delete_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_membership(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_membership_rest_required_fields( + request_type=service.DeleteMembershipRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_membership._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "force", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_membership(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_membership_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_membership._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "force", + "requestId", + ) + ) + & set(("name",)) + ) + + +def test_delete_membership_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/memberships/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_membership(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/memberships/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_membership_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_membership( + service.DeleteMembershipRequest(), + name="name_value", + ) + + +def test_delete_feature_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_feature in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_feature] = mock_rpc + + request = {} + client.delete_feature(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_feature(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_feature_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/features/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_feature(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/features/*}" % client.transport._host, + args[1], + ) + + +def test_delete_feature_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_feature( + service.DeleteFeatureRequest(), + name="name_value", + ) + + +def test_update_membership_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_membership in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_membership + ] = mock_rpc + + request = {} + client.update_membership(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_membership(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_membership_rest_required_fields( + request_type=service.UpdateMembershipRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_membership._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_membership._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_membership(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_membership_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_membership._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set( + ( + "name", + "updateMask", + "resource", + ) + ) + ) + + +def test_update_membership_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/memberships/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + resource=membership.Membership( + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster( + resource_link="resource_link_value" + ) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_membership(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/memberships/*}" + % client.transport._host, + args[1], + ) + + +def test_update_membership_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_membership( + service.UpdateMembershipRequest(), + name="name_value", + resource=membership.Membership( + endpoint=membership.MembershipEndpoint( + gke_cluster=membership.GkeCluster( + resource_link="resource_link_value" + ) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_feature_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_feature in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_feature] = mock_rpc + + request = {} + client.update_feature(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_feature(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_feature_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/features/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + resource=feature.Feature(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_feature(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/features/*}" % client.transport._host, + args[1], + ) + + +def test_update_feature_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_feature( + service.UpdateFeatureRequest(), + name="name_value", + resource=feature.Feature(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_generate_connect_manifest_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.generate_connect_manifest + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.generate_connect_manifest + ] = mock_rpc + + request = {} + client.generate_connect_manifest(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_connect_manifest(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_connect_manifest_rest_required_fields( + request_type=service.GenerateConnectManifestRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).generate_connect_manifest._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).generate_connect_manifest._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "image_pull_secret_content", + "is_upgrade", + "namespace", + "proxy", + "registry", + "version", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.GenerateConnectManifestResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.GenerateConnectManifestResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.generate_connect_manifest(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_generate_connect_manifest_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.generate_connect_manifest._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "imagePullSecretContent", + "isUpgrade", + "namespace", + "proxy", + "registry", + "version", + ) + ) + & set(("name",)) + ) + + +def test_create_fleet_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_fleet in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_fleet] = mock_rpc + + request = {} + client.create_fleet(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_fleet(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_fleet_rest_required_fields(request_type=service.CreateFleetRequest): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_fleet._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_fleet._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 = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_fleet(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_fleet_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_fleet._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "fleet", + ) + ) + ) + + +def test_create_fleet_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + fleet=gcg_fleet.Fleet(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_fleet(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/fleets" % client.transport._host, + args[1], + ) + + +def test_create_fleet_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_fleet( + service.CreateFleetRequest(), + parent="parent_value", + fleet=gcg_fleet.Fleet(name="name_value"), + ) + + +def test_get_fleet_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_fleet in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_fleet] = mock_rpc + + request = {} + client.get_fleet(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_fleet(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_fleet_rest_required_fields(request_type=service.GetFleetRequest): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_fleet._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_fleet._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = fleet.Fleet() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = fleet.Fleet.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_fleet(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_fleet_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_fleet._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_fleet_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = fleet.Fleet() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/fleets/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = fleet.Fleet.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_fleet(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/fleets/*}" % client.transport._host, + args[1], + ) + + +def test_get_fleet_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_fleet( + service.GetFleetRequest(), + name="name_value", + ) + + +def test_update_fleet_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_fleet in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_fleet] = mock_rpc + + request = {} + client.update_fleet(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_fleet(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_fleet_rest_required_fields(request_type=service.UpdateFleetRequest): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_fleet._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_fleet._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_fleet(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_fleet_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_fleet._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "fleet", + "updateMask", + ) + ) + ) + + +def test_update_fleet_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "fleet": {"name": "projects/sample1/locations/sample2/fleets/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + fleet=gcg_fleet.Fleet(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_fleet(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{fleet.name=projects/*/locations/*/fleets/*}" + % client.transport._host, + args[1], + ) + + +def test_update_fleet_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_fleet( + service.UpdateFleetRequest(), + fleet=gcg_fleet.Fleet(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_fleet_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_fleet in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_fleet] = mock_rpc + + request = {} + client.delete_fleet(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_fleet(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_fleet_rest_required_fields(request_type=service.DeleteFleetRequest): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_fleet._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_fleet._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_fleet(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_fleet_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_fleet._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_fleet_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/fleets/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_fleet(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/fleets/*}" % client.transport._host, + args[1], + ) + + +def test_delete_fleet_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_fleet( + service.DeleteFleetRequest(), + name="name_value", + ) + + +def test_list_fleets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_fleets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_fleets] = mock_rpc + + request = {} + client.list_fleets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_fleets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_fleets_rest_required_fields(request_type=service.ListFleetsRequest): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_fleets._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_fleets._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 = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListFleetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListFleetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_fleets(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_fleets_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_fleets._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_fleets_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListFleetsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListFleetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_fleets(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/fleets" % client.transport._host, + args[1], + ) + + +def test_list_fleets_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_fleets( + service.ListFleetsRequest(), + parent="parent_value", + ) + + +def test_list_fleets_rest_pager(transport: str = "rest"): + client = GkeHubClient( + 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 = ( + service.ListFleetsResponse( + fleets=[ + fleet.Fleet(), + fleet.Fleet(), + fleet.Fleet(), + ], + next_page_token="abc", + ), + service.ListFleetsResponse( + fleets=[], + next_page_token="def", + ), + service.ListFleetsResponse( + fleets=[ + fleet.Fleet(), + ], + next_page_token="ghi", + ), + service.ListFleetsResponse( + fleets=[ + fleet.Fleet(), + fleet.Fleet(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListFleetsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_fleets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, fleet.Fleet) for i in results) + + pages = list(client.list_fleets(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_scope_namespace_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_scope_namespace in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_scope_namespace + ] = mock_rpc + + request = {} + client.get_scope_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_scope_namespace(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_scope_namespace_rest_required_fields( + request_type=service.GetScopeNamespaceRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_scope_namespace._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_scope_namespace._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = fleet.Namespace() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = fleet.Namespace.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_scope_namespace(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_scope_namespace_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_scope_namespace._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_scope_namespace_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = fleet.Namespace() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/scopes/sample3/namespaces/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = fleet.Namespace.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_scope_namespace(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/scopes/*/namespaces/*}" + % client.transport._host, + args[1], + ) + + +def test_get_scope_namespace_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_scope_namespace( + service.GetScopeNamespaceRequest(), + name="name_value", + ) + + +def test_create_scope_namespace_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_scope_namespace + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_scope_namespace + ] = mock_rpc + + request = {} + client.create_scope_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_scope_namespace(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_scope_namespace_rest_required_fields( + request_type=service.CreateScopeNamespaceRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["scope_namespace_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "scopeNamespaceId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_scope_namespace._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "scopeNamespaceId" in jsonified_request + assert jsonified_request["scopeNamespaceId"] == request_init["scope_namespace_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["scopeNamespaceId"] = "scope_namespace_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_scope_namespace._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("scope_namespace_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "scopeNamespaceId" in jsonified_request + assert jsonified_request["scopeNamespaceId"] == "scope_namespace_id_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_scope_namespace(request) + + expected_params = [ + ( + "scopeNamespaceId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_scope_namespace_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_scope_namespace._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("scopeNamespaceId",)) + & set( + ( + "parent", + "scopeNamespaceId", + "scopeNamespace", + ) + ) + ) + + +def test_create_scope_namespace_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/scopes/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + scope_namespace=fleet.Namespace(name="name_value"), + scope_namespace_id="scope_namespace_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_scope_namespace(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/scopes/*}/namespaces" + % client.transport._host, + args[1], + ) + + +def test_create_scope_namespace_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_scope_namespace( + service.CreateScopeNamespaceRequest(), + parent="parent_value", + scope_namespace=fleet.Namespace(name="name_value"), + scope_namespace_id="scope_namespace_id_value", + ) + + +def test_update_scope_namespace_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_scope_namespace + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_scope_namespace + ] = mock_rpc + + request = {} + client.update_scope_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_scope_namespace(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_scope_namespace_rest_required_fields( + request_type=service.UpdateScopeNamespaceRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_scope_namespace._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_scope_namespace._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_scope_namespace(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_scope_namespace_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_scope_namespace._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "scopeNamespace", + "updateMask", + ) + ) + ) + + +def test_update_scope_namespace_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "scope_namespace": { + "name": "projects/sample1/locations/sample2/scopes/sample3/namespaces/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + scope_namespace=fleet.Namespace(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_scope_namespace(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{scope_namespace.name=projects/*/locations/*/scopes/*/namespaces/*}" + % client.transport._host, + args[1], + ) + + +def test_update_scope_namespace_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_scope_namespace( + service.UpdateScopeNamespaceRequest(), + scope_namespace=fleet.Namespace(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_scope_namespace_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_scope_namespace + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_scope_namespace + ] = mock_rpc + + request = {} + client.delete_scope_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_scope_namespace(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_scope_namespace_rest_required_fields( + request_type=service.DeleteScopeNamespaceRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_scope_namespace._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_scope_namespace._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_scope_namespace(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_scope_namespace_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_scope_namespace._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_scope_namespace_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/scopes/sample3/namespaces/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_scope_namespace(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/scopes/*/namespaces/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_scope_namespace_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_scope_namespace( + service.DeleteScopeNamespaceRequest(), + name="name_value", + ) + + +def test_list_scope_namespaces_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_scope_namespaces + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_scope_namespaces + ] = mock_rpc + + request = {} + client.list_scope_namespaces(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_scope_namespaces(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_scope_namespaces_rest_required_fields( + request_type=service.ListScopeNamespacesRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_scope_namespaces._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_scope_namespaces._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 = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListScopeNamespacesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListScopeNamespacesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_scope_namespaces(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_scope_namespaces_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_scope_namespaces._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_scope_namespaces_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListScopeNamespacesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/scopes/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListScopeNamespacesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_scope_namespaces(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/scopes/*}/namespaces" + % client.transport._host, + args[1], + ) + + +def test_list_scope_namespaces_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_scope_namespaces( + service.ListScopeNamespacesRequest(), + parent="parent_value", + ) + + +def test_list_scope_namespaces_rest_pager(transport: str = "rest"): + client = GkeHubClient( + 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 = ( + service.ListScopeNamespacesResponse( + scope_namespaces=[ + fleet.Namespace(), + fleet.Namespace(), + fleet.Namespace(), + ], + next_page_token="abc", + ), + service.ListScopeNamespacesResponse( + scope_namespaces=[], + next_page_token="def", + ), + service.ListScopeNamespacesResponse( + scope_namespaces=[ + fleet.Namespace(), + ], + next_page_token="ghi", + ), + service.ListScopeNamespacesResponse( + scope_namespaces=[ + fleet.Namespace(), + fleet.Namespace(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListScopeNamespacesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2/scopes/sample3"} + + pager = client.list_scope_namespaces(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, fleet.Namespace) for i in results) + + pages = list(client.list_scope_namespaces(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_scope_rbac_role_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_scope_rbac_role_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_scope_rbac_role_binding + ] = mock_rpc + + request = {} + client.get_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_scope_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_scope_rbac_role_binding_rest_required_fields( + request_type=service.GetScopeRBACRoleBindingRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_scope_rbac_role_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_scope_rbac_role_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = fleet.RBACRoleBinding() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = fleet.RBACRoleBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_scope_rbac_role_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_scope_rbac_role_binding_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_scope_rbac_role_binding._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_scope_rbac_role_binding_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = fleet.RBACRoleBinding() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/scopes/sample3/rbacrolebindings/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = fleet.RBACRoleBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_scope_rbac_role_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/scopes/*/rbacrolebindings/*}" + % client.transport._host, + args[1], + ) + + +def test_get_scope_rbac_role_binding_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_scope_rbac_role_binding( + service.GetScopeRBACRoleBindingRequest(), + name="name_value", + ) + + +def test_create_scope_rbac_role_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_scope_rbac_role_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_scope_rbac_role_binding + ] = mock_rpc + + request = {} + client.create_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_scope_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_scope_rbac_role_binding_rest_required_fields( + request_type=service.CreateScopeRBACRoleBindingRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["rbacrolebinding_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "rbacrolebindingId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_scope_rbac_role_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "rbacrolebindingId" in jsonified_request + assert jsonified_request["rbacrolebindingId"] == request_init["rbacrolebinding_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["rbacrolebindingId"] = "rbacrolebinding_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_scope_rbac_role_binding._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("rbacrolebinding_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "rbacrolebindingId" in jsonified_request + assert jsonified_request["rbacrolebindingId"] == "rbacrolebinding_id_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_scope_rbac_role_binding(request) + + expected_params = [ + ( + "rbacrolebindingId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_scope_rbac_role_binding_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_scope_rbac_role_binding._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(("rbacrolebindingId",)) + & set( + ( + "parent", + "rbacrolebindingId", + "rbacrolebinding", + ) + ) + ) + + +def test_create_scope_rbac_role_binding_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/scopes/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + rbacrolebinding_id="rbacrolebinding_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_scope_rbac_role_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/scopes/*}/rbacrolebindings" + % client.transport._host, + args[1], + ) + + +def test_create_scope_rbac_role_binding_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_scope_rbac_role_binding( + service.CreateScopeRBACRoleBindingRequest(), + parent="parent_value", + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + rbacrolebinding_id="rbacrolebinding_id_value", + ) + + +def test_update_scope_rbac_role_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_scope_rbac_role_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_scope_rbac_role_binding + ] = mock_rpc + + request = {} + client.update_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_scope_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_scope_rbac_role_binding_rest_required_fields( + request_type=service.UpdateScopeRBACRoleBindingRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_scope_rbac_role_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_scope_rbac_role_binding._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_scope_rbac_role_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_scope_rbac_role_binding_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_scope_rbac_role_binding._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "rbacrolebinding", + "updateMask", + ) + ) + ) + + +def test_update_scope_rbac_role_binding_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "rbacrolebinding": { + "name": "projects/sample1/locations/sample2/scopes/sample3/rbacrolebindings/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_scope_rbac_role_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{rbacrolebinding.name=projects/*/locations/*/scopes/*/rbacrolebindings/*}" + % client.transport._host, + args[1], + ) + + +def test_update_scope_rbac_role_binding_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_scope_rbac_role_binding( + service.UpdateScopeRBACRoleBindingRequest(), + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_scope_rbac_role_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_scope_rbac_role_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_scope_rbac_role_binding + ] = mock_rpc + + request = {} + client.delete_scope_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_scope_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_scope_rbac_role_binding_rest_required_fields( + request_type=service.DeleteScopeRBACRoleBindingRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_scope_rbac_role_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_scope_rbac_role_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_scope_rbac_role_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_scope_rbac_role_binding_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_scope_rbac_role_binding._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_scope_rbac_role_binding_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/scopes/sample3/rbacrolebindings/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_scope_rbac_role_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/scopes/*/rbacrolebindings/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_scope_rbac_role_binding_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_scope_rbac_role_binding( + service.DeleteScopeRBACRoleBindingRequest(), + name="name_value", + ) + + +def test_list_scope_rbac_role_bindings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_scope_rbac_role_bindings + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_scope_rbac_role_bindings + ] = mock_rpc + + request = {} + client.list_scope_rbac_role_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_scope_rbac_role_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_scope_rbac_role_bindings_rest_required_fields( + request_type=service.ListScopeRBACRoleBindingsRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_scope_rbac_role_bindings._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_scope_rbac_role_bindings._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 = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListScopeRBACRoleBindingsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListScopeRBACRoleBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_scope_rbac_role_bindings(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_scope_rbac_role_bindings_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_scope_rbac_role_bindings._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_scope_rbac_role_bindings_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListScopeRBACRoleBindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/scopes/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListScopeRBACRoleBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_scope_rbac_role_bindings(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/scopes/*}/rbacrolebindings" + % client.transport._host, + args[1], + ) + + +def test_list_scope_rbac_role_bindings_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_scope_rbac_role_bindings( + service.ListScopeRBACRoleBindingsRequest(), + parent="parent_value", + ) + + +def test_list_scope_rbac_role_bindings_rest_pager(transport: str = "rest"): + client = GkeHubClient( + 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 = ( + service.ListScopeRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + ], + next_page_token="abc", + ), + service.ListScopeRBACRoleBindingsResponse( + rbacrolebindings=[], + next_page_token="def", + ), + service.ListScopeRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + ], + next_page_token="ghi", + ), + service.ListScopeRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListScopeRBACRoleBindingsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2/scopes/sample3"} + + pager = client.list_scope_rbac_role_bindings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, fleet.RBACRoleBinding) for i in results) + + pages = list(client.list_scope_rbac_role_bindings(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_scope_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_scope in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_scope] = mock_rpc + + request = {} + client.get_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_scope(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_scope_rest_required_fields(request_type=service.GetScopeRequest): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_scope._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_scope._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = fleet.Scope() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = fleet.Scope.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_scope(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_scope_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_scope._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_scope_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = fleet.Scope() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/scopes/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = fleet.Scope.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_scope(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/scopes/*}" % client.transport._host, + args[1], + ) + + +def test_get_scope_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_scope( + service.GetScopeRequest(), + name="name_value", + ) + + +def test_create_scope_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_scope in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_scope] = mock_rpc + + request = {} + client.create_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_scope(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_scope_rest_required_fields(request_type=service.CreateScopeRequest): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["scope_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "scopeId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_scope._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "scopeId" in jsonified_request + assert jsonified_request["scopeId"] == request_init["scope_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["scopeId"] = "scope_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_scope._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("scope_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "scopeId" in jsonified_request + assert jsonified_request["scopeId"] == "scope_id_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_scope(request) + + expected_params = [ + ( + "scopeId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_scope_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_scope._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("scopeId",)) + & set( + ( + "parent", + "scopeId", + "scope", + ) + ) + ) + + +def test_create_scope_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + scope=fleet.Scope(name="name_value"), + scope_id="scope_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_scope(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/scopes" % client.transport._host, + args[1], + ) + + +def test_create_scope_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_scope( + service.CreateScopeRequest(), + parent="parent_value", + scope=fleet.Scope(name="name_value"), + scope_id="scope_id_value", + ) + + +def test_update_scope_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_scope in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_scope] = mock_rpc + + request = {} + client.update_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_scope(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_scope_rest_required_fields(request_type=service.UpdateScopeRequest): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_scope._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_scope._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_scope(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_scope_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_scope._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "scope", + "updateMask", + ) + ) + ) + + +def test_update_scope_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "scope": {"name": "projects/sample1/locations/sample2/scopes/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + scope=fleet.Scope(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_scope(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{scope.name=projects/*/locations/*/scopes/*}" + % client.transport._host, + args[1], + ) + + +def test_update_scope_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_scope( + service.UpdateScopeRequest(), + scope=fleet.Scope(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_scope_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_scope in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_scope] = mock_rpc + + request = {} + client.delete_scope(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_scope(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_scope_rest_required_fields(request_type=service.DeleteScopeRequest): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_scope._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_scope._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_scope(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_scope_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_scope._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_scope_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/scopes/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_scope(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/scopes/*}" % client.transport._host, + args[1], + ) + + +def test_delete_scope_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_scope( + service.DeleteScopeRequest(), + name="name_value", + ) + + +def test_list_scopes_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_scopes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_scopes] = mock_rpc + + request = {} + client.list_scopes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_scopes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_scopes_rest_required_fields(request_type=service.ListScopesRequest): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_scopes._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_scopes._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 = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListScopesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListScopesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_scopes(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_scopes_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_scopes._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_scopes_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListScopesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListScopesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_scopes(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/scopes" % client.transport._host, + args[1], + ) + + +def test_list_scopes_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_scopes( + service.ListScopesRequest(), + parent="parent_value", + ) + + +def test_list_scopes_rest_pager(transport: str = "rest"): + client = GkeHubClient( + 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 = ( + service.ListScopesResponse( + scopes=[ + fleet.Scope(), + fleet.Scope(), + fleet.Scope(), + ], + next_page_token="abc", + ), + service.ListScopesResponse( + scopes=[], + next_page_token="def", + ), + service.ListScopesResponse( + scopes=[ + fleet.Scope(), + ], + next_page_token="ghi", + ), + service.ListScopesResponse( + scopes=[ + fleet.Scope(), + fleet.Scope(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListScopesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_scopes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, fleet.Scope) for i in results) + + pages = list(client.list_scopes(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_permitted_scopes_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_permitted_scopes + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_permitted_scopes + ] = mock_rpc + + request = {} + client.list_permitted_scopes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_permitted_scopes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_permitted_scopes_rest_required_fields( + request_type=service.ListPermittedScopesRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_permitted_scopes._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_permitted_scopes._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 = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListPermittedScopesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListPermittedScopesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_permitted_scopes(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_permitted_scopes_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_permitted_scopes._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_permitted_scopes_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListPermittedScopesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListPermittedScopesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_permitted_scopes(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/scopes:listPermitted" + % client.transport._host, + args[1], + ) + + +def test_list_permitted_scopes_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_permitted_scopes( + service.ListPermittedScopesRequest(), + parent="parent_value", + ) + + +def test_list_permitted_scopes_rest_pager(transport: str = "rest"): + client = GkeHubClient( + 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 = ( + service.ListPermittedScopesResponse( + scopes=[ + fleet.Scope(), + fleet.Scope(), + fleet.Scope(), + ], + next_page_token="abc", + ), + service.ListPermittedScopesResponse( + scopes=[], + next_page_token="def", + ), + service.ListPermittedScopesResponse( + scopes=[ + fleet.Scope(), + ], + next_page_token="ghi", + ), + service.ListPermittedScopesResponse( + scopes=[ + fleet.Scope(), + fleet.Scope(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListPermittedScopesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_permitted_scopes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, fleet.Scope) for i in results) + + pages = list(client.list_permitted_scopes(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_membership_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_membership_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_membership_binding + ] = mock_rpc + + request = {} + client.get_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_membership_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_membership_binding_rest_required_fields( + request_type=service.GetMembershipBindingRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_membership_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_membership_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = fleet.MembershipBinding() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = fleet.MembershipBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_membership_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_membership_binding_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_membership_binding._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_membership_binding_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = fleet.MembershipBinding() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/memberships/sample3/bindings/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = fleet.MembershipBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_membership_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/memberships/*/bindings/*}" + % client.transport._host, + args[1], + ) + + +def test_get_membership_binding_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_membership_binding( + service.GetMembershipBindingRequest(), + name="name_value", + ) + + +def test_create_membership_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_membership_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_membership_binding + ] = mock_rpc + + request = {} + client.create_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_membership_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_membership_binding_rest_required_fields( + request_type=service.CreateMembershipBindingRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["membership_binding_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "membershipBindingId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_membership_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "membershipBindingId" in jsonified_request + assert ( + jsonified_request["membershipBindingId"] + == request_init["membership_binding_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["membershipBindingId"] = "membership_binding_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_membership_binding._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("membership_binding_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "membershipBindingId" in jsonified_request + assert jsonified_request["membershipBindingId"] == "membership_binding_id_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_membership_binding(request) + + expected_params = [ + ( + "membershipBindingId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_membership_binding_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_membership_binding._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("membershipBindingId",)) + & set( + ( + "parent", + "membershipBinding", + "membershipBindingId", + ) + ) + ) + + +def test_create_membership_binding_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/memberships/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + membership_binding=fleet.MembershipBinding(scope="scope_value"), + membership_binding_id="membership_binding_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_membership_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/memberships/*}/bindings" + % client.transport._host, + args[1], + ) + + +def test_create_membership_binding_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_membership_binding( + service.CreateMembershipBindingRequest(), + parent="parent_value", + membership_binding=fleet.MembershipBinding(scope="scope_value"), + membership_binding_id="membership_binding_id_value", + ) + + +def test_update_membership_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_membership_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_membership_binding + ] = mock_rpc + + request = {} + client.update_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_membership_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_membership_binding_rest_required_fields( + request_type=service.UpdateMembershipBindingRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_membership_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_membership_binding._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_membership_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_membership_binding_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_membership_binding._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "membershipBinding", + "updateMask", + ) + ) + ) + + +def test_update_membership_binding_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "membership_binding": { + "name": "projects/sample1/locations/sample2/memberships/sample3/bindings/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + membership_binding=fleet.MembershipBinding(scope="scope_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_membership_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{membership_binding.name=projects/*/locations/*/memberships/*/bindings/*}" + % client.transport._host, + args[1], + ) + + +def test_update_membership_binding_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_membership_binding( + service.UpdateMembershipBindingRequest(), + membership_binding=fleet.MembershipBinding(scope="scope_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_membership_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_membership_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_membership_binding + ] = mock_rpc + + request = {} + client.delete_membership_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_membership_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_membership_binding_rest_required_fields( + request_type=service.DeleteMembershipBindingRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_membership_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_membership_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_membership_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_membership_binding_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_membership_binding._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_membership_binding_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/memberships/sample3/bindings/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_membership_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/memberships/*/bindings/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_membership_binding_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_membership_binding( + service.DeleteMembershipBindingRequest(), + name="name_value", + ) + + +def test_list_membership_bindings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_membership_bindings + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_membership_bindings + ] = mock_rpc + + request = {} + client.list_membership_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_membership_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_membership_bindings_rest_required_fields( + request_type=service.ListMembershipBindingsRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_membership_bindings._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_membership_bindings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListMembershipBindingsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListMembershipBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_membership_bindings(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_membership_bindings_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_membership_bindings._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_membership_bindings_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListMembershipBindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/memberships/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListMembershipBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_membership_bindings(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/memberships/*}/bindings" + % client.transport._host, + args[1], + ) + + +def test_list_membership_bindings_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_membership_bindings( + service.ListMembershipBindingsRequest(), + parent="parent_value", + ) + + +def test_list_membership_bindings_rest_pager(transport: str = "rest"): + client = GkeHubClient( + 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 = ( + service.ListMembershipBindingsResponse( + membership_bindings=[ + fleet.MembershipBinding(), + fleet.MembershipBinding(), + fleet.MembershipBinding(), + ], + next_page_token="abc", + ), + service.ListMembershipBindingsResponse( + membership_bindings=[], + next_page_token="def", + ), + service.ListMembershipBindingsResponse( + membership_bindings=[ + fleet.MembershipBinding(), + ], + next_page_token="ghi", + ), + service.ListMembershipBindingsResponse( + membership_bindings=[ + fleet.MembershipBinding(), + fleet.MembershipBinding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListMembershipBindingsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/memberships/sample3" + } + + pager = client.list_membership_bindings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, fleet.MembershipBinding) for i in results) + + pages = list(client.list_membership_bindings(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_membership_rbac_role_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_membership_rbac_role_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_membership_rbac_role_binding + ] = mock_rpc + + request = {} + client.get_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_membership_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_membership_rbac_role_binding_rest_required_fields( + request_type=service.GetMembershipRBACRoleBindingRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_membership_rbac_role_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_membership_rbac_role_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = fleet.RBACRoleBinding() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = fleet.RBACRoleBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_membership_rbac_role_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_membership_rbac_role_binding_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.get_membership_rbac_role_binding._get_unset_required_fields({}) + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_membership_rbac_role_binding_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = fleet.RBACRoleBinding() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/memberships/sample3/rbacrolebindings/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = fleet.RBACRoleBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_membership_rbac_role_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/memberships/*/rbacrolebindings/*}" + % client.transport._host, + args[1], + ) + + +def test_get_membership_rbac_role_binding_rest_flattened_error(transport: str = "rest"): + client = GkeHubClient( + credentials=ga_credentials.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_membership_rbac_role_binding( + service.GetMembershipRBACRoleBindingRequest(), + name="name_value", + ) + + +def test_create_membership_rbac_role_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_membership_rbac_role_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_membership_rbac_role_binding + ] = mock_rpc + + request = {} + client.create_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_membership_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_membership_rbac_role_binding_rest_required_fields( + request_type=service.CreateMembershipRBACRoleBindingRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["rbacrolebinding_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "rbacrolebindingId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_membership_rbac_role_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "rbacrolebindingId" in jsonified_request + assert jsonified_request["rbacrolebindingId"] == request_init["rbacrolebinding_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["rbacrolebindingId"] = "rbacrolebinding_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_membership_rbac_role_binding._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("rbacrolebinding_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "rbacrolebindingId" in jsonified_request + assert jsonified_request["rbacrolebindingId"] == "rbacrolebinding_id_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_membership_rbac_role_binding(request) + + expected_params = [ + ( + "rbacrolebindingId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_membership_rbac_role_binding_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.create_membership_rbac_role_binding._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set(("rbacrolebindingId",)) + & set( + ( + "parent", + "rbacrolebindingId", + "rbacrolebinding", + ) + ) + ) + + +def test_create_membership_rbac_role_binding_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/memberships/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + rbacrolebinding_id="rbacrolebinding_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_membership_rbac_role_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/memberships/*}/rbacrolebindings" + % client.transport._host, + args[1], + ) + + +def test_create_membership_rbac_role_binding_rest_flattened_error( + transport: str = "rest", +): + client = GkeHubClient( + credentials=ga_credentials.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_membership_rbac_role_binding( + service.CreateMembershipRBACRoleBindingRequest(), + parent="parent_value", + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + rbacrolebinding_id="rbacrolebinding_id_value", + ) + + +def test_update_membership_rbac_role_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_membership_rbac_role_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_membership_rbac_role_binding + ] = mock_rpc + + request = {} + client.update_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_membership_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_membership_rbac_role_binding_rest_required_fields( + request_type=service.UpdateMembershipRBACRoleBindingRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_membership_rbac_role_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_membership_rbac_role_binding._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_membership_rbac_role_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_membership_rbac_role_binding_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.update_membership_rbac_role_binding._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "rbacrolebinding", + "updateMask", + ) + ) + ) + + +def test_update_membership_rbac_role_binding_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "rbacrolebinding": { + "name": "projects/sample1/locations/sample2/memberships/sample3/rbacrolebindings/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_membership_rbac_role_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{rbacrolebinding.name=projects/*/locations/*/memberships/*/rbacrolebindings/*}" + % client.transport._host, + args[1], + ) + + +def test_update_membership_rbac_role_binding_rest_flattened_error( + transport: str = "rest", +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_membership_rbac_role_binding( + service.UpdateMembershipRBACRoleBindingRequest(), + rbacrolebinding=fleet.RBACRoleBinding(user="user_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_membership_rbac_role_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_membership_rbac_role_binding + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_membership_rbac_role_binding + ] = mock_rpc + + request = {} + client.delete_membership_rbac_role_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_membership_rbac_role_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_membership_rbac_role_binding_rest_required_fields( + request_type=service.DeleteMembershipRBACRoleBindingRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_membership_rbac_role_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_membership_rbac_role_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_membership_rbac_role_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_membership_rbac_role_binding_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.delete_membership_rbac_role_binding._get_unset_required_fields({}) + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_membership_rbac_role_binding_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/memberships/sample3/rbacrolebindings/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_membership_rbac_role_binding(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/memberships/*/rbacrolebindings/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_membership_rbac_role_binding_rest_flattened_error( + transport: str = "rest", +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_membership_rbac_role_binding( + service.DeleteMembershipRBACRoleBindingRequest(), + name="name_value", + ) + + +def test_list_membership_rbac_role_bindings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_membership_rbac_role_bindings + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_membership_rbac_role_bindings + ] = mock_rpc + + request = {} + client.list_membership_rbac_role_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_membership_rbac_role_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_membership_rbac_role_bindings_rest_required_fields( + request_type=service.ListMembershipRBACRoleBindingsRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_membership_rbac_role_bindings._get_unset_required_fields(jsonified_request) + jsonified_request.update(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_membership_rbac_role_bindings._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 = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListMembershipRBACRoleBindingsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListMembershipRBACRoleBindingsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_membership_rbac_role_bindings(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_membership_rbac_role_bindings_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.list_membership_rbac_role_bindings._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_membership_rbac_role_bindings_rest_flattened(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListMembershipRBACRoleBindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/memberships/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListMembershipRBACRoleBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_membership_rbac_role_bindings(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/memberships/*}/rbacrolebindings" + % client.transport._host, + args[1], + ) + + +def test_list_membership_rbac_role_bindings_rest_flattened_error( + transport: str = "rest", +): + client = GkeHubClient( + credentials=ga_credentials.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_membership_rbac_role_bindings( + service.ListMembershipRBACRoleBindingsRequest(), + parent="parent_value", + ) + + +def test_list_membership_rbac_role_bindings_rest_pager(transport: str = "rest"): + client = GkeHubClient( + 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 = ( + service.ListMembershipRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + ], + next_page_token="abc", + ), + service.ListMembershipRBACRoleBindingsResponse( + rbacrolebindings=[], + next_page_token="def", + ), + service.ListMembershipRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + ], + next_page_token="ghi", + ), + service.ListMembershipRBACRoleBindingsResponse( + rbacrolebindings=[ + fleet.RBACRoleBinding(), + fleet.RBACRoleBinding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListMembershipRBACRoleBindingsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/memberships/sample3" + } + + pager = client.list_membership_rbac_role_bindings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, fleet.RBACRoleBinding) for i in results) + + pages = list( + client.list_membership_rbac_role_bindings(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_generate_membership_rbac_role_binding_yaml_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.generate_membership_rbac_role_binding_yaml + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.generate_membership_rbac_role_binding_yaml + ] = mock_rpc + + request = {} + client.generate_membership_rbac_role_binding_yaml(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_membership_rbac_role_binding_yaml(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_membership_rbac_role_binding_yaml_rest_required_fields( + request_type=service.GenerateMembershipRBACRoleBindingYAMLRequest, +): + transport_class = transports.GkeHubRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["rbacrolebinding_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "rbacrolebindingId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).generate_membership_rbac_role_binding_yaml._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "rbacrolebindingId" in jsonified_request + assert jsonified_request["rbacrolebindingId"] == request_init["rbacrolebinding_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["rbacrolebindingId"] = "rbacrolebinding_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).generate_membership_rbac_role_binding_yaml._get_unset_required_fields( + jsonified_request + ) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("rbacrolebinding_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "rbacrolebindingId" in jsonified_request + assert jsonified_request["rbacrolebindingId"] == "rbacrolebinding_id_value" + + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.GenerateMembershipRBACRoleBindingYAMLResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "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 = service.GenerateMembershipRBACRoleBindingYAMLResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.generate_membership_rbac_role_binding_yaml(request) + + expected_params = [ + ( + "rbacrolebindingId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_generate_membership_rbac_role_binding_yaml_rest_unset_required_fields(): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.generate_membership_rbac_role_binding_yaml._get_unset_required_fields( + {} + ) + ) + assert set(unset_fields) == ( + set(("rbacrolebindingId",)) + & set( + ( + "parent", + "rbacrolebindingId", + "rbacrolebinding", + ) + ) + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.GkeHubGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.GkeHubGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GkeHubClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.GkeHubGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = GkeHubClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = GkeHubClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.GkeHubGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GkeHubClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.GkeHubGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = GkeHubClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.GkeHubGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.GkeHubGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GkeHubGrpcTransport, + transports.GkeHubGrpcAsyncIOTransport, + transports.GkeHubRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = GkeHubClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_memberships_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_memberships), "__call__") as call: + call.return_value = service.ListMembershipsResponse() + client.list_memberships(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListMembershipsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_bound_memberships_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_bound_memberships), "__call__" + ) as call: + call.return_value = service.ListBoundMembershipsResponse() + client.list_bound_memberships(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListBoundMembershipsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_features_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_features), "__call__") as call: + call.return_value = service.ListFeaturesResponse() + client.list_features(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListFeaturesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_membership_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_membership), "__call__") as call: + call.return_value = membership.Membership() + client.get_membership(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetMembershipRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_feature_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_feature), "__call__") as call: + call.return_value = feature.Feature() + client.get_feature(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetFeatureRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_membership_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_membership(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateMembershipRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_feature_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_feature), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_feature(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateFeatureRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_membership_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_membership(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteMembershipRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_feature_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_feature), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_feature(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteFeatureRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_membership_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_membership), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_membership(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateMembershipRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_feature_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_feature), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_feature(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateFeatureRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_connect_manifest_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_connect_manifest), "__call__" + ) as call: + call.return_value = service.GenerateConnectManifestResponse() + client.generate_connect_manifest(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GenerateConnectManifestRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_fleet_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_fleet), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_fleet(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateFleetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_fleet_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_fleet), "__call__") as call: + call.return_value = fleet.Fleet() + client.get_fleet(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetFleetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_fleet_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_fleet), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_fleet(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateFleetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_fleet_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_fleet), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_fleet(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteFleetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_fleets_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_fleets), "__call__") as call: + call.return_value = service.ListFleetsResponse() + client.list_fleets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListFleetsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_scope_namespace_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scope_namespace), "__call__" + ) as call: + call.return_value = fleet.Namespace() + client.get_scope_namespace(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetScopeNamespaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_scope_namespace_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_scope_namespace), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_scope_namespace(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateScopeNamespaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_scope_namespace_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_scope_namespace), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_scope_namespace(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateScopeNamespaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_scope_namespace_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_scope_namespace), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_scope_namespace(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteScopeNamespaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_scope_namespaces_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_namespaces), "__call__" + ) as call: + call.return_value = service.ListScopeNamespacesResponse() + client.list_scope_namespaces(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListScopeNamespacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_scope_rbac_role_binding_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scope_rbac_role_binding), "__call__" + ) as call: + call.return_value = fleet.RBACRoleBinding() + client.get_scope_rbac_role_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetScopeRBACRoleBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_scope_rbac_role_binding_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_scope_rbac_role_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_scope_rbac_role_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateScopeRBACRoleBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_scope_rbac_role_binding_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_scope_rbac_role_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_scope_rbac_role_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateScopeRBACRoleBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_scope_rbac_role_binding_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_scope_rbac_role_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_scope_rbac_role_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteScopeRBACRoleBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_scope_rbac_role_bindings_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_rbac_role_bindings), "__call__" + ) as call: + call.return_value = service.ListScopeRBACRoleBindingsResponse() + client.list_scope_rbac_role_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListScopeRBACRoleBindingsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_scope_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_scope), "__call__") as call: + call.return_value = fleet.Scope() + client.get_scope(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetScopeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_scope_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_scope), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_scope(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateScopeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_scope_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_scope), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_scope(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateScopeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_scope_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_scope), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_scope(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteScopeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_scopes_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_scopes), "__call__") as call: + call.return_value = service.ListScopesResponse() + client.list_scopes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListScopesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_permitted_scopes_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_permitted_scopes), "__call__" + ) as call: + call.return_value = service.ListPermittedScopesResponse() + client.list_permitted_scopes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListPermittedScopesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_membership_binding_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_membership_binding), "__call__" + ) as call: + call.return_value = fleet.MembershipBinding() + client.get_membership_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetMembershipBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_membership_binding_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_membership_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_membership_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateMembershipBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_membership_binding_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_membership_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_membership_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateMembershipBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_membership_binding_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_membership_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteMembershipBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_membership_bindings_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_bindings), "__call__" + ) as call: + call.return_value = service.ListMembershipBindingsResponse() + client.list_membership_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListMembershipBindingsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_membership_rbac_role_binding_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_membership_rbac_role_binding), "__call__" + ) as call: + call.return_value = fleet.RBACRoleBinding() + client.get_membership_rbac_role_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetMembershipRBACRoleBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_membership_rbac_role_binding_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_membership_rbac_role_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_membership_rbac_role_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateMembershipRBACRoleBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_membership_rbac_role_binding_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_membership_rbac_role_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_membership_rbac_role_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateMembershipRBACRoleBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_membership_rbac_role_binding_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership_rbac_role_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_membership_rbac_role_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteMembershipRBACRoleBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_membership_rbac_role_bindings_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_rbac_role_bindings), "__call__" + ) as call: + call.return_value = service.ListMembershipRBACRoleBindingsResponse() + client.list_membership_rbac_role_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListMembershipRBACRoleBindingsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_membership_rbac_role_binding_yaml_empty_call_grpc(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_membership_rbac_role_binding_yaml), "__call__" + ) as call: + call.return_value = service.GenerateMembershipRBACRoleBindingYAMLResponse() + client.generate_membership_rbac_role_binding_yaml(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GenerateMembershipRBACRoleBindingYAMLRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = GkeHubAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_memberships_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_memberships), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListMembershipsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_memberships(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListMembershipsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_bound_memberships_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_bound_memberships), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListBoundMembershipsResponse( + unreachable=["unreachable_value"], + next_page_token="next_page_token_value", + ) + ) + await client.list_bound_memberships(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListBoundMembershipsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_features_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_features), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListFeaturesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_features(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListFeaturesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_membership_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_membership), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + membership.Membership( + name="name_value", + description="description_value", + external_id="external_id_value", + unique_id="unique_id_value", + ) + ) + await client.get_membership(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetMembershipRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_feature_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_feature), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + feature.Feature( + name="name_value", + unreachable=["unreachable_value"], + ) + ) + await client.get_feature(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetFeatureRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_membership_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_membership), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_membership(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateMembershipRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_feature_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_feature), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_feature(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateFeatureRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_membership_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_membership(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteMembershipRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_feature_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_feature), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_feature(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteFeatureRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_membership_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_membership), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_membership(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateMembershipRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_feature_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_feature), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_feature(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateFeatureRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_generate_connect_manifest_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_connect_manifest), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.GenerateConnectManifestResponse() + ) + await client.generate_connect_manifest(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GenerateConnectManifestRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_fleet_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_fleet), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_fleet(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateFleetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_fleet_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_fleet), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fleet.Fleet( + name="name_value", + display_name="display_name_value", + uid="uid_value", + ) + ) + await client.get_fleet(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetFleetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_fleet_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_fleet), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_fleet(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateFleetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_fleet_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_fleet), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_fleet(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteFleetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_fleets_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_fleets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListFleetsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_fleets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListFleetsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_scope_namespace_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scope_namespace), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fleet.Namespace( + name="name_value", + uid="uid_value", + scope="scope_value", + ) + ) + await client.get_scope_namespace(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetScopeNamespaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_scope_namespace_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_scope_namespace), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_scope_namespace(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateScopeNamespaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_scope_namespace_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_scope_namespace), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_scope_namespace(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateScopeNamespaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_scope_namespace_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_scope_namespace), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_scope_namespace(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteScopeNamespaceRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_scope_namespaces_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_namespaces), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListScopeNamespacesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_scope_namespaces(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListScopeNamespacesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_scope_rbac_role_binding_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scope_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fleet.RBACRoleBinding( + name="name_value", + uid="uid_value", + ) + ) + await client.get_scope_rbac_role_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetScopeRBACRoleBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_scope_rbac_role_binding_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_scope_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_scope_rbac_role_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateScopeRBACRoleBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_scope_rbac_role_binding_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_scope_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_scope_rbac_role_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateScopeRBACRoleBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_scope_rbac_role_binding_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_scope_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_scope_rbac_role_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteScopeRBACRoleBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_scope_rbac_role_bindings_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_rbac_role_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListScopeRBACRoleBindingsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_scope_rbac_role_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListScopeRBACRoleBindingsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_scope_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_scope), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fleet.Scope( + name="name_value", + uid="uid_value", + ) + ) + await client.get_scope(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetScopeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_scope_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_scope), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_scope(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateScopeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_scope_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_scope), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_scope(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateScopeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_scope_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_scope), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_scope(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteScopeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_scopes_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_scopes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListScopesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_scopes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListScopesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_permitted_scopes_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_permitted_scopes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListPermittedScopesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_permitted_scopes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListPermittedScopesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_membership_binding_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_membership_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fleet.MembershipBinding( + name="name_value", + uid="uid_value", + ) + ) + await client.get_membership_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetMembershipBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_membership_binding_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_membership_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_membership_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateMembershipBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_membership_binding_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_membership_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_membership_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateMembershipBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_membership_binding_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_membership_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteMembershipBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_membership_bindings_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListMembershipBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_membership_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListMembershipBindingsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_membership_rbac_role_binding_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_membership_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fleet.RBACRoleBinding( + name="name_value", + uid="uid_value", + ) + ) + await client.get_membership_rbac_role_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetMembershipRBACRoleBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_membership_rbac_role_binding_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_membership_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_membership_rbac_role_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateMembershipRBACRoleBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_membership_rbac_role_binding_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_membership_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_membership_rbac_role_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateMembershipRBACRoleBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_membership_rbac_role_binding_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership_rbac_role_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_membership_rbac_role_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteMembershipRBACRoleBindingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_membership_rbac_role_bindings_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_membership_rbac_role_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListMembershipRBACRoleBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_membership_rbac_role_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListMembershipRBACRoleBindingsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_generate_membership_rbac_role_binding_yaml_empty_call_grpc_asyncio(): + client = GkeHubAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_membership_rbac_role_binding_yaml), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.GenerateMembershipRBACRoleBindingYAMLResponse( + role_bindings_yaml="role_bindings_yaml_value", + ) + ) + await client.generate_membership_rbac_role_binding_yaml(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GenerateMembershipRBACRoleBindingYAMLRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = GkeHubClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_memberships_rest_bad_request(request_type=service.ListMembershipsRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_memberships(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListMembershipsRequest, + dict, + ], +) +def test_list_memberships_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListMembershipsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListMembershipsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_memberships(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembershipsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_memberships_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.GkeHubRestInterceptor, "post_list_memberships" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_list_memberships_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_list_memberships" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.ListMembershipsRequest.pb(service.ListMembershipsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = service.ListMembershipsResponse.to_json( + service.ListMembershipsResponse() + ) + req.return_value.content = return_value + + request = service.ListMembershipsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListMembershipsResponse() + post_with_metadata.return_value = service.ListMembershipsResponse(), metadata + + client.list_memberships( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_bound_memberships_rest_bad_request( + request_type=service.ListBoundMembershipsRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"scope_name": "projects/sample1/locations/sample2/scopes/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_bound_memberships(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListBoundMembershipsRequest, + dict, + ], +) +def test_list_bound_memberships_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"scope_name": "projects/sample1/locations/sample2/scopes/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListBoundMembershipsResponse( + unreachable=["unreachable_value"], + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListBoundMembershipsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_bound_memberships(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBoundMembershipsPager) + assert response.unreachable == ["unreachable_value"] + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_bound_memberships_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.GkeHubRestInterceptor, "post_list_bound_memberships" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_list_bound_memberships_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_list_bound_memberships" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.ListBoundMembershipsRequest.pb( + service.ListBoundMembershipsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = service.ListBoundMembershipsResponse.to_json( + service.ListBoundMembershipsResponse() + ) + req.return_value.content = return_value + + request = service.ListBoundMembershipsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListBoundMembershipsResponse() + post_with_metadata.return_value = ( + service.ListBoundMembershipsResponse(), + metadata, + ) + + client.list_bound_memberships( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_features_rest_bad_request(request_type=service.ListFeaturesRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_features(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListFeaturesRequest, + dict, + ], +) +def test_list_features_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListFeaturesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListFeaturesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_features(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFeaturesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_features_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.GkeHubRestInterceptor, "post_list_features" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_list_features_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_list_features" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.ListFeaturesRequest.pb(service.ListFeaturesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = service.ListFeaturesResponse.to_json( + service.ListFeaturesResponse() + ) + req.return_value.content = return_value + + request = service.ListFeaturesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListFeaturesResponse() + post_with_metadata.return_value = service.ListFeaturesResponse(), metadata + + client.list_features( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_membership_rest_bad_request(request_type=service.GetMembershipRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_membership(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetMembershipRequest, + dict, + ], +) +def test_get_membership_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = membership.Membership( + name="name_value", + description="description_value", + external_id="external_id_value", + unique_id="unique_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = membership.Membership.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_membership(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, membership.Membership) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.external_id == "external_id_value" + assert response.unique_id == "unique_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_membership_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.GkeHubRestInterceptor, "post_get_membership" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_get_membership_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_get_membership" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.GetMembershipRequest.pb(service.GetMembershipRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = membership.Membership.to_json(membership.Membership()) + req.return_value.content = return_value + + request = service.GetMembershipRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = membership.Membership() + post_with_metadata.return_value = membership.Membership(), metadata + + client.get_membership( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_feature_rest_bad_request(request_type=service.GetFeatureRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/features/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_feature(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetFeatureRequest, + dict, + ], +) +def test_get_feature_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/features/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = feature.Feature( + name="name_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = feature.Feature.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_feature(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, feature.Feature) + assert response.name == "name_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_feature_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.GkeHubRestInterceptor, "post_get_feature" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_get_feature_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_get_feature" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.GetFeatureRequest.pb(service.GetFeatureRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = feature.Feature.to_json(feature.Feature()) + req.return_value.content = return_value + + request = service.GetFeatureRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = feature.Feature() + post_with_metadata.return_value = feature.Feature(), metadata + + client.get_feature( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_membership_rest_bad_request( + request_type=service.CreateMembershipRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_membership(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateMembershipRequest, + dict, + ], +) +def test_create_membership_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["resource"] = { + "endpoint": { + "gke_cluster": { + "resource_link": "resource_link_value", + "cluster_missing": True, + }, + "kubernetes_metadata": { + "kubernetes_api_server_version": "kubernetes_api_server_version_value", + "node_provider_id": "node_provider_id_value", + "node_count": 1070, + "vcpu_count": 1094, + "memory_mb": 967, + "update_time": {"seconds": 751, "nanos": 543}, + }, + "kubernetes_resource": { + "membership_cr_manifest": "membership_cr_manifest_value", + "membership_resources": [ + {"manifest": "manifest_value", "cluster_scoped": True} + ], + "connect_resources": {}, + "resource_options": { + "connect_version": "connect_version_value", + "v1beta1_crd": True, + "k8s_version": "k8s_version_value", + "k8s_git_version": "k8s_git_version_value", + }, + }, + "google_managed": True, + }, + "name": "name_value", + "labels": {}, + "description": "description_value", + "state": {"code": 1}, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "external_id": "external_id_value", + "last_connection_time": {}, + "unique_id": "unique_id_value", + "authority": { + "issuer": "issuer_value", + "workload_identity_pool": "workload_identity_pool_value", + "identity_provider": "identity_provider_value", + "oidc_jwks": b"oidc_jwks_blob", + }, + "monitoring_config": { + "project_id": "project_id_value", + "location": "location_value", + "cluster": "cluster_value", + "kubernetes_metrics_prefix": "kubernetes_metrics_prefix_value", + "cluster_hash": "cluster_hash_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 = service.CreateMembershipRequest.meta.fields["resource"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["resource"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["resource"][field])): + del request_init["resource"][field][i][subfield] + else: + del request_init["resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_membership(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_membership_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_create_membership" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_create_membership_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_create_membership" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.CreateMembershipRequest.pb( + service.CreateMembershipRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.CreateMembershipRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_membership( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_feature_rest_bad_request(request_type=service.CreateFeatureRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_feature(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateFeatureRequest, + dict, + ], +) +def test_create_feature_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["resource"] = { + "name": "name_value", + "labels": {}, + "resource_state": {"state": 1}, + "spec": { + "multiclusteringress": {"config_membership": "config_membership_value"} + }, + "membership_specs": {}, + "state": { + "rbacrolebindingactuation": {}, + "state": { + "code": 1, + "description": "description_value", + "update_time": {"seconds": 751, "nanos": 543}, + }, + }, + "membership_states": {}, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "scope_specs": {}, + "scope_states": {}, + "unreachable": ["unreachable_value1", "unreachable_value2"], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateFeatureRequest.meta.fields["resource"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["resource"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["resource"][field])): + del request_init["resource"][field][i][subfield] + else: + del request_init["resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_feature(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_feature_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_create_feature" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_create_feature_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_create_feature" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.CreateFeatureRequest.pb(service.CreateFeatureRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.CreateFeatureRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_feature( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_membership_rest_bad_request( + request_type=service.DeleteMembershipRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_membership(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteMembershipRequest, + dict, + ], +) +def test_delete_membership_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_membership(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_membership_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_delete_membership" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_delete_membership_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_delete_membership" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.DeleteMembershipRequest.pb( + service.DeleteMembershipRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.DeleteMembershipRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_membership( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_feature_rest_bad_request(request_type=service.DeleteFeatureRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/features/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_feature(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteFeatureRequest, + dict, + ], +) +def test_delete_feature_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/features/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_feature(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_feature_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_delete_feature" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_delete_feature_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_delete_feature" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.DeleteFeatureRequest.pb(service.DeleteFeatureRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.DeleteFeatureRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_feature( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_membership_rest_bad_request( + request_type=service.UpdateMembershipRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_membership(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateMembershipRequest, + dict, + ], +) +def test_update_membership_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} + request_init["resource"] = { + "endpoint": { + "gke_cluster": { + "resource_link": "resource_link_value", + "cluster_missing": True, + }, + "kubernetes_metadata": { + "kubernetes_api_server_version": "kubernetes_api_server_version_value", + "node_provider_id": "node_provider_id_value", + "node_count": 1070, + "vcpu_count": 1094, + "memory_mb": 967, + "update_time": {"seconds": 751, "nanos": 543}, + }, + "kubernetes_resource": { + "membership_cr_manifest": "membership_cr_manifest_value", + "membership_resources": [ + {"manifest": "manifest_value", "cluster_scoped": True} + ], + "connect_resources": {}, + "resource_options": { + "connect_version": "connect_version_value", + "v1beta1_crd": True, + "k8s_version": "k8s_version_value", + "k8s_git_version": "k8s_git_version_value", + }, + }, + "google_managed": True, + }, + "name": "name_value", + "labels": {}, + "description": "description_value", + "state": {"code": 1}, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "external_id": "external_id_value", + "last_connection_time": {}, + "unique_id": "unique_id_value", + "authority": { + "issuer": "issuer_value", + "workload_identity_pool": "workload_identity_pool_value", + "identity_provider": "identity_provider_value", + "oidc_jwks": b"oidc_jwks_blob", + }, + "monitoring_config": { + "project_id": "project_id_value", + "location": "location_value", + "cluster": "cluster_value", + "kubernetes_metrics_prefix": "kubernetes_metrics_prefix_value", + "cluster_hash": "cluster_hash_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 = service.UpdateMembershipRequest.meta.fields["resource"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["resource"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["resource"][field])): + del request_init["resource"][field][i][subfield] + else: + del request_init["resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_membership(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_membership_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_update_membership" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_update_membership_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_update_membership" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.UpdateMembershipRequest.pb( + service.UpdateMembershipRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.UpdateMembershipRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_membership( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_feature_rest_bad_request(request_type=service.UpdateFeatureRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/features/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_feature(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateFeatureRequest, + dict, + ], +) +def test_update_feature_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/features/sample3"} + request_init["resource"] = { + "name": "name_value", + "labels": {}, + "resource_state": {"state": 1}, + "spec": { + "multiclusteringress": {"config_membership": "config_membership_value"} + }, + "membership_specs": {}, + "state": { + "rbacrolebindingactuation": {}, + "state": { + "code": 1, + "description": "description_value", + "update_time": {"seconds": 751, "nanos": 543}, + }, + }, + "membership_states": {}, + "create_time": {}, + "update_time": {}, + "delete_time": {}, + "scope_specs": {}, + "scope_states": {}, + "unreachable": ["unreachable_value1", "unreachable_value2"], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.UpdateFeatureRequest.meta.fields["resource"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["resource"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["resource"][field])): + del request_init["resource"][field][i][subfield] + else: + del request_init["resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_feature(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_feature_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_update_feature" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_update_feature_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_update_feature" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.UpdateFeatureRequest.pb(service.UpdateFeatureRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.UpdateFeatureRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_feature( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_generate_connect_manifest_rest_bad_request( + request_type=service.GenerateConnectManifestRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.generate_connect_manifest(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GenerateConnectManifestRequest, + dict, + ], +) +def test_generate_connect_manifest_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.GenerateConnectManifestResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.GenerateConnectManifestResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.generate_connect_manifest(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateConnectManifestResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_connect_manifest_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.GkeHubRestInterceptor, "post_generate_connect_manifest" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_generate_connect_manifest_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_generate_connect_manifest" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.GenerateConnectManifestRequest.pb( + service.GenerateConnectManifestRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = service.GenerateConnectManifestResponse.to_json( + service.GenerateConnectManifestResponse() + ) + req.return_value.content = return_value + + request = service.GenerateConnectManifestRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.GenerateConnectManifestResponse() + post_with_metadata.return_value = ( + service.GenerateConnectManifestResponse(), + metadata, + ) + + client.generate_connect_manifest( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_fleet_rest_bad_request(request_type=service.CreateFleetRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_fleet(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateFleetRequest, + dict, + ], +) +def test_create_fleet_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["fleet"] = { + "name": "name_value", + "display_name": "display_name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "uid": "uid_value", + "state": {"code": 1}, + "default_cluster_config": { + "security_posture_config": {"mode": 1, "vulnerability_mode": 1}, + "binary_authorization_config": { + "evaluation_mode": 1, + "policy_bindings": [{"name": "name_value"}], + }, + "compliance_posture_config": { + "mode": 1, + "compliance_standards": [{"standard": "standard_value"}], + }, + }, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateFleetRequest.meta.fields["fleet"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["fleet"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["fleet"][field])): + del request_init["fleet"][field][i][subfield] + else: + del request_init["fleet"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_fleet(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_fleet_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_create_fleet" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_create_fleet_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_create_fleet" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.CreateFleetRequest.pb(service.CreateFleetRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.CreateFleetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_fleet( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_fleet_rest_bad_request(request_type=service.GetFleetRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/fleets/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_fleet(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetFleetRequest, + dict, + ], +) +def test_get_fleet_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/fleets/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = fleet.Fleet( + name="name_value", + display_name="display_name_value", + uid="uid_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = fleet.Fleet.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_fleet(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, fleet.Fleet) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.uid == "uid_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_fleet_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.GkeHubRestInterceptor, "post_get_fleet" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_get_fleet_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_get_fleet" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.GetFleetRequest.pb(service.GetFleetRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = fleet.Fleet.to_json(fleet.Fleet()) + req.return_value.content = return_value + + request = service.GetFleetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = fleet.Fleet() + post_with_metadata.return_value = fleet.Fleet(), metadata + + client.get_fleet( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_fleet_rest_bad_request(request_type=service.UpdateFleetRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "fleet": {"name": "projects/sample1/locations/sample2/fleets/sample3"} + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_fleet(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateFleetRequest, + dict, + ], +) +def test_update_fleet_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "fleet": {"name": "projects/sample1/locations/sample2/fleets/sample3"} + } + request_init["fleet"] = { + "name": "projects/sample1/locations/sample2/fleets/sample3", + "display_name": "display_name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "uid": "uid_value", + "state": {"code": 1}, + "default_cluster_config": { + "security_posture_config": {"mode": 1, "vulnerability_mode": 1}, + "binary_authorization_config": { + "evaluation_mode": 1, + "policy_bindings": [{"name": "name_value"}], + }, + "compliance_posture_config": { + "mode": 1, + "compliance_standards": [{"standard": "standard_value"}], + }, + }, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.UpdateFleetRequest.meta.fields["fleet"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["fleet"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["fleet"][field])): + del request_init["fleet"][field][i][subfield] + else: + del request_init["fleet"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_fleet(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_fleet_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_update_fleet" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_update_fleet_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_update_fleet" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.UpdateFleetRequest.pb(service.UpdateFleetRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.UpdateFleetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_fleet( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_fleet_rest_bad_request(request_type=service.DeleteFleetRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/fleets/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_fleet(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteFleetRequest, + dict, + ], +) +def test_delete_fleet_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/fleets/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_fleet(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_fleet_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_delete_fleet" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_delete_fleet_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_delete_fleet" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.DeleteFleetRequest.pb(service.DeleteFleetRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.DeleteFleetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_fleet( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_fleets_rest_bad_request(request_type=service.ListFleetsRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_fleets(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListFleetsRequest, + dict, + ], +) +def test_list_fleets_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListFleetsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListFleetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_fleets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFleetsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_fleets_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.GkeHubRestInterceptor, "post_list_fleets" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_list_fleets_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_list_fleets" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.ListFleetsRequest.pb(service.ListFleetsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = service.ListFleetsResponse.to_json(service.ListFleetsResponse()) + req.return_value.content = return_value + + request = service.ListFleetsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListFleetsResponse() + post_with_metadata.return_value = service.ListFleetsResponse(), metadata + + client.list_fleets( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_scope_namespace_rest_bad_request( + request_type=service.GetScopeNamespaceRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/scopes/sample3/namespaces/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_scope_namespace(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetScopeNamespaceRequest, + dict, + ], +) +def test_get_scope_namespace_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/scopes/sample3/namespaces/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = fleet.Namespace( + name="name_value", + uid="uid_value", + scope="scope_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = fleet.Namespace.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_scope_namespace(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, fleet.Namespace) + assert response.name == "name_value" + assert response.uid == "uid_value" + assert response.scope == "scope_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_scope_namespace_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.GkeHubRestInterceptor, "post_get_scope_namespace" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_get_scope_namespace_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_get_scope_namespace" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.GetScopeNamespaceRequest.pb( + service.GetScopeNamespaceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = fleet.Namespace.to_json(fleet.Namespace()) + req.return_value.content = return_value + + request = service.GetScopeNamespaceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = fleet.Namespace() + post_with_metadata.return_value = fleet.Namespace(), metadata + + client.get_scope_namespace( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_scope_namespace_rest_bad_request( + request_type=service.CreateScopeNamespaceRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/scopes/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_scope_namespace(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateScopeNamespaceRequest, + dict, + ], +) +def test_create_scope_namespace_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/scopes/sample3"} + request_init["scope_namespace"] = { + "name": "name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "state": {"code": 1}, + "scope": "scope_value", + "namespace_labels": {}, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateScopeNamespaceRequest.meta.fields["scope_namespace"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["scope_namespace"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["scope_namespace"][field])): + del request_init["scope_namespace"][field][i][subfield] + else: + del request_init["scope_namespace"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_scope_namespace(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_scope_namespace_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_create_scope_namespace" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_create_scope_namespace_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_create_scope_namespace" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.CreateScopeNamespaceRequest.pb( + service.CreateScopeNamespaceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.CreateScopeNamespaceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_scope_namespace( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_scope_namespace_rest_bad_request( + request_type=service.UpdateScopeNamespaceRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "scope_namespace": { + "name": "projects/sample1/locations/sample2/scopes/sample3/namespaces/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_scope_namespace(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateScopeNamespaceRequest, + dict, + ], +) +def test_update_scope_namespace_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "scope_namespace": { + "name": "projects/sample1/locations/sample2/scopes/sample3/namespaces/sample4" + } + } + request_init["scope_namespace"] = { + "name": "projects/sample1/locations/sample2/scopes/sample3/namespaces/sample4", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "state": {"code": 1}, + "scope": "scope_value", + "namespace_labels": {}, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.UpdateScopeNamespaceRequest.meta.fields["scope_namespace"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["scope_namespace"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["scope_namespace"][field])): + del request_init["scope_namespace"][field][i][subfield] + else: + del request_init["scope_namespace"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_scope_namespace(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_scope_namespace_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_update_scope_namespace" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_update_scope_namespace_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_update_scope_namespace" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.UpdateScopeNamespaceRequest.pb( + service.UpdateScopeNamespaceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.UpdateScopeNamespaceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_scope_namespace( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_scope_namespace_rest_bad_request( + request_type=service.DeleteScopeNamespaceRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/scopes/sample3/namespaces/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_scope_namespace(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteScopeNamespaceRequest, + dict, + ], +) +def test_delete_scope_namespace_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/scopes/sample3/namespaces/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_scope_namespace(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_scope_namespace_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_delete_scope_namespace" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_delete_scope_namespace_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_delete_scope_namespace" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.DeleteScopeNamespaceRequest.pb( + service.DeleteScopeNamespaceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.DeleteScopeNamespaceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_scope_namespace( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_scope_namespaces_rest_bad_request( + request_type=service.ListScopeNamespacesRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/scopes/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_scope_namespaces(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListScopeNamespacesRequest, + dict, + ], +) +def test_list_scope_namespaces_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/scopes/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListScopeNamespacesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListScopeNamespacesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_scope_namespaces(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScopeNamespacesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_scope_namespaces_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.GkeHubRestInterceptor, "post_list_scope_namespaces" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_list_scope_namespaces_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_list_scope_namespaces" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.ListScopeNamespacesRequest.pb( + service.ListScopeNamespacesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = service.ListScopeNamespacesResponse.to_json( + service.ListScopeNamespacesResponse() + ) + req.return_value.content = return_value + + request = service.ListScopeNamespacesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListScopeNamespacesResponse() + post_with_metadata.return_value = ( + service.ListScopeNamespacesResponse(), + metadata, + ) + + client.list_scope_namespaces( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_scope_rbac_role_binding_rest_bad_request( + request_type=service.GetScopeRBACRoleBindingRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/scopes/sample3/rbacrolebindings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_scope_rbac_role_binding(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetScopeRBACRoleBindingRequest, + dict, + ], +) +def test_get_scope_rbac_role_binding_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/scopes/sample3/rbacrolebindings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = fleet.RBACRoleBinding( + name="name_value", + uid="uid_value", + user="user_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = fleet.RBACRoleBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_scope_rbac_role_binding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, fleet.RBACRoleBinding) + assert response.name == "name_value" + assert response.uid == "uid_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_scope_rbac_role_binding_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.GkeHubRestInterceptor, "post_get_scope_rbac_role_binding" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, + "post_get_scope_rbac_role_binding_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_get_scope_rbac_role_binding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.GetScopeRBACRoleBindingRequest.pb( + service.GetScopeRBACRoleBindingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = fleet.RBACRoleBinding.to_json(fleet.RBACRoleBinding()) + req.return_value.content = return_value + + request = service.GetScopeRBACRoleBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = fleet.RBACRoleBinding() + post_with_metadata.return_value = fleet.RBACRoleBinding(), metadata + + client.get_scope_rbac_role_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_scope_rbac_role_binding_rest_bad_request( + request_type=service.CreateScopeRBACRoleBindingRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/scopes/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_scope_rbac_role_binding(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateScopeRBACRoleBindingRequest, + dict, + ], +) +def test_create_scope_rbac_role_binding_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/scopes/sample3"} + request_init["rbacrolebinding"] = { + "user": "user_value", + "group": "group_value", + "name": "name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "state": {"code": 1}, + "role": {"predefined_role": 1, "custom_role": "custom_role_value"}, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateScopeRBACRoleBindingRequest.meta.fields[ + "rbacrolebinding" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["rbacrolebinding"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["rbacrolebinding"][field])): + del request_init["rbacrolebinding"][field][i][subfield] + else: + del request_init["rbacrolebinding"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_scope_rbac_role_binding(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_scope_rbac_role_binding_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_create_scope_rbac_role_binding" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, + "post_create_scope_rbac_role_binding_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_create_scope_rbac_role_binding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.CreateScopeRBACRoleBindingRequest.pb( + service.CreateScopeRBACRoleBindingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.CreateScopeRBACRoleBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_scope_rbac_role_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_scope_rbac_role_binding_rest_bad_request( + request_type=service.UpdateScopeRBACRoleBindingRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "rbacrolebinding": { + "name": "projects/sample1/locations/sample2/scopes/sample3/rbacrolebindings/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_scope_rbac_role_binding(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateScopeRBACRoleBindingRequest, + dict, + ], +) +def test_update_scope_rbac_role_binding_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "rbacrolebinding": { + "name": "projects/sample1/locations/sample2/scopes/sample3/rbacrolebindings/sample4" + } + } + request_init["rbacrolebinding"] = { + "user": "user_value", + "group": "group_value", + "name": "projects/sample1/locations/sample2/scopes/sample3/rbacrolebindings/sample4", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "state": {"code": 1}, + "role": {"predefined_role": 1, "custom_role": "custom_role_value"}, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.UpdateScopeRBACRoleBindingRequest.meta.fields[ + "rbacrolebinding" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["rbacrolebinding"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["rbacrolebinding"][field])): + del request_init["rbacrolebinding"][field][i][subfield] + else: + del request_init["rbacrolebinding"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_scope_rbac_role_binding(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_scope_rbac_role_binding_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_update_scope_rbac_role_binding" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, + "post_update_scope_rbac_role_binding_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_update_scope_rbac_role_binding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.UpdateScopeRBACRoleBindingRequest.pb( + service.UpdateScopeRBACRoleBindingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.UpdateScopeRBACRoleBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_scope_rbac_role_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_scope_rbac_role_binding_rest_bad_request( + request_type=service.DeleteScopeRBACRoleBindingRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/scopes/sample3/rbacrolebindings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_scope_rbac_role_binding(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteScopeRBACRoleBindingRequest, + dict, + ], +) +def test_delete_scope_rbac_role_binding_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/scopes/sample3/rbacrolebindings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_scope_rbac_role_binding(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_scope_rbac_role_binding_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_delete_scope_rbac_role_binding" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, + "post_delete_scope_rbac_role_binding_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_delete_scope_rbac_role_binding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.DeleteScopeRBACRoleBindingRequest.pb( + service.DeleteScopeRBACRoleBindingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.DeleteScopeRBACRoleBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_scope_rbac_role_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_scope_rbac_role_bindings_rest_bad_request( + request_type=service.ListScopeRBACRoleBindingsRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/scopes/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_scope_rbac_role_bindings(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListScopeRBACRoleBindingsRequest, + dict, + ], +) +def test_list_scope_rbac_role_bindings_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/scopes/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListScopeRBACRoleBindingsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListScopeRBACRoleBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_scope_rbac_role_bindings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScopeRBACRoleBindingsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_scope_rbac_role_bindings_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.GkeHubRestInterceptor, "post_list_scope_rbac_role_bindings" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, + "post_list_scope_rbac_role_bindings_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_list_scope_rbac_role_bindings" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.ListScopeRBACRoleBindingsRequest.pb( + service.ListScopeRBACRoleBindingsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = service.ListScopeRBACRoleBindingsResponse.to_json( + service.ListScopeRBACRoleBindingsResponse() + ) + req.return_value.content = return_value + + request = service.ListScopeRBACRoleBindingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListScopeRBACRoleBindingsResponse() + post_with_metadata.return_value = ( + service.ListScopeRBACRoleBindingsResponse(), + metadata, + ) + + client.list_scope_rbac_role_bindings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_scope_rest_bad_request(request_type=service.GetScopeRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/scopes/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_scope(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetScopeRequest, + dict, + ], +) +def test_get_scope_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/scopes/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = fleet.Scope( + name="name_value", + uid="uid_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = fleet.Scope.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_scope(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, fleet.Scope) + assert response.name == "name_value" + assert response.uid == "uid_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_scope_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.GkeHubRestInterceptor, "post_get_scope" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_get_scope_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_get_scope" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.GetScopeRequest.pb(service.GetScopeRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = fleet.Scope.to_json(fleet.Scope()) + req.return_value.content = return_value + + request = service.GetScopeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = fleet.Scope() + post_with_metadata.return_value = fleet.Scope(), metadata + + client.get_scope( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_scope_rest_bad_request(request_type=service.CreateScopeRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_scope(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateScopeRequest, + dict, + ], +) +def test_create_scope_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["scope"] = { + "name": "name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "state": {"code": 1}, + "namespace_labels": {}, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateScopeRequest.meta.fields["scope"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["scope"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["scope"][field])): + del request_init["scope"][field][i][subfield] + else: + del request_init["scope"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_scope(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_scope_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_create_scope" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_create_scope_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_create_scope" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.CreateScopeRequest.pb(service.CreateScopeRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.CreateScopeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_scope( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_scope_rest_bad_request(request_type=service.UpdateScopeRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "scope": {"name": "projects/sample1/locations/sample2/scopes/sample3"} + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_scope(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateScopeRequest, + dict, + ], +) +def test_update_scope_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "scope": {"name": "projects/sample1/locations/sample2/scopes/sample3"} + } + request_init["scope"] = { + "name": "projects/sample1/locations/sample2/scopes/sample3", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "state": {"code": 1}, + "namespace_labels": {}, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.UpdateScopeRequest.meta.fields["scope"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["scope"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["scope"][field])): + del request_init["scope"][field][i][subfield] + else: + del request_init["scope"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_scope(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_scope_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_update_scope" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_update_scope_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_update_scope" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.UpdateScopeRequest.pb(service.UpdateScopeRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.UpdateScopeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_scope( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_scope_rest_bad_request(request_type=service.DeleteScopeRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/scopes/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_scope(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteScopeRequest, + dict, + ], +) +def test_delete_scope_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/scopes/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_scope(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_scope_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_delete_scope" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_delete_scope_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_delete_scope" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.DeleteScopeRequest.pb(service.DeleteScopeRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.DeleteScopeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_scope( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_scopes_rest_bad_request(request_type=service.ListScopesRequest): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_scopes(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListScopesRequest, + dict, + ], +) +def test_list_scopes_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListScopesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListScopesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_scopes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScopesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_scopes_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.GkeHubRestInterceptor, "post_list_scopes" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_list_scopes_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_list_scopes" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.ListScopesRequest.pb(service.ListScopesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = service.ListScopesResponse.to_json(service.ListScopesResponse()) + req.return_value.content = return_value + + request = service.ListScopesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListScopesResponse() + post_with_metadata.return_value = service.ListScopesResponse(), metadata + + client.list_scopes( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_permitted_scopes_rest_bad_request( + request_type=service.ListPermittedScopesRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_permitted_scopes(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListPermittedScopesRequest, + dict, + ], +) +def test_list_permitted_scopes_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListPermittedScopesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListPermittedScopesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_permitted_scopes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPermittedScopesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_permitted_scopes_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.GkeHubRestInterceptor, "post_list_permitted_scopes" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_list_permitted_scopes_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_list_permitted_scopes" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.ListPermittedScopesRequest.pb( + service.ListPermittedScopesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = service.ListPermittedScopesResponse.to_json( + service.ListPermittedScopesResponse() + ) + req.return_value.content = return_value + + request = service.ListPermittedScopesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListPermittedScopesResponse() + post_with_metadata.return_value = ( + service.ListPermittedScopesResponse(), + metadata, + ) + + client.list_permitted_scopes( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_membership_binding_rest_bad_request( + request_type=service.GetMembershipBindingRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/memberships/sample3/bindings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_membership_binding(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetMembershipBindingRequest, + dict, + ], +) +def test_get_membership_binding_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/memberships/sample3/bindings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = fleet.MembershipBinding( + name="name_value", + uid="uid_value", + scope="scope_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = fleet.MembershipBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_membership_binding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, fleet.MembershipBinding) + assert response.name == "name_value" + assert response.uid == "uid_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_membership_binding_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.GkeHubRestInterceptor, "post_get_membership_binding" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_get_membership_binding_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_get_membership_binding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.GetMembershipBindingRequest.pb( + service.GetMembershipBindingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = fleet.MembershipBinding.to_json(fleet.MembershipBinding()) + req.return_value.content = return_value + + request = service.GetMembershipBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = fleet.MembershipBinding() + post_with_metadata.return_value = fleet.MembershipBinding(), metadata + + client.get_membership_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_membership_binding_rest_bad_request( + request_type=service.CreateMembershipBindingRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/memberships/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_membership_binding(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateMembershipBindingRequest, + dict, + ], +) +def test_create_membership_binding_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/memberships/sample3"} + request_init["membership_binding"] = { + "scope": "scope_value", + "name": "name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "state": {"code": 1}, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateMembershipBindingRequest.meta.fields[ + "membership_binding" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["membership_binding"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["membership_binding"][field])): + del request_init["membership_binding"][field][i][subfield] + else: + del request_init["membership_binding"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_membership_binding(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_membership_binding_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_create_membership_binding" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_create_membership_binding_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_create_membership_binding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.CreateMembershipBindingRequest.pb( + service.CreateMembershipBindingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.CreateMembershipBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_membership_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_membership_binding_rest_bad_request( + request_type=service.UpdateMembershipBindingRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "membership_binding": { + "name": "projects/sample1/locations/sample2/memberships/sample3/bindings/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_membership_binding(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateMembershipBindingRequest, + dict, + ], +) +def test_update_membership_binding_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "membership_binding": { + "name": "projects/sample1/locations/sample2/memberships/sample3/bindings/sample4" + } + } + request_init["membership_binding"] = { + "scope": "scope_value", + "name": "projects/sample1/locations/sample2/memberships/sample3/bindings/sample4", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "state": {"code": 1}, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.UpdateMembershipBindingRequest.meta.fields[ + "membership_binding" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["membership_binding"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["membership_binding"][field])): + del request_init["membership_binding"][field][i][subfield] + else: + del request_init["membership_binding"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_membership_binding(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_membership_binding_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_update_membership_binding" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_update_membership_binding_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_update_membership_binding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.UpdateMembershipBindingRequest.pb( + service.UpdateMembershipBindingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.UpdateMembershipBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_membership_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_membership_binding_rest_bad_request( + request_type=service.DeleteMembershipBindingRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/memberships/sample3/bindings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_membership_binding(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteMembershipBindingRequest, + dict, + ], +) +def test_delete_membership_binding_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/memberships/sample3/bindings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_membership_binding(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_membership_binding_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_delete_membership_binding" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_delete_membership_binding_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_delete_membership_binding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.DeleteMembershipBindingRequest.pb( + service.DeleteMembershipBindingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.DeleteMembershipBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_membership_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_membership_bindings_rest_bad_request( + request_type=service.ListMembershipBindingsRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/memberships/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_membership_bindings(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListMembershipBindingsRequest, + dict, + ], +) +def test_list_membership_bindings_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/memberships/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListMembershipBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListMembershipBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_membership_bindings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMembershipBindingsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_membership_bindings_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.GkeHubRestInterceptor, "post_list_membership_bindings" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, "post_list_membership_bindings_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_list_membership_bindings" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.ListMembershipBindingsRequest.pb( + service.ListMembershipBindingsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = service.ListMembershipBindingsResponse.to_json( + service.ListMembershipBindingsResponse() + ) + req.return_value.content = return_value + + request = service.ListMembershipBindingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListMembershipBindingsResponse() + post_with_metadata.return_value = ( + service.ListMembershipBindingsResponse(), + metadata, + ) + + client.list_membership_bindings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_membership_rbac_role_binding_rest_bad_request( + request_type=service.GetMembershipRBACRoleBindingRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/memberships/sample3/rbacrolebindings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_membership_rbac_role_binding(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetMembershipRBACRoleBindingRequest, + dict, + ], +) +def test_get_membership_rbac_role_binding_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/memberships/sample3/rbacrolebindings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = fleet.RBACRoleBinding( + name="name_value", + uid="uid_value", + user="user_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = fleet.RBACRoleBinding.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_membership_rbac_role_binding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, fleet.RBACRoleBinding) + assert response.name == "name_value" + assert response.uid == "uid_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_membership_rbac_role_binding_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.GkeHubRestInterceptor, "post_get_membership_rbac_role_binding" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, + "post_get_membership_rbac_role_binding_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_get_membership_rbac_role_binding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.GetMembershipRBACRoleBindingRequest.pb( + service.GetMembershipRBACRoleBindingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = fleet.RBACRoleBinding.to_json(fleet.RBACRoleBinding()) + req.return_value.content = return_value + + request = service.GetMembershipRBACRoleBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = fleet.RBACRoleBinding() + post_with_metadata.return_value = fleet.RBACRoleBinding(), metadata + + client.get_membership_rbac_role_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_membership_rbac_role_binding_rest_bad_request( + request_type=service.CreateMembershipRBACRoleBindingRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/memberships/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_membership_rbac_role_binding(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateMembershipRBACRoleBindingRequest, + dict, + ], +) +def test_create_membership_rbac_role_binding_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/memberships/sample3"} + request_init["rbacrolebinding"] = { + "user": "user_value", + "group": "group_value", + "name": "name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "state": {"code": 1}, + "role": {"predefined_role": 1, "custom_role": "custom_role_value"}, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateMembershipRBACRoleBindingRequest.meta.fields[ + "rbacrolebinding" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["rbacrolebinding"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["rbacrolebinding"][field])): + del request_init["rbacrolebinding"][field][i][subfield] + else: + del request_init["rbacrolebinding"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_membership_rbac_role_binding(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_membership_rbac_role_binding_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_create_membership_rbac_role_binding" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, + "post_create_membership_rbac_role_binding_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_create_membership_rbac_role_binding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.CreateMembershipRBACRoleBindingRequest.pb( + service.CreateMembershipRBACRoleBindingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.CreateMembershipRBACRoleBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_membership_rbac_role_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_membership_rbac_role_binding_rest_bad_request( + request_type=service.UpdateMembershipRBACRoleBindingRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "rbacrolebinding": { + "name": "projects/sample1/locations/sample2/memberships/sample3/rbacrolebindings/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_membership_rbac_role_binding(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.UpdateMembershipRBACRoleBindingRequest, + dict, + ], +) +def test_update_membership_rbac_role_binding_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "rbacrolebinding": { + "name": "projects/sample1/locations/sample2/memberships/sample3/rbacrolebindings/sample4" + } + } + request_init["rbacrolebinding"] = { + "user": "user_value", + "group": "group_value", + "name": "projects/sample1/locations/sample2/memberships/sample3/rbacrolebindings/sample4", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "state": {"code": 1}, + "role": {"predefined_role": 1, "custom_role": "custom_role_value"}, + "labels": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.UpdateMembershipRBACRoleBindingRequest.meta.fields[ + "rbacrolebinding" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["rbacrolebinding"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["rbacrolebinding"][field])): + del request_init["rbacrolebinding"][field][i][subfield] + else: + del request_init["rbacrolebinding"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_membership_rbac_role_binding(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_membership_rbac_role_binding_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_update_membership_rbac_role_binding" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, + "post_update_membership_rbac_role_binding_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_update_membership_rbac_role_binding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.UpdateMembershipRBACRoleBindingRequest.pb( + service.UpdateMembershipRBACRoleBindingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.UpdateMembershipRBACRoleBindingRequest() + metadata = [ + ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = feature.Feature() - post_with_metadata.return_value = feature.Feature(), metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.get_feature( + client.update_membership_rbac_role_binding( request, metadata=[ ("key", "val"), @@ -8311,14 +35709,16 @@ def test_get_feature_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_create_membership_rest_bad_request( - request_type=service.CreateMembershipRequest, +def test_delete_membership_rbac_role_binding_rest_bad_request( + request_type=service.DeleteMembershipRBACRoleBindingRequest, ): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "name": "projects/sample1/locations/sample2/memberships/sample3/rbacrolebindings/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -8333,165 +35733,177 @@ def test_create_membership_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_membership(request) + client.delete_membership_rbac_role_binding(request) @pytest.mark.parametrize( "request_type", [ - service.CreateMembershipRequest, + service.DeleteMembershipRBACRoleBindingRequest, dict, ], ) -def test_create_membership_rest_call_success(request_type): +def test_delete_membership_rbac_role_binding_rest_call_success(request_type): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["resource"] = { - "endpoint": { - "gke_cluster": { - "resource_link": "resource_link_value", - "cluster_missing": True, - }, - "kubernetes_metadata": { - "kubernetes_api_server_version": "kubernetes_api_server_version_value", - "node_provider_id": "node_provider_id_value", - "node_count": 1070, - "vcpu_count": 1094, - "memory_mb": 967, - "update_time": {"seconds": 751, "nanos": 543}, - }, - "kubernetes_resource": { - "membership_cr_manifest": "membership_cr_manifest_value", - "membership_resources": [ - {"manifest": "manifest_value", "cluster_scoped": True} - ], - "connect_resources": {}, - "resource_options": { - "connect_version": "connect_version_value", - "v1beta1_crd": True, - "k8s_version": "k8s_version_value", - "k8s_git_version": "k8s_git_version_value", - }, - }, - "google_managed": True, - }, - "name": "name_value", - "labels": {}, - "description": "description_value", - "state": {"code": 1}, - "create_time": {}, - "update_time": {}, - "delete_time": {}, - "external_id": "external_id_value", - "last_connection_time": {}, - "unique_id": "unique_id_value", - "authority": { - "issuer": "issuer_value", - "workload_identity_pool": "workload_identity_pool_value", - "identity_provider": "identity_provider_value", - "oidc_jwks": b"oidc_jwks_blob", - }, - "monitoring_config": { - "project_id": "project_id_value", - "location": "location_value", - "cluster": "cluster_value", - "kubernetes_metrics_prefix": "kubernetes_metrics_prefix_value", - "cluster_hash": "cluster_hash_value", - }, + request_init = { + "name": "projects/sample1/locations/sample2/memberships/sample3/rbacrolebindings/sample4" } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + request = request_type(**request_init) - # Determine if the message type is proto-plus or protobuf - test_field = service.CreateMembershipRequest.meta.fields["resource"] + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") - def get_message_fields(field): - # Given a field which is a message (composite type), 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 = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_membership_rbac_role_binding(request) - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_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 - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_membership_rbac_role_binding_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) - subfields_not_in_runtime = [] + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.GkeHubRestInterceptor, "post_delete_membership_rbac_role_binding" + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, + "post_delete_membership_rbac_role_binding_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, "pre_delete_membership_rbac_role_binding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.DeleteMembershipRBACRoleBindingRequest.pb( + service.DeleteMembershipRBACRoleBindingRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["resource"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.DeleteMembershipRBACRoleBindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_membership_rbac_role_binding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_membership_rbac_role_bindings_rest_bad_request( + request_type=service.ListMembershipRBACRoleBindingsRequest, +): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/memberships/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_membership_rbac_role_bindings(request) - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["resource"][field])): - del request_init["resource"][field][i][subfield] - else: - del request_init["resource"][field][subfield] +@pytest.mark.parametrize( + "request_type", + [ + service.ListMembershipRBACRoleBindingsRequest, + dict, + ], +) +def test_list_membership_rbac_role_bindings_rest_call_success(request_type): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/memberships/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListMembershipRBACRoleBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListMembershipRBACRoleBindingsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_membership(request) + response = client.list_membership_rbac_role_bindings(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, pagers.ListMembershipRBACRoleBindingsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_membership_rest_interceptors(null_interceptor): +def test_list_membership_rbac_role_bindings_rest_interceptors(null_interceptor): transport = transports.GkeHubRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), @@ -8503,19 +35915,18 @@ def test_create_membership_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.GkeHubRestInterceptor, "post_create_membership" + transports.GkeHubRestInterceptor, "post_list_membership_rbac_role_bindings" ) as post, mock.patch.object( - transports.GkeHubRestInterceptor, "post_create_membership_with_metadata" + transports.GkeHubRestInterceptor, + "post_list_membership_rbac_role_bindings_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.GkeHubRestInterceptor, "pre_create_membership" + transports.GkeHubRestInterceptor, "pre_list_membership_rbac_role_bindings" ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.CreateMembershipRequest.pb( - service.CreateMembershipRequest() + pb_message = service.ListMembershipRBACRoleBindingsRequest.pb( + service.ListMembershipRBACRoleBindingsRequest() ) transcode.return_value = { "method": "post", @@ -8527,19 +35938,24 @@ def test_create_membership_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) + return_value = service.ListMembershipRBACRoleBindingsResponse.to_json( + service.ListMembershipRBACRoleBindingsResponse() + ) req.return_value.content = return_value - request = service.CreateMembershipRequest() + request = service.ListMembershipRBACRoleBindingsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + post.return_value = service.ListMembershipRBACRoleBindingsResponse() + post_with_metadata.return_value = ( + service.ListMembershipRBACRoleBindingsResponse(), + metadata, + ) - client.create_membership( + client.list_membership_rbac_role_bindings( request, metadata=[ ("key", "val"), @@ -8552,12 +35968,14 @@ def test_create_membership_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_create_feature_rest_bad_request(request_type=service.CreateFeatureRequest): +def test_generate_membership_rbac_role_binding_yaml_rest_bad_request( + request_type=service.GenerateMembershipRBACRoleBindingYAMLRequest, +): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"parent": "projects/sample1/locations/sample2/memberships/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -8572,49 +35990,43 @@ def test_create_feature_rest_bad_request(request_type=service.CreateFeatureReque response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_feature(request) + client.generate_membership_rbac_role_binding_yaml(request) @pytest.mark.parametrize( "request_type", [ - service.CreateFeatureRequest, + service.GenerateMembershipRBACRoleBindingYAMLRequest, dict, ], ) -def test_create_feature_rest_call_success(request_type): +def test_generate_membership_rbac_role_binding_yaml_rest_call_success(request_type): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["resource"] = { + request_init = {"parent": "projects/sample1/locations/sample2/memberships/sample3"} + request_init["rbacrolebinding"] = { + "user": "user_value", + "group": "group_value", "name": "name_value", - "labels": {}, - "resource_state": {"state": 1}, - "spec": { - "multiclusteringress": {"config_membership": "config_membership_value"} - }, - "membership_specs": {}, - "state": { - "state": { - "code": 1, - "description": "description_value", - "update_time": {"seconds": 751, "nanos": 543}, - } - }, - "membership_states": {}, - "create_time": {}, + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, "update_time": {}, "delete_time": {}, + "state": {"code": 1}, + "role": {"predefined_role": 1, "custom_role": "custom_role_value"}, + "labels": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = service.CreateFeatureRequest.meta.fields["resource"] + test_field = service.GenerateMembershipRBACRoleBindingYAMLRequest.meta.fields[ + "rbacrolebinding" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -8642,7 +36054,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["resource"].items(): # pragma: NO COVER + for field, value in request_init["rbacrolebinding"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -8672,990 +36084,896 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["resource"][field])): - del request_init["resource"][field][i][subfield] + for i in range(0, len(request_init["rbacrolebinding"][field])): + del request_init["rbacrolebinding"][field][i][subfield] else: - del request_init["resource"][field][subfield] + del request_init["rbacrolebinding"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.GenerateMembershipRBACRoleBindingYAMLResponse( + role_bindings_yaml="role_bindings_yaml_value", + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.GenerateMembershipRBACRoleBindingYAMLResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_feature(request) + response = client.generate_membership_rbac_role_binding_yaml(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, service.GenerateMembershipRBACRoleBindingYAMLResponse) + assert response.role_bindings_yaml == "role_bindings_yaml_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_membership_rbac_role_binding_yaml_rest_interceptors(null_interceptor): + transport = transports.GkeHubRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + ) + client = GkeHubClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.GkeHubRestInterceptor, + "post_generate_membership_rbac_role_binding_yaml", + ) as post, mock.patch.object( + transports.GkeHubRestInterceptor, + "post_generate_membership_rbac_role_binding_yaml_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.GkeHubRestInterceptor, + "pre_generate_membership_rbac_role_binding_yaml", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.GenerateMembershipRBACRoleBindingYAMLRequest.pb( + service.GenerateMembershipRBACRoleBindingYAMLRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = service.GenerateMembershipRBACRoleBindingYAMLResponse.to_json( + service.GenerateMembershipRBACRoleBindingYAMLResponse() + ) + req.return_value.content = return_value + + request = service.GenerateMembershipRBACRoleBindingYAMLRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.GenerateMembershipRBACRoleBindingYAMLResponse() + post_with_metadata.return_value = ( + service.GenerateMembershipRBACRoleBindingYAMLResponse(), + metadata, + ) + + client.generate_membership_rbac_role_binding_yaml( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_initialize_client_w_rest(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_memberships_empty_call_rest(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_memberships), "__call__") as call: + client.list_memberships(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListMembershipsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_bound_memberships_empty_call_rest(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_bound_memberships), "__call__" + ) as call: + client.list_bound_memberships(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListBoundMembershipsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_features_empty_call_rest(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_features), "__call__") as call: + client.list_features(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListFeaturesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_membership_empty_call_rest(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_membership), "__call__") as call: + client.get_membership(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetMembershipRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_feature_empty_call_rest(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_feature), "__call__") as call: + client.get_feature(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetFeatureRequest() + + assert args[0] == request_msg -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_feature_rest_interceptors(null_interceptor): - transport = transports.GkeHubRestTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_membership_empty_call_rest(): + client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + transport="rest", ) - client = GkeHubClient(transport=transport) + # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.GkeHubRestInterceptor, "post_create_feature" - ) as post, mock.patch.object( - transports.GkeHubRestInterceptor, "post_create_feature_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GkeHubRestInterceptor, "pre_create_feature" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = service.CreateFeatureRequest.pb(service.CreateFeatureRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } + type(client.transport.create_membership), "__call__" + ) as call: + client.create_membership(request=None) - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateMembershipRequest() - request = service.CreateFeatureRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + assert args[0] == request_msg - client.create_feature( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_feature_empty_call_rest(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_feature), "__call__") as call: + client.create_feature(request=None) -def test_delete_membership_rest_bad_request( - request_type=service.DeleteMembershipRequest, -): + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateFeatureRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_membership_empty_call_rest(): client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_membership(request) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_membership), "__call__" + ) as call: + client.delete_membership(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteMembershipRequest() -@pytest.mark.parametrize( - "request_type", - [ - service.DeleteMembershipRequest, - dict, - ], -) -def test_delete_membership_rest_call_success(request_type): + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_feature_empty_call_rest(): client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_feature), "__call__") as call: + client.delete_feature(request=None) - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_membership(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteFeatureRequest() - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert args[0] == request_msg -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_membership_rest_interceptors(null_interceptor): - transport = transports.GkeHubRestTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_membership_empty_call_rest(): + client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + transport="rest", ) - client = GkeHubClient(transport=transport) + # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.GkeHubRestInterceptor, "post_delete_membership" - ) as post, mock.patch.object( - transports.GkeHubRestInterceptor, "post_delete_membership_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GkeHubRestInterceptor, "pre_delete_membership" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = service.DeleteMembershipRequest.pb( - service.DeleteMembershipRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } + type(client.transport.update_membership), "__call__" + ) as call: + client.update_membership(request=None) - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateMembershipRequest() - request = service.DeleteMembershipRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + assert args[0] == request_msg - client.delete_membership( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_feature_empty_call_rest(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_feature), "__call__") as call: + client.update_feature(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateFeatureRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_connect_manifest_empty_call_rest(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_connect_manifest), "__call__" + ) as call: + client.generate_connect_manifest(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GenerateConnectManifestRequest() + assert args[0] == request_msg -def test_delete_feature_rest_bad_request(request_type=service.DeleteFeatureRequest): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_fleet_empty_call_rest(): client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/features/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_feature(request) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_fleet), "__call__") as call: + client.create_fleet(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateFleetRequest() -@pytest.mark.parametrize( - "request_type", - [ - service.DeleteFeatureRequest, - dict, - ], -) -def test_delete_feature_rest_call_success(request_type): + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_fleet_empty_call_rest(): client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/features/sample3"} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_fleet), "__call__") as call: + client.get_fleet(request=None) - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_feature(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetFleetRequest() - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert args[0] == request_msg -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_feature_rest_interceptors(null_interceptor): - transport = transports.GkeHubRestTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_fleet_empty_call_rest(): + client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + transport="rest", ) - client = GkeHubClient(transport=transport) - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.GkeHubRestInterceptor, "post_delete_feature" - ) as post, mock.patch.object( - transports.GkeHubRestInterceptor, "post_delete_feature_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GkeHubRestInterceptor, "pre_delete_feature" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = service.DeleteFeatureRequest.pb(service.DeleteFeatureRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_fleet), "__call__") as call: + client.update_fleet(request=None) - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateFleetRequest() - request = service.DeleteFeatureRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + assert args[0] == request_msg - client.delete_feature( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_fleet_empty_call_rest(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_fleet), "__call__") as call: + client.delete_fleet(request=None) -def test_update_membership_rest_bad_request( - request_type=service.UpdateMembershipRequest, -): + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteFleetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_fleets_empty_call_rest(): client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_membership(request) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_fleets), "__call__") as call: + client.list_fleets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListFleetsRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "request_type", - [ - service.UpdateMembershipRequest, - dict, - ], -) -def test_update_membership_rest_call_success(request_type): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_scope_namespace_empty_call_rest(): client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} - request_init["resource"] = { - "endpoint": { - "gke_cluster": { - "resource_link": "resource_link_value", - "cluster_missing": True, - }, - "kubernetes_metadata": { - "kubernetes_api_server_version": "kubernetes_api_server_version_value", - "node_provider_id": "node_provider_id_value", - "node_count": 1070, - "vcpu_count": 1094, - "memory_mb": 967, - "update_time": {"seconds": 751, "nanos": 543}, - }, - "kubernetes_resource": { - "membership_cr_manifest": "membership_cr_manifest_value", - "membership_resources": [ - {"manifest": "manifest_value", "cluster_scoped": True} - ], - "connect_resources": {}, - "resource_options": { - "connect_version": "connect_version_value", - "v1beta1_crd": True, - "k8s_version": "k8s_version_value", - "k8s_git_version": "k8s_git_version_value", - }, - }, - "google_managed": True, - }, - "name": "name_value", - "labels": {}, - "description": "description_value", - "state": {"code": 1}, - "create_time": {}, - "update_time": {}, - "delete_time": {}, - "external_id": "external_id_value", - "last_connection_time": {}, - "unique_id": "unique_id_value", - "authority": { - "issuer": "issuer_value", - "workload_identity_pool": "workload_identity_pool_value", - "identity_provider": "identity_provider_value", - "oidc_jwks": b"oidc_jwks_blob", - }, - "monitoring_config": { - "project_id": "project_id_value", - "location": "location_value", - "cluster": "cluster_value", - "kubernetes_metrics_prefix": "kubernetes_metrics_prefix_value", - "cluster_hash": "cluster_hash_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 + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scope_namespace), "__call__" + ) as call: + client.get_scope_namespace(request=None) - # Determine if the message type is proto-plus or protobuf - test_field = service.UpdateMembershipRequest.meta.fields["resource"] + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetScopeNamespaceRequest() - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + assert args[0] == request_msg - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_scope_namespace_empty_call_rest(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_scope_namespace), "__call__" + ) as call: + client.create_scope_namespace(request=None) - subfields_not_in_runtime = [] + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateScopeNamespaceRequest() - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["resource"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value + assert args[0] == request_msg - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["resource"][field])): - del request_init["resource"][field][i][subfield] - else: - del request_init["resource"][field][subfield] - request = request_type(**request_init) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_scope_namespace_empty_call_rest(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_scope_namespace), "__call__" + ) as call: + client.update_scope_namespace(request=None) - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_membership(request) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateScopeNamespaceRequest() - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert args[0] == request_msg -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_membership_rest_interceptors(null_interceptor): - transport = transports.GkeHubRestTransport( +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_scope_namespace_empty_call_rest(): + client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + transport="rest", ) - client = GkeHubClient(transport=transport) + # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.GkeHubRestInterceptor, "post_update_membership" - ) as post, mock.patch.object( - transports.GkeHubRestInterceptor, "post_update_membership_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GkeHubRestInterceptor, "pre_update_membership" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = service.UpdateMembershipRequest.pb( - service.UpdateMembershipRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } + type(client.transport.delete_scope_namespace), "__call__" + ) as call: + client.delete_scope_namespace(request=None) - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteScopeNamespaceRequest() - request = service.UpdateMembershipRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + assert args[0] == request_msg - client.update_membership( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_scope_namespaces_empty_call_rest(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scope_namespaces), "__call__" + ) as call: + client.list_scope_namespaces(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListScopeNamespacesRequest() + assert args[0] == request_msg -def test_update_feature_rest_bad_request(request_type=service.UpdateFeatureRequest): + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_scope_rbac_role_binding_empty_call_rest(): client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/features/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_feature(request) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scope_rbac_role_binding), "__call__" + ) as call: + client.get_scope_rbac_role_binding(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetScopeRBACRoleBindingRequest() -@pytest.mark.parametrize( - "request_type", - [ - service.UpdateFeatureRequest, - dict, - ], -) -def test_update_feature_rest_call_success(request_type): + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_scope_rbac_role_binding_empty_call_rest(): client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/features/sample3"} - request_init["resource"] = { - "name": "name_value", - "labels": {}, - "resource_state": {"state": 1}, - "spec": { - "multiclusteringress": {"config_membership": "config_membership_value"} - }, - "membership_specs": {}, - "state": { - "state": { - "code": 1, - "description": "description_value", - "update_time": {"seconds": 751, "nanos": 543}, - } - }, - "membership_states": {}, - "create_time": {}, - "update_time": {}, - "delete_time": {}, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.UpdateFeatureRequest.meta.fields["resource"] + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_scope_rbac_role_binding), "__call__" + ) as call: + client.create_scope_rbac_role_binding(request=None) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateScopeRBACRoleBindingRequest() - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + assert args[0] == request_msg - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_scope_rbac_role_binding_empty_call_rest(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - subfields_not_in_runtime = [] + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_scope_rbac_role_binding), "__call__" + ) as call: + client.update_scope_rbac_role_binding(request=None) - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["resource"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateScopeRBACRoleBindingRequest() - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) + assert args[0] == request_msg - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["resource"][field])): - del request_init["resource"][field][i][subfield] - else: - del request_init["resource"][field][subfield] - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_scope_rbac_role_binding_empty_call_rest(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_feature(request) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_scope_rbac_role_binding), "__call__" + ) as call: + client.delete_scope_rbac_role_binding(request=None) - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteScopeRBACRoleBindingRequest() + assert args[0] == request_msg -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_feature_rest_interceptors(null_interceptor): - transport = transports.GkeHubRestTransport( + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_scope_rbac_role_bindings_empty_call_rest(): + client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + transport="rest", ) - client = GkeHubClient(transport=transport) + # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.GkeHubRestInterceptor, "post_update_feature" - ) as post, mock.patch.object( - transports.GkeHubRestInterceptor, "post_update_feature_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GkeHubRestInterceptor, "pre_update_feature" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = service.UpdateFeatureRequest.pb(service.UpdateFeatureRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } + type(client.transport.list_scope_rbac_role_bindings), "__call__" + ) as call: + client.list_scope_rbac_role_bindings(request=None) - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListScopeRBACRoleBindingsRequest() - request = service.UpdateFeatureRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + assert args[0] == request_msg - client.update_feature( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_scope_empty_call_rest(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_scope), "__call__") as call: + client.get_scope(request=None) -def test_generate_connect_manifest_rest_bad_request( - request_type=service.GenerateConnectManifestRequest, -): + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetScopeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_scope_empty_call_rest(): client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.generate_connect_manifest(request) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_scope), "__call__") as call: + client.create_scope(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateScopeRequest() -@pytest.mark.parametrize( - "request_type", - [ - service.GenerateConnectManifestRequest, - dict, - ], -) -def test_generate_connect_manifest_rest_call_success(request_type): + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_scope_empty_call_rest(): client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/memberships/sample3"} - request = request_type(**request_init) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_scope), "__call__") as call: + client.update_scope(request=None) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = service.GenerateConnectManifestResponse() + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateScopeRequest() - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 + assert args[0] == request_msg - # Convert return value to protobuf type - return_value = service.GenerateConnectManifestResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.generate_connect_manifest(request) - # Establish that the response is the type that we expect. - assert isinstance(response, service.GenerateConnectManifestResponse) +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_scope_empty_call_rest(): + client = GkeHubClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_scope), "__call__") as call: + client.delete_scope(request=None) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_generate_connect_manifest_rest_interceptors(null_interceptor): - transport = transports.GkeHubRestTransport( + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteScopeRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_scopes_empty_call_rest(): + client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GkeHubRestInterceptor(), + transport="rest", ) - client = GkeHubClient(transport=transport) - - with mock.patch.object( - type(client.transport._session), "request" - ) as req, mock.patch.object( - path_template, "transcode" - ) as transcode, mock.patch.object( - transports.GkeHubRestInterceptor, "post_generate_connect_manifest" - ) as post, mock.patch.object( - transports.GkeHubRestInterceptor, "post_generate_connect_manifest_with_metadata" - ) as post_with_metadata, mock.patch.object( - transports.GkeHubRestInterceptor, "pre_generate_connect_manifest" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = service.GenerateConnectManifestRequest.pb( - service.GenerateConnectManifestRequest() - ) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = service.GenerateConnectManifestResponse.to_json( - service.GenerateConnectManifestResponse() - ) - req.return_value.content = return_value - request = service.GenerateConnectManifestRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.GenerateConnectManifestResponse() - post_with_metadata.return_value = ( - service.GenerateConnectManifestResponse(), - metadata, - ) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_scopes), "__call__") as call: + client.list_scopes(request=None) - client.generate_connect_manifest( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListScopesRequest() - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() + assert args[0] == request_msg -def test_initialize_client_w_rest(): +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_permitted_scopes_empty_call_rest(): client = GkeHubClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert client is not None + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_permitted_scopes), "__call__" + ) as call: + client.list_permitted_scopes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListPermittedScopesRequest() + + assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_list_memberships_empty_call_rest(): +def test_get_membership_binding_empty_call_rest(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_memberships), "__call__") as call: - client.list_memberships(request=None) + with mock.patch.object( + type(client.transport.get_membership_binding), "__call__" + ) as call: + client.get_membership_binding(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.ListMembershipsRequest() + request_msg = service.GetMembershipBindingRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_list_features_empty_call_rest(): +def test_create_membership_binding_empty_call_rest(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_features), "__call__") as call: - client.list_features(request=None) + with mock.patch.object( + type(client.transport.create_membership_binding), "__call__" + ) as call: + client.create_membership_binding(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.ListFeaturesRequest() + request_msg = service.CreateMembershipBindingRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_get_membership_empty_call_rest(): +def test_update_membership_binding_empty_call_rest(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_membership), "__call__") as call: - client.get_membership(request=None) + with mock.patch.object( + type(client.transport.update_membership_binding), "__call__" + ) as call: + client.update_membership_binding(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.GetMembershipRequest() + request_msg = service.UpdateMembershipBindingRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_get_feature_empty_call_rest(): +def test_delete_membership_binding_empty_call_rest(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_feature), "__call__") as call: - client.get_feature(request=None) + with mock.patch.object( + type(client.transport.delete_membership_binding), "__call__" + ) as call: + client.delete_membership_binding(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.GetFeatureRequest() + request_msg = service.DeleteMembershipBindingRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_create_membership_empty_call_rest(): +def test_list_membership_bindings_empty_call_rest(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -9663,41 +36981,43 @@ def test_create_membership_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_membership), "__call__" + type(client.transport.list_membership_bindings), "__call__" ) as call: - client.create_membership(request=None) + client.list_membership_bindings(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.CreateMembershipRequest() + request_msg = service.ListMembershipBindingsRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_create_feature_empty_call_rest(): +def test_get_membership_rbac_role_binding_empty_call_rest(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_feature), "__call__") as call: - client.create_feature(request=None) + with mock.patch.object( + type(client.transport.get_membership_rbac_role_binding), "__call__" + ) as call: + client.get_membership_rbac_role_binding(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.CreateFeatureRequest() + request_msg = service.GetMembershipRBACRoleBindingRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_delete_membership_empty_call_rest(): +def test_create_membership_rbac_role_binding_empty_call_rest(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -9705,41 +37025,43 @@ def test_delete_membership_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_membership), "__call__" + type(client.transport.create_membership_rbac_role_binding), "__call__" ) as call: - client.delete_membership(request=None) + client.create_membership_rbac_role_binding(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.DeleteMembershipRequest() + request_msg = service.CreateMembershipRBACRoleBindingRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_delete_feature_empty_call_rest(): +def test_update_membership_rbac_role_binding_empty_call_rest(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_feature), "__call__") as call: - client.delete_feature(request=None) + with mock.patch.object( + type(client.transport.update_membership_rbac_role_binding), "__call__" + ) as call: + client.update_membership_rbac_role_binding(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.DeleteFeatureRequest() + request_msg = service.UpdateMembershipRBACRoleBindingRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_update_membership_empty_call_rest(): +def test_delete_membership_rbac_role_binding_empty_call_rest(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -9747,41 +37069,43 @@ def test_update_membership_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_membership), "__call__" + type(client.transport.delete_membership_rbac_role_binding), "__call__" ) as call: - client.update_membership(request=None) + client.delete_membership_rbac_role_binding(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.UpdateMembershipRequest() + request_msg = service.DeleteMembershipRBACRoleBindingRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_update_feature_empty_call_rest(): +def test_list_membership_rbac_role_bindings_empty_call_rest(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_feature), "__call__") as call: - client.update_feature(request=None) + with mock.patch.object( + type(client.transport.list_membership_rbac_role_bindings), "__call__" + ) as call: + client.list_membership_rbac_role_bindings(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.UpdateFeatureRequest() + request_msg = service.ListMembershipRBACRoleBindingsRequest() assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. -def test_generate_connect_manifest_empty_call_rest(): +def test_generate_membership_rbac_role_binding_yaml_empty_call_rest(): client = GkeHubClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -9789,14 +37113,14 @@ def test_generate_connect_manifest_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.generate_connect_manifest), "__call__" + type(client.transport.generate_membership_rbac_role_binding_yaml), "__call__" ) as call: - client.generate_connect_manifest(request=None) + client.generate_membership_rbac_role_binding_yaml(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.GenerateConnectManifestRequest() + request_msg = service.GenerateMembershipRBACRoleBindingYAMLRequest() assert args[0] == request_msg @@ -9852,6 +37176,7 @@ def test_gke_hub_base_transport(): # raise NotImplementedError. methods = ( "list_memberships", + "list_bound_memberships", "list_features", "get_membership", "get_feature", @@ -9862,6 +37187,38 @@ def test_gke_hub_base_transport(): "update_membership", "update_feature", "generate_connect_manifest", + "create_fleet", + "get_fleet", + "update_fleet", + "delete_fleet", + "list_fleets", + "get_scope_namespace", + "create_scope_namespace", + "update_scope_namespace", + "delete_scope_namespace", + "list_scope_namespaces", + "get_scope_rbac_role_binding", + "create_scope_rbac_role_binding", + "update_scope_rbac_role_binding", + "delete_scope_rbac_role_binding", + "list_scope_rbac_role_bindings", + "get_scope", + "create_scope", + "update_scope", + "delete_scope", + "list_scopes", + "list_permitted_scopes", + "get_membership_binding", + "create_membership_binding", + "update_membership_binding", + "delete_membership_binding", + "list_membership_bindings", + "get_membership_rbac_role_binding", + "create_membership_rbac_role_binding", + "update_membership_rbac_role_binding", + "delete_membership_rbac_role_binding", + "list_membership_rbac_role_bindings", + "generate_membership_rbac_role_binding_yaml", ) for method in methods: with pytest.raises(NotImplementedError): @@ -10125,6 +37482,9 @@ def test_gke_hub_client_transport_session_collision(transport_name): session1 = client1.transport.list_memberships._session session2 = client2.transport.list_memberships._session assert session1 != session2 + session1 = client1.transport.list_bound_memberships._session + session2 = client2.transport.list_bound_memberships._session + assert session1 != session2 session1 = client1.transport.list_features._session session2 = client2.transport.list_features._session assert session1 != session2 @@ -10155,6 +37515,102 @@ def test_gke_hub_client_transport_session_collision(transport_name): session1 = client1.transport.generate_connect_manifest._session session2 = client2.transport.generate_connect_manifest._session assert session1 != session2 + session1 = client1.transport.create_fleet._session + session2 = client2.transport.create_fleet._session + assert session1 != session2 + session1 = client1.transport.get_fleet._session + session2 = client2.transport.get_fleet._session + assert session1 != session2 + session1 = client1.transport.update_fleet._session + session2 = client2.transport.update_fleet._session + assert session1 != session2 + session1 = client1.transport.delete_fleet._session + session2 = client2.transport.delete_fleet._session + assert session1 != session2 + session1 = client1.transport.list_fleets._session + session2 = client2.transport.list_fleets._session + assert session1 != session2 + session1 = client1.transport.get_scope_namespace._session + session2 = client2.transport.get_scope_namespace._session + assert session1 != session2 + session1 = client1.transport.create_scope_namespace._session + session2 = client2.transport.create_scope_namespace._session + assert session1 != session2 + session1 = client1.transport.update_scope_namespace._session + session2 = client2.transport.update_scope_namespace._session + assert session1 != session2 + session1 = client1.transport.delete_scope_namespace._session + session2 = client2.transport.delete_scope_namespace._session + assert session1 != session2 + session1 = client1.transport.list_scope_namespaces._session + session2 = client2.transport.list_scope_namespaces._session + assert session1 != session2 + session1 = client1.transport.get_scope_rbac_role_binding._session + session2 = client2.transport.get_scope_rbac_role_binding._session + assert session1 != session2 + session1 = client1.transport.create_scope_rbac_role_binding._session + session2 = client2.transport.create_scope_rbac_role_binding._session + assert session1 != session2 + session1 = client1.transport.update_scope_rbac_role_binding._session + session2 = client2.transport.update_scope_rbac_role_binding._session + assert session1 != session2 + session1 = client1.transport.delete_scope_rbac_role_binding._session + session2 = client2.transport.delete_scope_rbac_role_binding._session + assert session1 != session2 + session1 = client1.transport.list_scope_rbac_role_bindings._session + session2 = client2.transport.list_scope_rbac_role_bindings._session + assert session1 != session2 + session1 = client1.transport.get_scope._session + session2 = client2.transport.get_scope._session + assert session1 != session2 + session1 = client1.transport.create_scope._session + session2 = client2.transport.create_scope._session + assert session1 != session2 + session1 = client1.transport.update_scope._session + session2 = client2.transport.update_scope._session + assert session1 != session2 + session1 = client1.transport.delete_scope._session + session2 = client2.transport.delete_scope._session + assert session1 != session2 + session1 = client1.transport.list_scopes._session + session2 = client2.transport.list_scopes._session + assert session1 != session2 + session1 = client1.transport.list_permitted_scopes._session + session2 = client2.transport.list_permitted_scopes._session + assert session1 != session2 + session1 = client1.transport.get_membership_binding._session + session2 = client2.transport.get_membership_binding._session + assert session1 != session2 + session1 = client1.transport.create_membership_binding._session + session2 = client2.transport.create_membership_binding._session + assert session1 != session2 + session1 = client1.transport.update_membership_binding._session + session2 = client2.transport.update_membership_binding._session + assert session1 != session2 + session1 = client1.transport.delete_membership_binding._session + session2 = client2.transport.delete_membership_binding._session + assert session1 != session2 + session1 = client1.transport.list_membership_bindings._session + session2 = client2.transport.list_membership_bindings._session + assert session1 != session2 + session1 = client1.transport.get_membership_rbac_role_binding._session + session2 = client2.transport.get_membership_rbac_role_binding._session + assert session1 != session2 + session1 = client1.transport.create_membership_rbac_role_binding._session + session2 = client2.transport.create_membership_rbac_role_binding._session + assert session1 != session2 + session1 = client1.transport.update_membership_rbac_role_binding._session + session2 = client2.transport.update_membership_rbac_role_binding._session + assert session1 != session2 + session1 = client1.transport.delete_membership_rbac_role_binding._session + session2 = client2.transport.delete_membership_rbac_role_binding._session + assert session1 != session2 + session1 = client1.transport.list_membership_rbac_role_bindings._session + session2 = client2.transport.list_membership_rbac_role_bindings._session + assert session1 != session2 + session1 = client1.transport.generate_membership_rbac_role_binding_yaml._session + session2 = client2.transport.generate_membership_rbac_role_binding_yaml._session + assert session1 != session2 def test_gke_hub_grpc_transport_channel(): @@ -10336,10 +37792,36 @@ def test_parse_feature_path(): assert expected == actual -def test_membership_path(): +def test_fleet_path(): project = "cuttlefish" location = "mussel" - membership = "winkle" + fleet = "winkle" + expected = "projects/{project}/locations/{location}/fleets/{fleet}".format( + project=project, + location=location, + fleet=fleet, + ) + actual = GkeHubClient.fleet_path(project, location, fleet) + assert expected == actual + + +def test_parse_fleet_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "fleet": "abalone", + } + path = GkeHubClient.fleet_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubClient.parse_fleet_path(path) + assert expected == actual + + +def test_membership_path(): + project = "squid" + location = "clam" + membership = "whelk" expected = ( "projects/{project}/locations/{location}/memberships/{membership}".format( project=project, @@ -10353,9 +37835,9 @@ def test_membership_path(): def test_parse_membership_path(): expected = { - "project": "nautilus", - "location": "scallop", - "membership": "abalone", + "project": "octopus", + "location": "oyster", + "membership": "nudibranch", } path = GkeHubClient.membership_path(**expected) @@ -10364,6 +37846,123 @@ def test_parse_membership_path(): assert expected == actual +def test_membership_binding_path(): + project = "cuttlefish" + location = "mussel" + membership = "winkle" + membershipbinding = "nautilus" + expected = "projects/{project}/locations/{location}/memberships/{membership}/bindings/{membershipbinding}".format( + project=project, + location=location, + membership=membership, + membershipbinding=membershipbinding, + ) + actual = GkeHubClient.membership_binding_path( + project, location, membership, membershipbinding + ) + assert expected == actual + + +def test_parse_membership_binding_path(): + expected = { + "project": "scallop", + "location": "abalone", + "membership": "squid", + "membershipbinding": "clam", + } + path = GkeHubClient.membership_binding_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubClient.parse_membership_binding_path(path) + assert expected == actual + + +def test_namespace_path(): + project = "whelk" + location = "octopus" + scope = "oyster" + namespace = "nudibranch" + expected = "projects/{project}/locations/{location}/scopes/{scope}/namespaces/{namespace}".format( + project=project, + location=location, + scope=scope, + namespace=namespace, + ) + actual = GkeHubClient.namespace_path(project, location, scope, namespace) + assert expected == actual + + +def test_parse_namespace_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "scope": "winkle", + "namespace": "nautilus", + } + path = GkeHubClient.namespace_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubClient.parse_namespace_path(path) + assert expected == actual + + +def test_rbac_role_binding_path(): + project = "scallop" + location = "abalone" + scope = "squid" + rbacrolebinding = "clam" + expected = "projects/{project}/locations/{location}/scopes/{scope}/rbacrolebindings/{rbacrolebinding}".format( + project=project, + location=location, + scope=scope, + rbacrolebinding=rbacrolebinding, + ) + actual = GkeHubClient.rbac_role_binding_path( + project, location, scope, rbacrolebinding + ) + assert expected == actual + + +def test_parse_rbac_role_binding_path(): + expected = { + "project": "whelk", + "location": "octopus", + "scope": "oyster", + "rbacrolebinding": "nudibranch", + } + path = GkeHubClient.rbac_role_binding_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubClient.parse_rbac_role_binding_path(path) + assert expected == actual + + +def test_scope_path(): + project = "cuttlefish" + location = "mussel" + scope = "winkle" + expected = "projects/{project}/locations/{location}/scopes/{scope}".format( + project=project, + location=location, + scope=scope, + ) + actual = GkeHubClient.scope_path(project, location, scope) + assert expected == actual + + +def test_parse_scope_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "scope": "abalone", + } + path = GkeHubClient.scope_path(**expected) + + # Check that the path construction is reversible. + actual = GkeHubClient.parse_scope_path(path) + assert expected == actual + + def test_common_billing_account_path(): billing_account = "squid" expected = "billingAccounts/{billing_account}".format(