diff --git a/Dataform/samples/V1beta1/DataformClient/cancel_workflow_invocation.php b/Dataform/samples/V1beta1/DataformClient/cancel_workflow_invocation.php index ed375aa20efe..733c6c56d521 100644 --- a/Dataform/samples/V1beta1/DataformClient/cancel_workflow_invocation.php +++ b/Dataform/samples/V1beta1/DataformClient/cancel_workflow_invocation.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_CancelWorkflowInvocation_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\CancelWorkflowInvocationRequest; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; /** * Requests cancellation of a running WorkflowInvocation. @@ -37,9 +38,13 @@ function cancel_workflow_invocation_sample(string $formattedName): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new CancelWorkflowInvocationRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { - $dataformClient->cancelWorkflowInvocation($formattedName); + $dataformClient->cancelWorkflowInvocation($request); printf('Call completed successfully.' . PHP_EOL); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/commit_workspace_changes.php b/Dataform/samples/V1beta1/DataformClient/commit_workspace_changes.php index 3f62a26ed28b..71d1f93fa410 100644 --- a/Dataform/samples/V1beta1/DataformClient/commit_workspace_changes.php +++ b/Dataform/samples/V1beta1/DataformClient/commit_workspace_changes.php @@ -24,8 +24,9 @@ // [START dataform_v1beta1_generated_Dataform_CommitWorkspaceChanges_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; use Google\Cloud\Dataform\V1beta1\CommitAuthor; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\CommitWorkspaceChangesRequest; /** * Applies a Git commit for uncommitted files in a Workspace. @@ -43,14 +44,17 @@ function commit_workspace_changes_sample( // Create a client. $dataformClient = new DataformClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $author = (new CommitAuthor()) ->setName($authorName) ->setEmailAddress($authorEmailAddress); + $request = (new CommitWorkspaceChangesRequest()) + ->setName($formattedName) + ->setAuthor($author); // Call the API and handle any network failures. try { - $dataformClient->commitWorkspaceChanges($formattedName, $author); + $dataformClient->commitWorkspaceChanges($request); printf('Call completed successfully.' . PHP_EOL); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/create_compilation_result.php b/Dataform/samples/V1beta1/DataformClient/create_compilation_result.php index 484b7d11a1a7..7b290fd2f421 100644 --- a/Dataform/samples/V1beta1/DataformClient/create_compilation_result.php +++ b/Dataform/samples/V1beta1/DataformClient/create_compilation_result.php @@ -24,8 +24,9 @@ // [START dataform_v1beta1_generated_Dataform_CreateCompilationResult_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; use Google\Cloud\Dataform\V1beta1\CompilationResult; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\CreateCompilationResultRequest; /** * Creates a new CompilationResult in a given project and location. @@ -39,13 +40,16 @@ function create_compilation_result_sample(string $formattedParent): void // Create a client. $dataformClient = new DataformClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $compilationResult = new CompilationResult(); + $request = (new CreateCompilationResultRequest()) + ->setParent($formattedParent) + ->setCompilationResult($compilationResult); // Call the API and handle any network failures. try { /** @var CompilationResult $response */ - $response = $dataformClient->createCompilationResult($formattedParent, $compilationResult); + $response = $dataformClient->createCompilationResult($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/create_repository.php b/Dataform/samples/V1beta1/DataformClient/create_repository.php index 609db6f8b72a..fec2d0f7f16c 100644 --- a/Dataform/samples/V1beta1/DataformClient/create_repository.php +++ b/Dataform/samples/V1beta1/DataformClient/create_repository.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_CreateRepository_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\CreateRepositoryRequest; use Google\Cloud\Dataform\V1beta1\Repository; /** @@ -41,13 +42,17 @@ function create_repository_sample(string $formattedParent, string $repositoryId) // Create a client. $dataformClient = new DataformClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $repository = new Repository(); + $request = (new CreateRepositoryRequest()) + ->setParent($formattedParent) + ->setRepository($repository) + ->setRepositoryId($repositoryId); // Call the API and handle any network failures. try { /** @var Repository $response */ - $response = $dataformClient->createRepository($formattedParent, $repository, $repositoryId); + $response = $dataformClient->createRepository($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/create_workflow_invocation.php b/Dataform/samples/V1beta1/DataformClient/create_workflow_invocation.php index 2f42e7352664..0fe7f6b44385 100644 --- a/Dataform/samples/V1beta1/DataformClient/create_workflow_invocation.php +++ b/Dataform/samples/V1beta1/DataformClient/create_workflow_invocation.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_CreateWorkflowInvocation_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\CreateWorkflowInvocationRequest; use Google\Cloud\Dataform\V1beta1\WorkflowInvocation; /** @@ -39,13 +40,16 @@ function create_workflow_invocation_sample(string $formattedParent): void // Create a client. $dataformClient = new DataformClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $workflowInvocation = new WorkflowInvocation(); + $request = (new CreateWorkflowInvocationRequest()) + ->setParent($formattedParent) + ->setWorkflowInvocation($workflowInvocation); // Call the API and handle any network failures. try { /** @var WorkflowInvocation $response */ - $response = $dataformClient->createWorkflowInvocation($formattedParent, $workflowInvocation); + $response = $dataformClient->createWorkflowInvocation($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/create_workspace.php b/Dataform/samples/V1beta1/DataformClient/create_workspace.php index c51393d6dd94..90a6c2864565 100644 --- a/Dataform/samples/V1beta1/DataformClient/create_workspace.php +++ b/Dataform/samples/V1beta1/DataformClient/create_workspace.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_CreateWorkspace_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\CreateWorkspaceRequest; use Google\Cloud\Dataform\V1beta1\Workspace; /** @@ -41,13 +42,17 @@ function create_workspace_sample(string $formattedParent, string $workspaceId): // Create a client. $dataformClient = new DataformClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $workspace = new Workspace(); + $request = (new CreateWorkspaceRequest()) + ->setParent($formattedParent) + ->setWorkspace($workspace) + ->setWorkspaceId($workspaceId); // Call the API and handle any network failures. try { /** @var Workspace $response */ - $response = $dataformClient->createWorkspace($formattedParent, $workspace, $workspaceId); + $response = $dataformClient->createWorkspace($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/delete_repository.php b/Dataform/samples/V1beta1/DataformClient/delete_repository.php index 8ba8d2c087ec..5b38cb9449a1 100644 --- a/Dataform/samples/V1beta1/DataformClient/delete_repository.php +++ b/Dataform/samples/V1beta1/DataformClient/delete_repository.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_DeleteRepository_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\DeleteRepositoryRequest; /** * Deletes a single Repository. @@ -37,9 +38,13 @@ function delete_repository_sample(string $formattedName): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new DeleteRepositoryRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { - $dataformClient->deleteRepository($formattedName); + $dataformClient->deleteRepository($request); printf('Call completed successfully.' . PHP_EOL); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/delete_workflow_invocation.php b/Dataform/samples/V1beta1/DataformClient/delete_workflow_invocation.php index 7da13e06dd98..6fb3c446e4c6 100644 --- a/Dataform/samples/V1beta1/DataformClient/delete_workflow_invocation.php +++ b/Dataform/samples/V1beta1/DataformClient/delete_workflow_invocation.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_DeleteWorkflowInvocation_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\DeleteWorkflowInvocationRequest; /** * Deletes a single WorkflowInvocation. @@ -37,9 +38,13 @@ function delete_workflow_invocation_sample(string $formattedName): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new DeleteWorkflowInvocationRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { - $dataformClient->deleteWorkflowInvocation($formattedName); + $dataformClient->deleteWorkflowInvocation($request); printf('Call completed successfully.' . PHP_EOL); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/delete_workspace.php b/Dataform/samples/V1beta1/DataformClient/delete_workspace.php index 7649cbb97141..143173bc98bf 100644 --- a/Dataform/samples/V1beta1/DataformClient/delete_workspace.php +++ b/Dataform/samples/V1beta1/DataformClient/delete_workspace.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_DeleteWorkspace_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\DeleteWorkspaceRequest; /** * Deletes a single Workspace. @@ -37,9 +38,13 @@ function delete_workspace_sample(string $formattedName): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new DeleteWorkspaceRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { - $dataformClient->deleteWorkspace($formattedName); + $dataformClient->deleteWorkspace($request); printf('Call completed successfully.' . PHP_EOL); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/fetch_file_diff.php b/Dataform/samples/V1beta1/DataformClient/fetch_file_diff.php index cecc4c8762ae..4dd45ea0fda3 100644 --- a/Dataform/samples/V1beta1/DataformClient/fetch_file_diff.php +++ b/Dataform/samples/V1beta1/DataformClient/fetch_file_diff.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_FetchFileDiff_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\FetchFileDiffRequest; use Google\Cloud\Dataform\V1beta1\FetchFileDiffResponse; /** @@ -39,10 +40,15 @@ function fetch_file_diff_sample(string $formattedWorkspace, string $path): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new FetchFileDiffRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path); + // Call the API and handle any network failures. try { /** @var FetchFileDiffResponse $response */ - $response = $dataformClient->fetchFileDiff($formattedWorkspace, $path); + $response = $dataformClient->fetchFileDiff($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/fetch_file_git_statuses.php b/Dataform/samples/V1beta1/DataformClient/fetch_file_git_statuses.php index 7f3e9b5e2b20..cd923f1d8a70 100644 --- a/Dataform/samples/V1beta1/DataformClient/fetch_file_git_statuses.php +++ b/Dataform/samples/V1beta1/DataformClient/fetch_file_git_statuses.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_FetchFileGitStatuses_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\FetchFileGitStatusesRequest; use Google\Cloud\Dataform\V1beta1\FetchFileGitStatusesResponse; /** @@ -38,10 +39,14 @@ function fetch_file_git_statuses_sample(string $formattedName): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new FetchFileGitStatusesRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var FetchFileGitStatusesResponse $response */ - $response = $dataformClient->fetchFileGitStatuses($formattedName); + $response = $dataformClient->fetchFileGitStatuses($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/fetch_git_ahead_behind.php b/Dataform/samples/V1beta1/DataformClient/fetch_git_ahead_behind.php index bad78eada327..6d48215932e0 100644 --- a/Dataform/samples/V1beta1/DataformClient/fetch_git_ahead_behind.php +++ b/Dataform/samples/V1beta1/DataformClient/fetch_git_ahead_behind.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_FetchGitAheadBehind_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\FetchGitAheadBehindRequest; use Google\Cloud\Dataform\V1beta1\FetchGitAheadBehindResponse; /** @@ -38,10 +39,14 @@ function fetch_git_ahead_behind_sample(string $formattedName): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new FetchGitAheadBehindRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var FetchGitAheadBehindResponse $response */ - $response = $dataformClient->fetchGitAheadBehind($formattedName); + $response = $dataformClient->fetchGitAheadBehind($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/fetch_remote_branches.php b/Dataform/samples/V1beta1/DataformClient/fetch_remote_branches.php index 308c6354febd..39890fa0aeae 100644 --- a/Dataform/samples/V1beta1/DataformClient/fetch_remote_branches.php +++ b/Dataform/samples/V1beta1/DataformClient/fetch_remote_branches.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_FetchRemoteBranches_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\FetchRemoteBranchesRequest; use Google\Cloud\Dataform\V1beta1\FetchRemoteBranchesResponse; /** @@ -38,10 +39,14 @@ function fetch_remote_branches_sample(string $formattedName): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new FetchRemoteBranchesRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var FetchRemoteBranchesResponse $response */ - $response = $dataformClient->fetchRemoteBranches($formattedName); + $response = $dataformClient->fetchRemoteBranches($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/get_compilation_result.php b/Dataform/samples/V1beta1/DataformClient/get_compilation_result.php index 0907ce82b508..821a12da664c 100644 --- a/Dataform/samples/V1beta1/DataformClient/get_compilation_result.php +++ b/Dataform/samples/V1beta1/DataformClient/get_compilation_result.php @@ -24,8 +24,9 @@ // [START dataform_v1beta1_generated_Dataform_GetCompilationResult_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; use Google\Cloud\Dataform\V1beta1\CompilationResult; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\GetCompilationResultRequest; /** * Fetches a single CompilationResult. @@ -38,10 +39,14 @@ function get_compilation_result_sample(string $formattedName): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new GetCompilationResultRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var CompilationResult $response */ - $response = $dataformClient->getCompilationResult($formattedName); + $response = $dataformClient->getCompilationResult($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/get_location.php b/Dataform/samples/V1beta1/DataformClient/get_location.php index 7ea9b6d846a7..6b940601d283 100644 --- a/Dataform/samples/V1beta1/DataformClient/get_location.php +++ b/Dataform/samples/V1beta1/DataformClient/get_location.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_GetLocation_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Location\GetLocationRequest; use Google\Cloud\Location\Location; /** @@ -41,10 +42,13 @@ function get_location_sample(): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = new GetLocationRequest(); + // Call the API and handle any network failures. try { /** @var Location $response */ - $response = $dataformClient->getLocation(); + $response = $dataformClient->getLocation($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/get_repository.php b/Dataform/samples/V1beta1/DataformClient/get_repository.php index 4f3ad9d1f12d..79786ca5af88 100644 --- a/Dataform/samples/V1beta1/DataformClient/get_repository.php +++ b/Dataform/samples/V1beta1/DataformClient/get_repository.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_GetRepository_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\GetRepositoryRequest; use Google\Cloud\Dataform\V1beta1\Repository; /** @@ -38,10 +39,14 @@ function get_repository_sample(string $formattedName): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new GetRepositoryRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var Repository $response */ - $response = $dataformClient->getRepository($formattedName); + $response = $dataformClient->getRepository($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/get_workflow_invocation.php b/Dataform/samples/V1beta1/DataformClient/get_workflow_invocation.php index 6502477b57ec..6c245f38c8a7 100644 --- a/Dataform/samples/V1beta1/DataformClient/get_workflow_invocation.php +++ b/Dataform/samples/V1beta1/DataformClient/get_workflow_invocation.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_GetWorkflowInvocation_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\GetWorkflowInvocationRequest; use Google\Cloud\Dataform\V1beta1\WorkflowInvocation; /** @@ -38,10 +39,14 @@ function get_workflow_invocation_sample(string $formattedName): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new GetWorkflowInvocationRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var WorkflowInvocation $response */ - $response = $dataformClient->getWorkflowInvocation($formattedName); + $response = $dataformClient->getWorkflowInvocation($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/get_workspace.php b/Dataform/samples/V1beta1/DataformClient/get_workspace.php index 790cb62c107a..eec4d7707023 100644 --- a/Dataform/samples/V1beta1/DataformClient/get_workspace.php +++ b/Dataform/samples/V1beta1/DataformClient/get_workspace.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_GetWorkspace_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\GetWorkspaceRequest; use Google\Cloud\Dataform\V1beta1\Workspace; /** @@ -38,10 +39,14 @@ function get_workspace_sample(string $formattedName): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new GetWorkspaceRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var Workspace $response */ - $response = $dataformClient->getWorkspace($formattedName); + $response = $dataformClient->getWorkspace($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/install_npm_packages.php b/Dataform/samples/V1beta1/DataformClient/install_npm_packages.php index e10ae8b02272..c047c77c7ab9 100644 --- a/Dataform/samples/V1beta1/DataformClient/install_npm_packages.php +++ b/Dataform/samples/V1beta1/DataformClient/install_npm_packages.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_InstallNpmPackages_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\InstallNpmPackagesRequest; use Google\Cloud\Dataform\V1beta1\InstallNpmPackagesResponse; /** @@ -38,10 +39,14 @@ function install_npm_packages_sample(string $formattedWorkspace): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new InstallNpmPackagesRequest()) + ->setWorkspace($formattedWorkspace); + // Call the API and handle any network failures. try { /** @var InstallNpmPackagesResponse $response */ - $response = $dataformClient->installNpmPackages($formattedWorkspace); + $response = $dataformClient->installNpmPackages($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/list_compilation_results.php b/Dataform/samples/V1beta1/DataformClient/list_compilation_results.php index bcd5f4eaeb35..33712044004a 100644 --- a/Dataform/samples/V1beta1/DataformClient/list_compilation_results.php +++ b/Dataform/samples/V1beta1/DataformClient/list_compilation_results.php @@ -25,8 +25,9 @@ // [START dataform_v1beta1_generated_Dataform_ListCompilationResults_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; use Google\Cloud\Dataform\V1beta1\CompilationResult; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\ListCompilationResultsRequest; /** * Lists CompilationResults in a given Repository. @@ -40,10 +41,14 @@ function list_compilation_results_sample(string $formattedParent): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new ListCompilationResultsRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $dataformClient->listCompilationResults($formattedParent); + $response = $dataformClient->listCompilationResults($request); /** @var CompilationResult $element */ foreach ($response as $element) { diff --git a/Dataform/samples/V1beta1/DataformClient/list_locations.php b/Dataform/samples/V1beta1/DataformClient/list_locations.php index 9cfc1963e7bb..4dd17842788f 100644 --- a/Dataform/samples/V1beta1/DataformClient/list_locations.php +++ b/Dataform/samples/V1beta1/DataformClient/list_locations.php @@ -25,7 +25,8 @@ // [START dataform_v1beta1_generated_Dataform_ListLocations_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Location\ListLocationsRequest; use Google\Cloud\Location\Location; /** @@ -42,10 +43,13 @@ function list_locations_sample(): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = new ListLocationsRequest(); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $dataformClient->listLocations(); + $response = $dataformClient->listLocations($request); /** @var Location $element */ foreach ($response as $element) { diff --git a/Dataform/samples/V1beta1/DataformClient/list_repositories.php b/Dataform/samples/V1beta1/DataformClient/list_repositories.php index 475341ef18cf..0ef168a50d6e 100644 --- a/Dataform/samples/V1beta1/DataformClient/list_repositories.php +++ b/Dataform/samples/V1beta1/DataformClient/list_repositories.php @@ -25,7 +25,8 @@ // [START dataform_v1beta1_generated_Dataform_ListRepositories_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\ListRepositoriesRequest; use Google\Cloud\Dataform\V1beta1\Repository; /** @@ -40,10 +41,14 @@ function list_repositories_sample(string $formattedParent): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new ListRepositoriesRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $dataformClient->listRepositories($formattedParent); + $response = $dataformClient->listRepositories($request); /** @var Repository $element */ foreach ($response as $element) { diff --git a/Dataform/samples/V1beta1/DataformClient/list_workflow_invocations.php b/Dataform/samples/V1beta1/DataformClient/list_workflow_invocations.php index 83ce82eba98f..b0e43bb4637b 100644 --- a/Dataform/samples/V1beta1/DataformClient/list_workflow_invocations.php +++ b/Dataform/samples/V1beta1/DataformClient/list_workflow_invocations.php @@ -25,7 +25,8 @@ // [START dataform_v1beta1_generated_Dataform_ListWorkflowInvocations_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\ListWorkflowInvocationsRequest; use Google\Cloud\Dataform\V1beta1\WorkflowInvocation; /** @@ -40,10 +41,14 @@ function list_workflow_invocations_sample(string $formattedParent): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new ListWorkflowInvocationsRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $dataformClient->listWorkflowInvocations($formattedParent); + $response = $dataformClient->listWorkflowInvocations($request); /** @var WorkflowInvocation $element */ foreach ($response as $element) { diff --git a/Dataform/samples/V1beta1/DataformClient/list_workspaces.php b/Dataform/samples/V1beta1/DataformClient/list_workspaces.php index 51bacce39559..6b1413dccae9 100644 --- a/Dataform/samples/V1beta1/DataformClient/list_workspaces.php +++ b/Dataform/samples/V1beta1/DataformClient/list_workspaces.php @@ -25,7 +25,8 @@ // [START dataform_v1beta1_generated_Dataform_ListWorkspaces_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\ListWorkspacesRequest; use Google\Cloud\Dataform\V1beta1\Workspace; /** @@ -40,10 +41,14 @@ function list_workspaces_sample(string $formattedParent): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new ListWorkspacesRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $dataformClient->listWorkspaces($formattedParent); + $response = $dataformClient->listWorkspaces($request); /** @var Workspace $element */ foreach ($response as $element) { diff --git a/Dataform/samples/V1beta1/DataformClient/make_directory.php b/Dataform/samples/V1beta1/DataformClient/make_directory.php index 86b30dfdbc89..4039a5416a2b 100644 --- a/Dataform/samples/V1beta1/DataformClient/make_directory.php +++ b/Dataform/samples/V1beta1/DataformClient/make_directory.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_MakeDirectory_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\MakeDirectoryRequest; use Google\Cloud\Dataform\V1beta1\MakeDirectoryResponse; /** @@ -40,10 +41,15 @@ function make_directory_sample(string $formattedWorkspace, string $path): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new MakeDirectoryRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path); + // Call the API and handle any network failures. try { /** @var MakeDirectoryResponse $response */ - $response = $dataformClient->makeDirectory($formattedWorkspace, $path); + $response = $dataformClient->makeDirectory($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/move_directory.php b/Dataform/samples/V1beta1/DataformClient/move_directory.php index 4be7f72cef2a..01c2a6d6daf2 100644 --- a/Dataform/samples/V1beta1/DataformClient/move_directory.php +++ b/Dataform/samples/V1beta1/DataformClient/move_directory.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_MoveDirectory_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\MoveDirectoryRequest; use Google\Cloud\Dataform\V1beta1\MoveDirectoryResponse; /** @@ -43,10 +44,16 @@ function move_directory_sample(string $formattedWorkspace, string $path, string // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new MoveDirectoryRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path) + ->setNewPath($newPath); + // Call the API and handle any network failures. try { /** @var MoveDirectoryResponse $response */ - $response = $dataformClient->moveDirectory($formattedWorkspace, $path, $newPath); + $response = $dataformClient->moveDirectory($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/move_file.php b/Dataform/samples/V1beta1/DataformClient/move_file.php index aa7e1ffa036b..4039fb6c10bc 100644 --- a/Dataform/samples/V1beta1/DataformClient/move_file.php +++ b/Dataform/samples/V1beta1/DataformClient/move_file.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_MoveFile_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\MoveFileRequest; use Google\Cloud\Dataform\V1beta1\MoveFileResponse; /** @@ -40,10 +41,16 @@ function move_file_sample(string $formattedWorkspace, string $path, string $newP // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new MoveFileRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path) + ->setNewPath($newPath); + // Call the API and handle any network failures. try { /** @var MoveFileResponse $response */ - $response = $dataformClient->moveFile($formattedWorkspace, $path, $newPath); + $response = $dataformClient->moveFile($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/pull_git_commits.php b/Dataform/samples/V1beta1/DataformClient/pull_git_commits.php index 3a49080da36b..544b9d5158da 100644 --- a/Dataform/samples/V1beta1/DataformClient/pull_git_commits.php +++ b/Dataform/samples/V1beta1/DataformClient/pull_git_commits.php @@ -24,8 +24,9 @@ // [START dataform_v1beta1_generated_Dataform_PullGitCommits_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; use Google\Cloud\Dataform\V1beta1\CommitAuthor; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\PullGitCommitsRequest; /** * Pulls Git commits from the Repository's remote into a Workspace. @@ -43,14 +44,17 @@ function pull_git_commits_sample( // Create a client. $dataformClient = new DataformClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $author = (new CommitAuthor()) ->setName($authorName) ->setEmailAddress($authorEmailAddress); + $request = (new PullGitCommitsRequest()) + ->setName($formattedName) + ->setAuthor($author); // Call the API and handle any network failures. try { - $dataformClient->pullGitCommits($formattedName, $author); + $dataformClient->pullGitCommits($request); printf('Call completed successfully.' . PHP_EOL); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/push_git_commits.php b/Dataform/samples/V1beta1/DataformClient/push_git_commits.php index 6dbd56f471e6..cf02a066c914 100644 --- a/Dataform/samples/V1beta1/DataformClient/push_git_commits.php +++ b/Dataform/samples/V1beta1/DataformClient/push_git_commits.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_PushGitCommits_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\PushGitCommitsRequest; /** * Pushes Git commits from a Workspace to the Repository's remote. @@ -37,9 +38,13 @@ function push_git_commits_sample(string $formattedName): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new PushGitCommitsRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { - $dataformClient->pushGitCommits($formattedName); + $dataformClient->pushGitCommits($request); printf('Call completed successfully.' . PHP_EOL); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/query_compilation_result_actions.php b/Dataform/samples/V1beta1/DataformClient/query_compilation_result_actions.php index 698a33063934..60a5cfbbe73e 100644 --- a/Dataform/samples/V1beta1/DataformClient/query_compilation_result_actions.php +++ b/Dataform/samples/V1beta1/DataformClient/query_compilation_result_actions.php @@ -25,8 +25,9 @@ // [START dataform_v1beta1_generated_Dataform_QueryCompilationResultActions_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; use Google\Cloud\Dataform\V1beta1\CompilationResultAction; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\QueryCompilationResultActionsRequest; /** * Returns CompilationResultActions in a given CompilationResult. @@ -39,10 +40,14 @@ function query_compilation_result_actions_sample(string $formattedName): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new QueryCompilationResultActionsRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $dataformClient->queryCompilationResultActions($formattedName); + $response = $dataformClient->queryCompilationResultActions($request); /** @var CompilationResultAction $element */ foreach ($response as $element) { diff --git a/Dataform/samples/V1beta1/DataformClient/query_directory_contents.php b/Dataform/samples/V1beta1/DataformClient/query_directory_contents.php index 233201daf11b..939e07a9529a 100644 --- a/Dataform/samples/V1beta1/DataformClient/query_directory_contents.php +++ b/Dataform/samples/V1beta1/DataformClient/query_directory_contents.php @@ -25,7 +25,8 @@ // [START dataform_v1beta1_generated_Dataform_QueryDirectoryContents_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\QueryDirectoryContentsRequest; use Google\Cloud\Dataform\V1beta1\QueryDirectoryContentsResponse\DirectoryEntry; /** @@ -39,10 +40,14 @@ function query_directory_contents_sample(string $formattedWorkspace): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new QueryDirectoryContentsRequest()) + ->setWorkspace($formattedWorkspace); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $dataformClient->queryDirectoryContents($formattedWorkspace); + $response = $dataformClient->queryDirectoryContents($request); /** @var DirectoryEntry $element */ foreach ($response as $element) { diff --git a/Dataform/samples/V1beta1/DataformClient/query_workflow_invocation_actions.php b/Dataform/samples/V1beta1/DataformClient/query_workflow_invocation_actions.php index 59e8d9bc2338..8145bdb1dd29 100644 --- a/Dataform/samples/V1beta1/DataformClient/query_workflow_invocation_actions.php +++ b/Dataform/samples/V1beta1/DataformClient/query_workflow_invocation_actions.php @@ -25,7 +25,8 @@ // [START dataform_v1beta1_generated_Dataform_QueryWorkflowInvocationActions_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\QueryWorkflowInvocationActionsRequest; use Google\Cloud\Dataform\V1beta1\WorkflowInvocationAction; /** @@ -39,10 +40,14 @@ function query_workflow_invocation_actions_sample(string $formattedName): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new QueryWorkflowInvocationActionsRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $dataformClient->queryWorkflowInvocationActions($formattedName); + $response = $dataformClient->queryWorkflowInvocationActions($request); /** @var WorkflowInvocationAction $element */ foreach ($response as $element) { diff --git a/Dataform/samples/V1beta1/DataformClient/read_file.php b/Dataform/samples/V1beta1/DataformClient/read_file.php index e66869d35f99..a0cc0335fe74 100644 --- a/Dataform/samples/V1beta1/DataformClient/read_file.php +++ b/Dataform/samples/V1beta1/DataformClient/read_file.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_ReadFile_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\ReadFileRequest; use Google\Cloud\Dataform\V1beta1\ReadFileResponse; /** @@ -39,10 +40,15 @@ function read_file_sample(string $formattedWorkspace, string $path): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new ReadFileRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path); + // Call the API and handle any network failures. try { /** @var ReadFileResponse $response */ - $response = $dataformClient->readFile($formattedWorkspace, $path); + $response = $dataformClient->readFile($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/remove_directory.php b/Dataform/samples/V1beta1/DataformClient/remove_directory.php index 4b94ebcc383d..e0b25331af87 100644 --- a/Dataform/samples/V1beta1/DataformClient/remove_directory.php +++ b/Dataform/samples/V1beta1/DataformClient/remove_directory.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_RemoveDirectory_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\RemoveDirectoryRequest; /** * Deletes a directory (inside a Workspace) and all of its contents. @@ -39,9 +40,14 @@ function remove_directory_sample(string $formattedWorkspace, string $path): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new RemoveDirectoryRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path); + // Call the API and handle any network failures. try { - $dataformClient->removeDirectory($formattedWorkspace, $path); + $dataformClient->removeDirectory($request); printf('Call completed successfully.' . PHP_EOL); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/remove_file.php b/Dataform/samples/V1beta1/DataformClient/remove_file.php index dd24e5cd4c50..2712a00f96b9 100644 --- a/Dataform/samples/V1beta1/DataformClient/remove_file.php +++ b/Dataform/samples/V1beta1/DataformClient/remove_file.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_RemoveFile_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\RemoveFileRequest; /** * Deletes a file (inside a Workspace). @@ -38,9 +39,14 @@ function remove_file_sample(string $formattedWorkspace, string $path): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new RemoveFileRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path); + // Call the API and handle any network failures. try { - $dataformClient->removeFile($formattedWorkspace, $path); + $dataformClient->removeFile($request); printf('Call completed successfully.' . PHP_EOL); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/reset_workspace_changes.php b/Dataform/samples/V1beta1/DataformClient/reset_workspace_changes.php index 0193c2ef075b..6aed225cb3ad 100644 --- a/Dataform/samples/V1beta1/DataformClient/reset_workspace_changes.php +++ b/Dataform/samples/V1beta1/DataformClient/reset_workspace_changes.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_ResetWorkspaceChanges_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\ResetWorkspaceChangesRequest; /** * Performs a Git reset for uncommitted files in a Workspace. @@ -37,9 +38,13 @@ function reset_workspace_changes_sample(string $formattedName): void // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new ResetWorkspaceChangesRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { - $dataformClient->resetWorkspaceChanges($formattedName); + $dataformClient->resetWorkspaceChanges($request); printf('Call completed successfully.' . PHP_EOL); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/update_repository.php b/Dataform/samples/V1beta1/DataformClient/update_repository.php index c9c6f80276dd..641feaa273c2 100644 --- a/Dataform/samples/V1beta1/DataformClient/update_repository.php +++ b/Dataform/samples/V1beta1/DataformClient/update_repository.php @@ -24,8 +24,9 @@ // [START dataform_v1beta1_generated_Dataform_UpdateRepository_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; use Google\Cloud\Dataform\V1beta1\Repository; +use Google\Cloud\Dataform\V1beta1\UpdateRepositoryRequest; /** * Updates a single Repository. @@ -41,13 +42,15 @@ function update_repository_sample(): void // Create a client. $dataformClient = new DataformClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $repository = new Repository(); + $request = (new UpdateRepositoryRequest()) + ->setRepository($repository); // Call the API and handle any network failures. try { /** @var Repository $response */ - $response = $dataformClient->updateRepository($repository); + $response = $dataformClient->updateRepository($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/samples/V1beta1/DataformClient/write_file.php b/Dataform/samples/V1beta1/DataformClient/write_file.php index f1ab6908b51f..596d0fcc7c5a 100644 --- a/Dataform/samples/V1beta1/DataformClient/write_file.php +++ b/Dataform/samples/V1beta1/DataformClient/write_file.php @@ -24,7 +24,8 @@ // [START dataform_v1beta1_generated_Dataform_WriteFile_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Dataform\V1beta1\DataformClient; +use Google\Cloud\Dataform\V1beta1\Client\DataformClient; +use Google\Cloud\Dataform\V1beta1\WriteFileRequest; use Google\Cloud\Dataform\V1beta1\WriteFileResponse; /** @@ -40,10 +41,16 @@ function write_file_sample(string $formattedWorkspace, string $path, string $con // Create a client. $dataformClient = new DataformClient(); + // Prepare the request message. + $request = (new WriteFileRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path) + ->setContents($contents); + // Call the API and handle any network failures. try { /** @var WriteFileResponse $response */ - $response = $dataformClient->writeFile($formattedWorkspace, $path, $contents); + $response = $dataformClient->writeFile($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Dataform/src/V1beta1/Client/BaseClient/DataformBaseClient.php b/Dataform/src/V1beta1/Client/BaseClient/DataformBaseClient.php new file mode 100644 index 000000000000..f03ea97cd316 --- /dev/null +++ b/Dataform/src/V1beta1/Client/BaseClient/DataformBaseClient.php @@ -0,0 +1,1393 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/dataform_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/dataform_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/dataform_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/dataform_rest_client_config.php', + ], + ], + ]; + } + + /** + * Formats a string containing the fully-qualified path to represent a + * compilation_result resource. + * + * @param string $project + * @param string $location + * @param string $repository + * @param string $compilationResult + * + * @return string The formatted compilation_result resource. + * + * @experimental + */ + public static function compilationResultName(string $project, string $location, string $repository, string $compilationResult): string + { + return self::getPathTemplate('compilationResult')->render([ + 'project' => $project, + 'location' => $location, + 'repository' => $repository, + 'compilation_result' => $compilationResult, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a location + * resource. + * + * @param string $project + * @param string $location + * + * @return string The formatted location resource. + * + * @experimental + */ + public static function locationName(string $project, string $location): string + { + return self::getPathTemplate('location')->render([ + 'project' => $project, + 'location' => $location, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a repository + * resource. + * + * @param string $project + * @param string $location + * @param string $repository + * + * @return string The formatted repository resource. + * + * @experimental + */ + public static function repositoryName(string $project, string $location, string $repository): string + { + return self::getPathTemplate('repository')->render([ + 'project' => $project, + 'location' => $location, + 'repository' => $repository, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * secret_version resource. + * + * @param string $project + * @param string $secret + * @param string $version + * + * @return string The formatted secret_version resource. + * + * @experimental + */ + public static function secretVersionName(string $project, string $secret, string $version): string + { + return self::getPathTemplate('secretVersion')->render([ + 'project' => $project, + 'secret' => $secret, + 'version' => $version, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * workflow_invocation resource. + * + * @param string $project + * @param string $location + * @param string $repository + * @param string $workflowInvocation + * + * @return string The formatted workflow_invocation resource. + * + * @experimental + */ + public static function workflowInvocationName(string $project, string $location, string $repository, string $workflowInvocation): string + { + return self::getPathTemplate('workflowInvocation')->render([ + 'project' => $project, + 'location' => $location, + 'repository' => $repository, + 'workflow_invocation' => $workflowInvocation, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a workspace + * resource. + * + * @param string $project + * @param string $location + * @param string $repository + * @param string $workspace + * + * @return string The formatted workspace resource. + * + * @experimental + */ + public static function workspaceName(string $project, string $location, string $repository, string $workspace): string + { + return self::getPathTemplate('workspace')->render([ + 'project' => $project, + 'location' => $location, + 'repository' => $repository, + 'workspace' => $workspace, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - compilationResult: projects/{project}/locations/{location}/repositories/{repository}/compilationResults/{compilation_result} + * - location: projects/{project}/locations/{location} + * - repository: projects/{project}/locations/{location}/repositories/{repository} + * - secretVersion: projects/{project}/secrets/{secret}/versions/{version} + * - workflowInvocation: projects/{project}/locations/{location}/repositories/{repository}/workflowInvocations/{workflow_invocation} + * - workspace: projects/{project}/locations/{location}/repositories/{repository}/workspaces/{workspace} + * + * The optional $template argument can be supplied to specify a particular pattern, + * and must match one of the templates listed above. If no $template argument is + * provided, or if the $template argument does not match one of the templates + * listed, then parseName will check each of the supported templates, and return + * the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + * + * @experimental + */ + public static function parseName(string $formattedName, string $template = null): array + { + return self::parseFormattedName($formattedName, $template); + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'dataform.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + * + * @experimental + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Requests cancellation of a running WorkflowInvocation. + * + * The async variant is {@see self::cancelWorkflowInvocationAsync()} . + * + * @param CancelWorkflowInvocationRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function cancelWorkflowInvocation(CancelWorkflowInvocationRequest $request, array $callOptions = []): void + { + $this->startApiCall('CancelWorkflowInvocation', $request, $callOptions)->wait(); + } + + /** + * Applies a Git commit for uncommitted files in a Workspace. + * + * The async variant is {@see self::commitWorkspaceChangesAsync()} . + * + * @param CommitWorkspaceChangesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function commitWorkspaceChanges(CommitWorkspaceChangesRequest $request, array $callOptions = []): void + { + $this->startApiCall('CommitWorkspaceChanges', $request, $callOptions)->wait(); + } + + /** + * Creates a new CompilationResult in a given project and location. + * + * The async variant is {@see self::createCompilationResultAsync()} . + * + * @param CreateCompilationResultRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return CompilationResult + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function createCompilationResult(CreateCompilationResultRequest $request, array $callOptions = []): CompilationResult + { + return $this->startApiCall('CreateCompilationResult', $request, $callOptions)->wait(); + } + + /** + * Creates a new Repository in a given project and location. + * + * The async variant is {@see self::createRepositoryAsync()} . + * + * @param CreateRepositoryRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Repository + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function createRepository(CreateRepositoryRequest $request, array $callOptions = []): Repository + { + return $this->startApiCall('CreateRepository', $request, $callOptions)->wait(); + } + + /** + * Creates a new WorkflowInvocation in a given Repository. + * + * The async variant is {@see self::createWorkflowInvocationAsync()} . + * + * @param CreateWorkflowInvocationRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return WorkflowInvocation + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function createWorkflowInvocation(CreateWorkflowInvocationRequest $request, array $callOptions = []): WorkflowInvocation + { + return $this->startApiCall('CreateWorkflowInvocation', $request, $callOptions)->wait(); + } + + /** + * Creates a new Workspace in a given Repository. + * + * The async variant is {@see self::createWorkspaceAsync()} . + * + * @param CreateWorkspaceRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Workspace + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function createWorkspace(CreateWorkspaceRequest $request, array $callOptions = []): Workspace + { + return $this->startApiCall('CreateWorkspace', $request, $callOptions)->wait(); + } + + /** + * Deletes a single Repository. + * + * The async variant is {@see self::deleteRepositoryAsync()} . + * + * @param DeleteRepositoryRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function deleteRepository(DeleteRepositoryRequest $request, array $callOptions = []): void + { + $this->startApiCall('DeleteRepository', $request, $callOptions)->wait(); + } + + /** + * Deletes a single WorkflowInvocation. + * + * The async variant is {@see self::deleteWorkflowInvocationAsync()} . + * + * @param DeleteWorkflowInvocationRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function deleteWorkflowInvocation(DeleteWorkflowInvocationRequest $request, array $callOptions = []): void + { + $this->startApiCall('DeleteWorkflowInvocation', $request, $callOptions)->wait(); + } + + /** + * Deletes a single Workspace. + * + * The async variant is {@see self::deleteWorkspaceAsync()} . + * + * @param DeleteWorkspaceRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function deleteWorkspace(DeleteWorkspaceRequest $request, array $callOptions = []): void + { + $this->startApiCall('DeleteWorkspace', $request, $callOptions)->wait(); + } + + /** + * Fetches Git diff for an uncommitted file in a Workspace. + * + * The async variant is {@see self::fetchFileDiffAsync()} . + * + * @param FetchFileDiffRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return FetchFileDiffResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function fetchFileDiff(FetchFileDiffRequest $request, array $callOptions = []): FetchFileDiffResponse + { + return $this->startApiCall('FetchFileDiff', $request, $callOptions)->wait(); + } + + /** + * Fetches Git statuses for the files in a Workspace. + * + * The async variant is {@see self::fetchFileGitStatusesAsync()} . + * + * @param FetchFileGitStatusesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return FetchFileGitStatusesResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function fetchFileGitStatuses(FetchFileGitStatusesRequest $request, array $callOptions = []): FetchFileGitStatusesResponse + { + return $this->startApiCall('FetchFileGitStatuses', $request, $callOptions)->wait(); + } + + /** + * Fetches Git ahead/behind against a remote branch. + * + * The async variant is {@see self::fetchGitAheadBehindAsync()} . + * + * @param FetchGitAheadBehindRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return FetchGitAheadBehindResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function fetchGitAheadBehind(FetchGitAheadBehindRequest $request, array $callOptions = []): FetchGitAheadBehindResponse + { + return $this->startApiCall('FetchGitAheadBehind', $request, $callOptions)->wait(); + } + + /** + * Fetches a Repository's remote branches. + * + * The async variant is {@see self::fetchRemoteBranchesAsync()} . + * + * @param FetchRemoteBranchesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return FetchRemoteBranchesResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function fetchRemoteBranches(FetchRemoteBranchesRequest $request, array $callOptions = []): FetchRemoteBranchesResponse + { + return $this->startApiCall('FetchRemoteBranches', $request, $callOptions)->wait(); + } + + /** + * Fetches a single CompilationResult. + * + * The async variant is {@see self::getCompilationResultAsync()} . + * + * @param GetCompilationResultRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return CompilationResult + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function getCompilationResult(GetCompilationResultRequest $request, array $callOptions = []): CompilationResult + { + return $this->startApiCall('GetCompilationResult', $request, $callOptions)->wait(); + } + + /** + * Fetches a single Repository. + * + * The async variant is {@see self::getRepositoryAsync()} . + * + * @param GetRepositoryRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Repository + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function getRepository(GetRepositoryRequest $request, array $callOptions = []): Repository + { + return $this->startApiCall('GetRepository', $request, $callOptions)->wait(); + } + + /** + * Fetches a single WorkflowInvocation. + * + * The async variant is {@see self::getWorkflowInvocationAsync()} . + * + * @param GetWorkflowInvocationRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return WorkflowInvocation + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function getWorkflowInvocation(GetWorkflowInvocationRequest $request, array $callOptions = []): WorkflowInvocation + { + return $this->startApiCall('GetWorkflowInvocation', $request, $callOptions)->wait(); + } + + /** + * Fetches a single Workspace. + * + * The async variant is {@see self::getWorkspaceAsync()} . + * + * @param GetWorkspaceRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Workspace + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function getWorkspace(GetWorkspaceRequest $request, array $callOptions = []): Workspace + { + return $this->startApiCall('GetWorkspace', $request, $callOptions)->wait(); + } + + /** + * Installs dependency NPM packages (inside a Workspace). + * + * The async variant is {@see self::installNpmPackagesAsync()} . + * + * @param InstallNpmPackagesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return InstallNpmPackagesResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function installNpmPackages(InstallNpmPackagesRequest $request, array $callOptions = []): InstallNpmPackagesResponse + { + return $this->startApiCall('InstallNpmPackages', $request, $callOptions)->wait(); + } + + /** + * Lists CompilationResults in a given Repository. + * + * The async variant is {@see self::listCompilationResultsAsync()} . + * + * @param ListCompilationResultsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function listCompilationResults(ListCompilationResultsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListCompilationResults', $request, $callOptions); + } + + /** + * Lists Repositories in a given project and location. + * + * The async variant is {@see self::listRepositoriesAsync()} . + * + * @param ListRepositoriesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function listRepositories(ListRepositoriesRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListRepositories', $request, $callOptions); + } + + /** + * Lists WorkflowInvocations in a given Repository. + * + * The async variant is {@see self::listWorkflowInvocationsAsync()} . + * + * @param ListWorkflowInvocationsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function listWorkflowInvocations(ListWorkflowInvocationsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListWorkflowInvocations', $request, $callOptions); + } + + /** + * Lists Workspaces in a given Repository. + * + * The async variant is {@see self::listWorkspacesAsync()} . + * + * @param ListWorkspacesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function listWorkspaces(ListWorkspacesRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListWorkspaces', $request, $callOptions); + } + + /** + * Creates a directory inside a Workspace. + * + * The async variant is {@see self::makeDirectoryAsync()} . + * + * @param MakeDirectoryRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return MakeDirectoryResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function makeDirectory(MakeDirectoryRequest $request, array $callOptions = []): MakeDirectoryResponse + { + return $this->startApiCall('MakeDirectory', $request, $callOptions)->wait(); + } + + /** + * Moves a directory (inside a Workspace), and all of its contents, to a new + * location. + * + * The async variant is {@see self::moveDirectoryAsync()} . + * + * @param MoveDirectoryRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return MoveDirectoryResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function moveDirectory(MoveDirectoryRequest $request, array $callOptions = []): MoveDirectoryResponse + { + return $this->startApiCall('MoveDirectory', $request, $callOptions)->wait(); + } + + /** + * Moves a file (inside a Workspace) to a new location. + * + * The async variant is {@see self::moveFileAsync()} . + * + * @param MoveFileRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return MoveFileResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function moveFile(MoveFileRequest $request, array $callOptions = []): MoveFileResponse + { + return $this->startApiCall('MoveFile', $request, $callOptions)->wait(); + } + + /** + * Pulls Git commits from the Repository's remote into a Workspace. + * + * The async variant is {@see self::pullGitCommitsAsync()} . + * + * @param PullGitCommitsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function pullGitCommits(PullGitCommitsRequest $request, array $callOptions = []): void + { + $this->startApiCall('PullGitCommits', $request, $callOptions)->wait(); + } + + /** + * Pushes Git commits from a Workspace to the Repository's remote. + * + * The async variant is {@see self::pushGitCommitsAsync()} . + * + * @param PushGitCommitsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function pushGitCommits(PushGitCommitsRequest $request, array $callOptions = []): void + { + $this->startApiCall('PushGitCommits', $request, $callOptions)->wait(); + } + + /** + * Returns CompilationResultActions in a given CompilationResult. + * + * The async variant is {@see self::queryCompilationResultActionsAsync()} . + * + * @param QueryCompilationResultActionsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function queryCompilationResultActions(QueryCompilationResultActionsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('QueryCompilationResultActions', $request, $callOptions); + } + + /** + * Returns the contents of a given Workspace directory. + * + * The async variant is {@see self::queryDirectoryContentsAsync()} . + * + * @param QueryDirectoryContentsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function queryDirectoryContents(QueryDirectoryContentsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('QueryDirectoryContents', $request, $callOptions); + } + + /** + * Returns WorkflowInvocationActions in a given WorkflowInvocation. + * + * The async variant is {@see self::queryWorkflowInvocationActionsAsync()} . + * + * @param QueryWorkflowInvocationActionsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function queryWorkflowInvocationActions(QueryWorkflowInvocationActionsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('QueryWorkflowInvocationActions', $request, $callOptions); + } + + /** + * Returns the contents of a file (inside a Workspace). + * + * The async variant is {@see self::readFileAsync()} . + * + * @param ReadFileRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return ReadFileResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function readFile(ReadFileRequest $request, array $callOptions = []): ReadFileResponse + { + return $this->startApiCall('ReadFile', $request, $callOptions)->wait(); + } + + /** + * Deletes a directory (inside a Workspace) and all of its contents. + * + * The async variant is {@see self::removeDirectoryAsync()} . + * + * @param RemoveDirectoryRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function removeDirectory(RemoveDirectoryRequest $request, array $callOptions = []): void + { + $this->startApiCall('RemoveDirectory', $request, $callOptions)->wait(); + } + + /** + * Deletes a file (inside a Workspace). + * + * The async variant is {@see self::removeFileAsync()} . + * + * @param RemoveFileRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function removeFile(RemoveFileRequest $request, array $callOptions = []): void + { + $this->startApiCall('RemoveFile', $request, $callOptions)->wait(); + } + + /** + * Performs a Git reset for uncommitted files in a Workspace. + * + * The async variant is {@see self::resetWorkspaceChangesAsync()} . + * + * @param ResetWorkspaceChangesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function resetWorkspaceChanges(ResetWorkspaceChangesRequest $request, array $callOptions = []): void + { + $this->startApiCall('ResetWorkspaceChanges', $request, $callOptions)->wait(); + } + + /** + * Updates a single Repository. + * + * The async variant is {@see self::updateRepositoryAsync()} . + * + * @param UpdateRepositoryRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Repository + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function updateRepository(UpdateRepositoryRequest $request, array $callOptions = []): Repository + { + return $this->startApiCall('UpdateRepository', $request, $callOptions)->wait(); + } + + /** + * Writes to a file (inside a Workspace). + * + * The async variant is {@see self::writeFileAsync()} . + * + * @param WriteFileRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return WriteFileResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function writeFile(WriteFileRequest $request, array $callOptions = []): WriteFileResponse + { + return $this->startApiCall('WriteFile', $request, $callOptions)->wait(); + } + + /** + * Gets information about a location. + * + * The async variant is {@see self::getLocationAsync()} . + * + * @param GetLocationRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Location + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function getLocation(GetLocationRequest $request, array $callOptions = []): Location + { + return $this->startApiCall('GetLocation', $request, $callOptions)->wait(); + } + + /** + * Lists information about the supported locations for this service. + * + * The async variant is {@see self::listLocationsAsync()} . + * + * @param ListLocationsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function listLocations(ListLocationsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListLocations', $request, $callOptions); + } +} diff --git a/Dataform/src/V1beta1/Client/DataformClient.php b/Dataform/src/V1beta1/Client/DataformClient.php new file mode 100644 index 000000000000..7346334af3fe --- /dev/null +++ b/Dataform/src/V1beta1/Client/DataformClient.php @@ -0,0 +1,42 @@ +setParent($parent) + ->setCompilationResult($compilationResult); + } + /** * Constructor. * diff --git a/Dataform/src/V1beta1/CreateRepositoryRequest.php b/Dataform/src/V1beta1/CreateRepositoryRequest.php index 5841622dd3ea..2127bab16066 100644 --- a/Dataform/src/V1beta1/CreateRepositoryRequest.php +++ b/Dataform/src/V1beta1/CreateRepositoryRequest.php @@ -36,6 +36,26 @@ class CreateRepositoryRequest extends \Google\Protobuf\Internal\Message */ private $repository_id = ''; + /** + * @param string $parent Required. The location in which to create the repository. Must be in the format + * `projects/*/locations/*`. Please see + * {@see DataformClient::locationName()} for help formatting this field. + * @param \Google\Cloud\Dataform\V1beta1\Repository $repository Required. The repository to create. + * @param string $repositoryId Required. The ID to use for the repository, which will become the final component of + * the repository's resource name. + * + * @return \Google\Cloud\Dataform\V1beta1\CreateRepositoryRequest + * + * @experimental + */ + public static function build(string $parent, \Google\Cloud\Dataform\V1beta1\Repository $repository, string $repositoryId): self + { + return (new self()) + ->setParent($parent) + ->setRepository($repository) + ->setRepositoryId($repositoryId); + } + /** * Constructor. * diff --git a/Dataform/src/V1beta1/CreateWorkflowInvocationRequest.php b/Dataform/src/V1beta1/CreateWorkflowInvocationRequest.php index 65887e6cc4e2..13f61c3f0787 100644 --- a/Dataform/src/V1beta1/CreateWorkflowInvocationRequest.php +++ b/Dataform/src/V1beta1/CreateWorkflowInvocationRequest.php @@ -29,6 +29,23 @@ class CreateWorkflowInvocationRequest extends \Google\Protobuf\Internal\Message */ private $workflow_invocation = null; + /** + * @param string $parent Required. The repository in which to create the workflow invocation. Must be in the + * format `projects/*/locations/*/repositories/*`. Please see + * {@see DataformClient::repositoryName()} for help formatting this field. + * @param \Google\Cloud\Dataform\V1beta1\WorkflowInvocation $workflowInvocation Required. The workflow invocation resource to create. + * + * @return \Google\Cloud\Dataform\V1beta1\CreateWorkflowInvocationRequest + * + * @experimental + */ + public static function build(string $parent, \Google\Cloud\Dataform\V1beta1\WorkflowInvocation $workflowInvocation): self + { + return (new self()) + ->setParent($parent) + ->setWorkflowInvocation($workflowInvocation); + } + /** * Constructor. * diff --git a/Dataform/src/V1beta1/CreateWorkspaceRequest.php b/Dataform/src/V1beta1/CreateWorkspaceRequest.php index 51c5f15c5377..88e4b857c1b3 100644 --- a/Dataform/src/V1beta1/CreateWorkspaceRequest.php +++ b/Dataform/src/V1beta1/CreateWorkspaceRequest.php @@ -36,6 +36,26 @@ class CreateWorkspaceRequest extends \Google\Protobuf\Internal\Message */ private $workspace_id = ''; + /** + * @param string $parent Required. The repository in which to create the workspace. Must be in the format + * `projects/*/locations/*/repositories/*`. Please see + * {@see DataformClient::repositoryName()} for help formatting this field. + * @param \Google\Cloud\Dataform\V1beta1\Workspace $workspace Required. The workspace to create. + * @param string $workspaceId Required. The ID to use for the workspace, which will become the final component of + * the workspace's resource name. + * + * @return \Google\Cloud\Dataform\V1beta1\CreateWorkspaceRequest + * + * @experimental + */ + public static function build(string $parent, \Google\Cloud\Dataform\V1beta1\Workspace $workspace, string $workspaceId): self + { + return (new self()) + ->setParent($parent) + ->setWorkspace($workspace) + ->setWorkspaceId($workspaceId); + } + /** * Constructor. * diff --git a/Dataform/src/V1beta1/DeleteRepositoryRequest.php b/Dataform/src/V1beta1/DeleteRepositoryRequest.php index d70d3dd5950e..f85235b9d56a 100644 --- a/Dataform/src/V1beta1/DeleteRepositoryRequest.php +++ b/Dataform/src/V1beta1/DeleteRepositoryRequest.php @@ -30,6 +30,20 @@ class DeleteRepositoryRequest extends \Google\Protobuf\Internal\Message */ private $force = false; + /** + * @param string $name Required. The repository's name. Please see + * {@see DataformClient::repositoryName()} for help formatting this field. + * + * @return \Google\Cloud\Dataform\V1beta1\DeleteRepositoryRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Dataform/src/V1beta1/DeleteWorkflowInvocationRequest.php b/Dataform/src/V1beta1/DeleteWorkflowInvocationRequest.php index 560b3f70340d..c38e09e0fd30 100644 --- a/Dataform/src/V1beta1/DeleteWorkflowInvocationRequest.php +++ b/Dataform/src/V1beta1/DeleteWorkflowInvocationRequest.php @@ -22,6 +22,20 @@ class DeleteWorkflowInvocationRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The workflow invocation resource's name. Please see + * {@see DataformClient::workflowInvocationName()} for help formatting this field. + * + * @return \Google\Cloud\Dataform\V1beta1\DeleteWorkflowInvocationRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Dataform/src/V1beta1/DeleteWorkspaceRequest.php b/Dataform/src/V1beta1/DeleteWorkspaceRequest.php index 264dd625d3f1..cf1d7fdb6167 100644 --- a/Dataform/src/V1beta1/DeleteWorkspaceRequest.php +++ b/Dataform/src/V1beta1/DeleteWorkspaceRequest.php @@ -22,6 +22,20 @@ class DeleteWorkspaceRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The workspace resource's name. Please see + * {@see DataformClient::workspaceName()} for help formatting this field. + * + * @return \Google\Cloud\Dataform\V1beta1\DeleteWorkspaceRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Dataform/src/V1beta1/GetCompilationResultRequest.php b/Dataform/src/V1beta1/GetCompilationResultRequest.php index 7aaa1075bde5..ec14cdd6b36a 100644 --- a/Dataform/src/V1beta1/GetCompilationResultRequest.php +++ b/Dataform/src/V1beta1/GetCompilationResultRequest.php @@ -22,6 +22,20 @@ class GetCompilationResultRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The compilation result's name. Please see + * {@see DataformClient::compilationResultName()} for help formatting this field. + * + * @return \Google\Cloud\Dataform\V1beta1\GetCompilationResultRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Dataform/src/V1beta1/GetRepositoryRequest.php b/Dataform/src/V1beta1/GetRepositoryRequest.php index 67ac4100f69e..5e8493e038dc 100644 --- a/Dataform/src/V1beta1/GetRepositoryRequest.php +++ b/Dataform/src/V1beta1/GetRepositoryRequest.php @@ -22,6 +22,20 @@ class GetRepositoryRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The repository's name. Please see + * {@see DataformClient::repositoryName()} for help formatting this field. + * + * @return \Google\Cloud\Dataform\V1beta1\GetRepositoryRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Dataform/src/V1beta1/GetWorkflowInvocationRequest.php b/Dataform/src/V1beta1/GetWorkflowInvocationRequest.php index f6b08ae77a3f..91590b4708e0 100644 --- a/Dataform/src/V1beta1/GetWorkflowInvocationRequest.php +++ b/Dataform/src/V1beta1/GetWorkflowInvocationRequest.php @@ -22,6 +22,20 @@ class GetWorkflowInvocationRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The workflow invocation resource's name. Please see + * {@see DataformClient::workflowInvocationName()} for help formatting this field. + * + * @return \Google\Cloud\Dataform\V1beta1\GetWorkflowInvocationRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Dataform/src/V1beta1/GetWorkspaceRequest.php b/Dataform/src/V1beta1/GetWorkspaceRequest.php index 496e404acf0c..a3c47482a6b8 100644 --- a/Dataform/src/V1beta1/GetWorkspaceRequest.php +++ b/Dataform/src/V1beta1/GetWorkspaceRequest.php @@ -22,6 +22,20 @@ class GetWorkspaceRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The workspace's name. Please see + * {@see DataformClient::workspaceName()} for help formatting this field. + * + * @return \Google\Cloud\Dataform\V1beta1\GetWorkspaceRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Dataform/src/V1beta1/ListCompilationResultsRequest.php b/Dataform/src/V1beta1/ListCompilationResultsRequest.php index 49237645f040..ab95cceb5f87 100644 --- a/Dataform/src/V1beta1/ListCompilationResultsRequest.php +++ b/Dataform/src/V1beta1/ListCompilationResultsRequest.php @@ -40,6 +40,21 @@ class ListCompilationResultsRequest extends \Google\Protobuf\Internal\Message */ private $page_token = ''; + /** + * @param string $parent Required. The repository in which to list compilation results. Must be in the + * format `projects/*/locations/*/repositories/*`. Please see + * {@see DataformClient::repositoryName()} for help formatting this field. + * + * @return \Google\Cloud\Dataform\V1beta1\ListCompilationResultsRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/Dataform/src/V1beta1/ListRepositoriesRequest.php b/Dataform/src/V1beta1/ListRepositoriesRequest.php index 48f9fe66822f..0a9690190f35 100644 --- a/Dataform/src/V1beta1/ListRepositoriesRequest.php +++ b/Dataform/src/V1beta1/ListRepositoriesRequest.php @@ -54,6 +54,21 @@ class ListRepositoriesRequest extends \Google\Protobuf\Internal\Message */ private $filter = ''; + /** + * @param string $parent Required. The location in which to list repositories. Must be in the format + * `projects/*/locations/*`. Please see + * {@see DataformClient::locationName()} for help formatting this field. + * + * @return \Google\Cloud\Dataform\V1beta1\ListRepositoriesRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/Dataform/src/V1beta1/ListWorkflowInvocationsRequest.php b/Dataform/src/V1beta1/ListWorkflowInvocationsRequest.php index 3c5e8c4d3746..685836c31e99 100644 --- a/Dataform/src/V1beta1/ListWorkflowInvocationsRequest.php +++ b/Dataform/src/V1beta1/ListWorkflowInvocationsRequest.php @@ -40,6 +40,21 @@ class ListWorkflowInvocationsRequest extends \Google\Protobuf\Internal\Message */ private $page_token = ''; + /** + * @param string $parent Required. The parent resource of the WorkflowInvocation type. Must be in the + * format `projects/*/locations/*/repositories/*`. Please see + * {@see DataformClient::repositoryName()} for help formatting this field. + * + * @return \Google\Cloud\Dataform\V1beta1\ListWorkflowInvocationsRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/Dataform/src/V1beta1/ListWorkspacesRequest.php b/Dataform/src/V1beta1/ListWorkspacesRequest.php index 2a26939a9321..3def0f3a3e69 100644 --- a/Dataform/src/V1beta1/ListWorkspacesRequest.php +++ b/Dataform/src/V1beta1/ListWorkspacesRequest.php @@ -54,6 +54,21 @@ class ListWorkspacesRequest extends \Google\Protobuf\Internal\Message */ private $filter = ''; + /** + * @param string $parent Required. The repository in which to list workspaces. Must be in the + * format `projects/*/locations/*/repositories/*`. Please see + * {@see DataformClient::repositoryName()} for help formatting this field. + * + * @return \Google\Cloud\Dataform\V1beta1\ListWorkspacesRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/Dataform/src/V1beta1/UpdateRepositoryRequest.php b/Dataform/src/V1beta1/UpdateRepositoryRequest.php index 52dab157b393..0d22cb229cd5 100644 --- a/Dataform/src/V1beta1/UpdateRepositoryRequest.php +++ b/Dataform/src/V1beta1/UpdateRepositoryRequest.php @@ -29,6 +29,22 @@ class UpdateRepositoryRequest extends \Google\Protobuf\Internal\Message */ private $repository = null; + /** + * @param \Google\Cloud\Dataform\V1beta1\Repository $repository Required. The repository to update. + * @param \Google\Protobuf\FieldMask $updateMask Optional. Specifies the fields to be updated in the repository. If left unset, + * all fields will be updated. + * + * @return \Google\Cloud\Dataform\V1beta1\UpdateRepositoryRequest + * + * @experimental + */ + public static function build(\Google\Cloud\Dataform\V1beta1\Repository $repository, \Google\Protobuf\FieldMask $updateMask): self + { + return (new self()) + ->setRepository($repository) + ->setUpdateMask($updateMask); + } + /** * Constructor. * diff --git a/Dataform/src/V1beta1/resources/dataform_descriptor_config.php b/Dataform/src/V1beta1/resources/dataform_descriptor_config.php index 9c77836ecc3c..2fb4914d841d 100644 --- a/Dataform/src/V1beta1/resources/dataform_descriptor_config.php +++ b/Dataform/src/V1beta1/resources/dataform_descriptor_config.php @@ -3,6 +3,222 @@ return [ 'interfaces' => [ 'google.cloud.dataform.v1beta1.Dataform' => [ + 'CancelWorkflowInvocation' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Protobuf\GPBEmpty', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'CommitWorkspaceChanges' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Protobuf\GPBEmpty', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'CreateCompilationResult' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\CompilationResult', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'CreateRepository' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\Repository', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'CreateWorkflowInvocation' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\WorkflowInvocation', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'CreateWorkspace' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\Workspace', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'DeleteRepository' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Protobuf\GPBEmpty', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'DeleteWorkflowInvocation' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Protobuf\GPBEmpty', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'DeleteWorkspace' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Protobuf\GPBEmpty', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'FetchFileDiff' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\FetchFileDiffResponse', + 'headerParams' => [ + [ + 'keyName' => 'workspace', + 'fieldAccessors' => [ + 'getWorkspace', + ], + ], + ], + ], + 'FetchFileGitStatuses' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\FetchFileGitStatusesResponse', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'FetchGitAheadBehind' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\FetchGitAheadBehindResponse', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'FetchRemoteBranches' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\FetchRemoteBranchesResponse', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetCompilationResult' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\CompilationResult', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetRepository' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\Repository', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetWorkflowInvocation' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\WorkflowInvocation', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetWorkspace' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\Workspace', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'InstallNpmPackages' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\InstallNpmPackagesResponse', + 'headerParams' => [ + [ + 'keyName' => 'workspace', + 'fieldAccessors' => [ + 'getWorkspace', + ], + ], + ], + ], 'ListCompilationResults' => [ 'pageStreaming' => [ 'requestPageTokenGetMethod' => 'getPageToken', @@ -12,6 +228,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getCompilationResults', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\ListCompilationResultsResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'ListRepositories' => [ 'pageStreaming' => [ @@ -22,6 +248,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getRepositories', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\ListRepositoriesResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'ListWorkflowInvocations' => [ 'pageStreaming' => [ @@ -32,6 +268,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getWorkflowInvocations', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\ListWorkflowInvocationsResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'ListWorkspaces' => [ 'pageStreaming' => [ @@ -42,6 +288,76 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getWorkspaces', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\ListWorkspacesResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'MakeDirectory' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\MakeDirectoryResponse', + 'headerParams' => [ + [ + 'keyName' => 'workspace', + 'fieldAccessors' => [ + 'getWorkspace', + ], + ], + ], + ], + 'MoveDirectory' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\MoveDirectoryResponse', + 'headerParams' => [ + [ + 'keyName' => 'workspace', + 'fieldAccessors' => [ + 'getWorkspace', + ], + ], + ], + ], + 'MoveFile' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\MoveFileResponse', + 'headerParams' => [ + [ + 'keyName' => 'workspace', + 'fieldAccessors' => [ + 'getWorkspace', + ], + ], + ], + ], + 'PullGitCommits' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Protobuf\GPBEmpty', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'PushGitCommits' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Protobuf\GPBEmpty', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'QueryCompilationResultActions' => [ 'pageStreaming' => [ @@ -52,6 +368,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getCompilationResultActions', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\QueryCompilationResultActionsResponse', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'QueryDirectoryContents' => [ 'pageStreaming' => [ @@ -62,6 +388,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getDirectoryEntries', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\QueryDirectoryContentsResponse', + 'headerParams' => [ + [ + 'keyName' => 'workspace', + 'fieldAccessors' => [ + 'getWorkspace', + ], + ], + ], ], 'QueryWorkflowInvocationActions' => [ 'pageStreaming' => [ @@ -72,8 +408,101 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getWorkflowInvocationActions', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\QueryWorkflowInvocationActionsResponse', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'ReadFile' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\ReadFileResponse', + 'headerParams' => [ + [ + 'keyName' => 'workspace', + 'fieldAccessors' => [ + 'getWorkspace', + ], + ], + ], + ], + 'RemoveDirectory' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Protobuf\GPBEmpty', + 'headerParams' => [ + [ + 'keyName' => 'workspace', + 'fieldAccessors' => [ + 'getWorkspace', + ], + ], + ], + ], + 'RemoveFile' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Protobuf\GPBEmpty', + 'headerParams' => [ + [ + 'keyName' => 'workspace', + 'fieldAccessors' => [ + 'getWorkspace', + ], + ], + ], + ], + 'ResetWorkspaceChanges' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Protobuf\GPBEmpty', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'UpdateRepository' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\Repository', + 'headerParams' => [ + [ + 'keyName' => 'repository.name', + 'fieldAccessors' => [ + 'getRepository', + 'getName', + ], + ], + ], + ], + 'WriteFile' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Dataform\V1beta1\WriteFileResponse', + 'headerParams' => [ + [ + 'keyName' => 'workspace', + 'fieldAccessors' => [ + 'getWorkspace', + ], + ], + ], ], 'GetLocation' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Location\Location', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], 'interfaceOverride' => 'google.cloud.location.Locations', ], 'ListLocations' => [ @@ -85,8 +514,26 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getLocations', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Location\ListLocationsResponse', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], 'interfaceOverride' => 'google.cloud.location.Locations', ], + 'templateMap' => [ + 'compilationResult' => 'projects/{project}/locations/{location}/repositories/{repository}/compilationResults/{compilation_result}', + 'location' => 'projects/{project}/locations/{location}', + 'repository' => 'projects/{project}/locations/{location}/repositories/{repository}', + 'secretVersion' => 'projects/{project}/secrets/{secret}/versions/{version}', + 'workflowInvocation' => 'projects/{project}/locations/{location}/repositories/{repository}/workflowInvocations/{workflow_invocation}', + 'workspace' => 'projects/{project}/locations/{location}/repositories/{repository}/workspaces/{workspace}', + ], ], ], ]; diff --git a/Dataform/tests/Unit/V1beta1/Client/DataformClientTest.php b/Dataform/tests/Unit/V1beta1/Client/DataformClientTest.php new file mode 100644 index 000000000000..e279e9298c4b --- /dev/null +++ b/Dataform/tests/Unit/V1beta1/Client/DataformClientTest.php @@ -0,0 +1,2736 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return DataformClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new DataformClient($options); + } + + /** @test */ + public function cancelWorkflowInvocationTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new GPBEmpty(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->workflowInvocationName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKFLOW_INVOCATION]'); + $request = (new CancelWorkflowInvocationRequest()) + ->setName($formattedName); + $gapicClient->cancelWorkflowInvocation($request); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/CancelWorkflowInvocation', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function cancelWorkflowInvocationExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->workflowInvocationName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKFLOW_INVOCATION]'); + $request = (new CancelWorkflowInvocationRequest()) + ->setName($formattedName); + try { + $gapicClient->cancelWorkflowInvocation($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function commitWorkspaceChangesTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new GPBEmpty(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $author = new CommitAuthor(); + $authorName = 'authorName-1501539658'; + $author->setName($authorName); + $authorEmailAddress = 'authorEmailAddress-6398493'; + $author->setEmailAddress($authorEmailAddress); + $request = (new CommitWorkspaceChangesRequest()) + ->setName($formattedName) + ->setAuthor($author); + $gapicClient->commitWorkspaceChanges($request); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/CommitWorkspaceChanges', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $actualValue = $actualRequestObject->getAuthor(); + $this->assertProtobufEquals($author, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function commitWorkspaceChangesExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $author = new CommitAuthor(); + $authorName = 'authorName-1501539658'; + $author->setName($authorName); + $authorEmailAddress = 'authorEmailAddress-6398493'; + $author->setEmailAddress($authorEmailAddress); + $request = (new CommitWorkspaceChangesRequest()) + ->setName($formattedName) + ->setAuthor($author); + try { + $gapicClient->commitWorkspaceChanges($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createCompilationResultTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name = 'name3373707'; + $gitCommitish = 'gitCommitish-459981894'; + $dataformCoreVersion = 'dataformCoreVersion1918089577'; + $expectedResponse = new CompilationResult(); + $expectedResponse->setName($name); + $expectedResponse->setGitCommitish($gitCommitish); + $expectedResponse->setDataformCoreVersion($dataformCoreVersion); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->repositoryName('[PROJECT]', '[LOCATION]', '[REPOSITORY]'); + $compilationResult = new CompilationResult(); + $request = (new CreateCompilationResultRequest()) + ->setParent($formattedParent) + ->setCompilationResult($compilationResult); + $response = $gapicClient->createCompilationResult($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/CreateCompilationResult', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualRequestObject->getCompilationResult(); + $this->assertProtobufEquals($compilationResult, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createCompilationResultExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->repositoryName('[PROJECT]', '[LOCATION]', '[REPOSITORY]'); + $compilationResult = new CompilationResult(); + $request = (new CreateCompilationResultRequest()) + ->setParent($formattedParent) + ->setCompilationResult($compilationResult); + try { + $gapicClient->createCompilationResult($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createRepositoryTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name = 'name3373707'; + $expectedResponse = new Repository(); + $expectedResponse->setName($name); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $repository = new Repository(); + $repositoryId = 'repositoryId1101683248'; + $request = (new CreateRepositoryRequest()) + ->setParent($formattedParent) + ->setRepository($repository) + ->setRepositoryId($repositoryId); + $response = $gapicClient->createRepository($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/CreateRepository', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualRequestObject->getRepository(); + $this->assertProtobufEquals($repository, $actualValue); + $actualValue = $actualRequestObject->getRepositoryId(); + $this->assertProtobufEquals($repositoryId, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createRepositoryExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $repository = new Repository(); + $repositoryId = 'repositoryId1101683248'; + $request = (new CreateRepositoryRequest()) + ->setParent($formattedParent) + ->setRepository($repository) + ->setRepositoryId($repositoryId); + try { + $gapicClient->createRepository($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createWorkflowInvocationTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name = 'name3373707'; + $compilationResult = 'compilationResult-2035984871'; + $expectedResponse = new WorkflowInvocation(); + $expectedResponse->setName($name); + $expectedResponse->setCompilationResult($compilationResult); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->repositoryName('[PROJECT]', '[LOCATION]', '[REPOSITORY]'); + $workflowInvocation = new WorkflowInvocation(); + $request = (new CreateWorkflowInvocationRequest()) + ->setParent($formattedParent) + ->setWorkflowInvocation($workflowInvocation); + $response = $gapicClient->createWorkflowInvocation($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/CreateWorkflowInvocation', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualRequestObject->getWorkflowInvocation(); + $this->assertProtobufEquals($workflowInvocation, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createWorkflowInvocationExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->repositoryName('[PROJECT]', '[LOCATION]', '[REPOSITORY]'); + $workflowInvocation = new WorkflowInvocation(); + $request = (new CreateWorkflowInvocationRequest()) + ->setParent($formattedParent) + ->setWorkflowInvocation($workflowInvocation); + try { + $gapicClient->createWorkflowInvocation($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createWorkspaceTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name = 'name3373707'; + $expectedResponse = new Workspace(); + $expectedResponse->setName($name); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->repositoryName('[PROJECT]', '[LOCATION]', '[REPOSITORY]'); + $workspace = new Workspace(); + $workspaceId = 'workspaceId1578483973'; + $request = (new CreateWorkspaceRequest()) + ->setParent($formattedParent) + ->setWorkspace($workspace) + ->setWorkspaceId($workspaceId); + $response = $gapicClient->createWorkspace($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/CreateWorkspace', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualRequestObject->getWorkspace(); + $this->assertProtobufEquals($workspace, $actualValue); + $actualValue = $actualRequestObject->getWorkspaceId(); + $this->assertProtobufEquals($workspaceId, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createWorkspaceExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->repositoryName('[PROJECT]', '[LOCATION]', '[REPOSITORY]'); + $workspace = new Workspace(); + $workspaceId = 'workspaceId1578483973'; + $request = (new CreateWorkspaceRequest()) + ->setParent($formattedParent) + ->setWorkspace($workspace) + ->setWorkspaceId($workspaceId); + try { + $gapicClient->createWorkspace($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function deleteRepositoryTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new GPBEmpty(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->repositoryName('[PROJECT]', '[LOCATION]', '[REPOSITORY]'); + $request = (new DeleteRepositoryRequest()) + ->setName($formattedName); + $gapicClient->deleteRepository($request); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/DeleteRepository', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function deleteRepositoryExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->repositoryName('[PROJECT]', '[LOCATION]', '[REPOSITORY]'); + $request = (new DeleteRepositoryRequest()) + ->setName($formattedName); + try { + $gapicClient->deleteRepository($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function deleteWorkflowInvocationTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new GPBEmpty(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->workflowInvocationName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKFLOW_INVOCATION]'); + $request = (new DeleteWorkflowInvocationRequest()) + ->setName($formattedName); + $gapicClient->deleteWorkflowInvocation($request); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/DeleteWorkflowInvocation', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function deleteWorkflowInvocationExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->workflowInvocationName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKFLOW_INVOCATION]'); + $request = (new DeleteWorkflowInvocationRequest()) + ->setName($formattedName); + try { + $gapicClient->deleteWorkflowInvocation($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function deleteWorkspaceTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new GPBEmpty(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $request = (new DeleteWorkspaceRequest()) + ->setName($formattedName); + $gapicClient->deleteWorkspace($request); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/DeleteWorkspace', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function deleteWorkspaceExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $request = (new DeleteWorkspaceRequest()) + ->setName($formattedName); + try { + $gapicClient->deleteWorkspace($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function fetchFileDiffTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $formattedDiff = 'formattedDiff-1687410264'; + $expectedResponse = new FetchFileDiffResponse(); + $expectedResponse->setFormattedDiff($formattedDiff); + $transport->addResponse($expectedResponse); + // Mock request + $formattedWorkspace = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $path = 'path3433509'; + $request = (new FetchFileDiffRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path); + $response = $gapicClient->fetchFileDiff($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/FetchFileDiff', $actualFuncCall); + $actualValue = $actualRequestObject->getWorkspace(); + $this->assertProtobufEquals($formattedWorkspace, $actualValue); + $actualValue = $actualRequestObject->getPath(); + $this->assertProtobufEquals($path, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function fetchFileDiffExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedWorkspace = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $path = 'path3433509'; + $request = (new FetchFileDiffRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path); + try { + $gapicClient->fetchFileDiff($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function fetchFileGitStatusesTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new FetchFileGitStatusesResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $request = (new FetchFileGitStatusesRequest()) + ->setName($formattedName); + $response = $gapicClient->fetchFileGitStatuses($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/FetchFileGitStatuses', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function fetchFileGitStatusesExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $request = (new FetchFileGitStatusesRequest()) + ->setName($formattedName); + try { + $gapicClient->fetchFileGitStatuses($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function fetchGitAheadBehindTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $commitsAhead = 1216483806; + $commitsBehind = 917751619; + $expectedResponse = new FetchGitAheadBehindResponse(); + $expectedResponse->setCommitsAhead($commitsAhead); + $expectedResponse->setCommitsBehind($commitsBehind); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $request = (new FetchGitAheadBehindRequest()) + ->setName($formattedName); + $response = $gapicClient->fetchGitAheadBehind($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/FetchGitAheadBehind', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function fetchGitAheadBehindExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $request = (new FetchGitAheadBehindRequest()) + ->setName($formattedName); + try { + $gapicClient->fetchGitAheadBehind($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function fetchRemoteBranchesTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new FetchRemoteBranchesResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->repositoryName('[PROJECT]', '[LOCATION]', '[REPOSITORY]'); + $request = (new FetchRemoteBranchesRequest()) + ->setName($formattedName); + $response = $gapicClient->fetchRemoteBranches($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/FetchRemoteBranches', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function fetchRemoteBranchesExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->repositoryName('[PROJECT]', '[LOCATION]', '[REPOSITORY]'); + $request = (new FetchRemoteBranchesRequest()) + ->setName($formattedName); + try { + $gapicClient->fetchRemoteBranches($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getCompilationResultTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $gitCommitish = 'gitCommitish-459981894'; + $dataformCoreVersion = 'dataformCoreVersion1918089577'; + $expectedResponse = new CompilationResult(); + $expectedResponse->setName($name2); + $expectedResponse->setGitCommitish($gitCommitish); + $expectedResponse->setDataformCoreVersion($dataformCoreVersion); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->compilationResultName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[COMPILATION_RESULT]'); + $request = (new GetCompilationResultRequest()) + ->setName($formattedName); + $response = $gapicClient->getCompilationResult($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/GetCompilationResult', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getCompilationResultExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->compilationResultName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[COMPILATION_RESULT]'); + $request = (new GetCompilationResultRequest()) + ->setName($formattedName); + try { + $gapicClient->getCompilationResult($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getRepositoryTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $expectedResponse = new Repository(); + $expectedResponse->setName($name2); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->repositoryName('[PROJECT]', '[LOCATION]', '[REPOSITORY]'); + $request = (new GetRepositoryRequest()) + ->setName($formattedName); + $response = $gapicClient->getRepository($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/GetRepository', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getRepositoryExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->repositoryName('[PROJECT]', '[LOCATION]', '[REPOSITORY]'); + $request = (new GetRepositoryRequest()) + ->setName($formattedName); + try { + $gapicClient->getRepository($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getWorkflowInvocationTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $compilationResult = 'compilationResult-2035984871'; + $expectedResponse = new WorkflowInvocation(); + $expectedResponse->setName($name2); + $expectedResponse->setCompilationResult($compilationResult); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->workflowInvocationName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKFLOW_INVOCATION]'); + $request = (new GetWorkflowInvocationRequest()) + ->setName($formattedName); + $response = $gapicClient->getWorkflowInvocation($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/GetWorkflowInvocation', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getWorkflowInvocationExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->workflowInvocationName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKFLOW_INVOCATION]'); + $request = (new GetWorkflowInvocationRequest()) + ->setName($formattedName); + try { + $gapicClient->getWorkflowInvocation($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getWorkspaceTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $expectedResponse = new Workspace(); + $expectedResponse->setName($name2); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $request = (new GetWorkspaceRequest()) + ->setName($formattedName); + $response = $gapicClient->getWorkspace($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/GetWorkspace', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getWorkspaceExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $request = (new GetWorkspaceRequest()) + ->setName($formattedName); + try { + $gapicClient->getWorkspace($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function installNpmPackagesTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new InstallNpmPackagesResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedWorkspace = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $request = (new InstallNpmPackagesRequest()) + ->setWorkspace($formattedWorkspace); + $response = $gapicClient->installNpmPackages($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/InstallNpmPackages', $actualFuncCall); + $actualValue = $actualRequestObject->getWorkspace(); + $this->assertProtobufEquals($formattedWorkspace, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function installNpmPackagesExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedWorkspace = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $request = (new InstallNpmPackagesRequest()) + ->setWorkspace($formattedWorkspace); + try { + $gapicClient->installNpmPackages($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listCompilationResultsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $compilationResultsElement = new CompilationResult(); + $compilationResults = [ + $compilationResultsElement, + ]; + $expectedResponse = new ListCompilationResultsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setCompilationResults($compilationResults); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->repositoryName('[PROJECT]', '[LOCATION]', '[REPOSITORY]'); + $request = (new ListCompilationResultsRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listCompilationResults($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getCompilationResults()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/ListCompilationResults', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listCompilationResultsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->repositoryName('[PROJECT]', '[LOCATION]', '[REPOSITORY]'); + $request = (new ListCompilationResultsRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listCompilationResults($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listRepositoriesTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $repositoriesElement = new Repository(); + $repositories = [ + $repositoriesElement, + ]; + $expectedResponse = new ListRepositoriesResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setRepositories($repositories); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListRepositoriesRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listRepositories($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getRepositories()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/ListRepositories', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listRepositoriesExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListRepositoriesRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listRepositories($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listWorkflowInvocationsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $workflowInvocationsElement = new WorkflowInvocation(); + $workflowInvocations = [ + $workflowInvocationsElement, + ]; + $expectedResponse = new ListWorkflowInvocationsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setWorkflowInvocations($workflowInvocations); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->repositoryName('[PROJECT]', '[LOCATION]', '[REPOSITORY]'); + $request = (new ListWorkflowInvocationsRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listWorkflowInvocations($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getWorkflowInvocations()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/ListWorkflowInvocations', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listWorkflowInvocationsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->repositoryName('[PROJECT]', '[LOCATION]', '[REPOSITORY]'); + $request = (new ListWorkflowInvocationsRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listWorkflowInvocations($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listWorkspacesTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $workspacesElement = new Workspace(); + $workspaces = [ + $workspacesElement, + ]; + $expectedResponse = new ListWorkspacesResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setWorkspaces($workspaces); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->repositoryName('[PROJECT]', '[LOCATION]', '[REPOSITORY]'); + $request = (new ListWorkspacesRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listWorkspaces($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getWorkspaces()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/ListWorkspaces', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listWorkspacesExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->repositoryName('[PROJECT]', '[LOCATION]', '[REPOSITORY]'); + $request = (new ListWorkspacesRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listWorkspaces($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function makeDirectoryTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new MakeDirectoryResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedWorkspace = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $path = 'path3433509'; + $request = (new MakeDirectoryRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path); + $response = $gapicClient->makeDirectory($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/MakeDirectory', $actualFuncCall); + $actualValue = $actualRequestObject->getWorkspace(); + $this->assertProtobufEquals($formattedWorkspace, $actualValue); + $actualValue = $actualRequestObject->getPath(); + $this->assertProtobufEquals($path, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function makeDirectoryExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedWorkspace = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $path = 'path3433509'; + $request = (new MakeDirectoryRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path); + try { + $gapicClient->makeDirectory($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function moveDirectoryTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new MoveDirectoryResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedWorkspace = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $path = 'path3433509'; + $newPath = 'newPath1377204068'; + $request = (new MoveDirectoryRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path) + ->setNewPath($newPath); + $response = $gapicClient->moveDirectory($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/MoveDirectory', $actualFuncCall); + $actualValue = $actualRequestObject->getWorkspace(); + $this->assertProtobufEquals($formattedWorkspace, $actualValue); + $actualValue = $actualRequestObject->getPath(); + $this->assertProtobufEquals($path, $actualValue); + $actualValue = $actualRequestObject->getNewPath(); + $this->assertProtobufEquals($newPath, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function moveDirectoryExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedWorkspace = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $path = 'path3433509'; + $newPath = 'newPath1377204068'; + $request = (new MoveDirectoryRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path) + ->setNewPath($newPath); + try { + $gapicClient->moveDirectory($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function moveFileTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new MoveFileResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedWorkspace = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $path = 'path3433509'; + $newPath = 'newPath1377204068'; + $request = (new MoveFileRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path) + ->setNewPath($newPath); + $response = $gapicClient->moveFile($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/MoveFile', $actualFuncCall); + $actualValue = $actualRequestObject->getWorkspace(); + $this->assertProtobufEquals($formattedWorkspace, $actualValue); + $actualValue = $actualRequestObject->getPath(); + $this->assertProtobufEquals($path, $actualValue); + $actualValue = $actualRequestObject->getNewPath(); + $this->assertProtobufEquals($newPath, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function moveFileExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedWorkspace = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $path = 'path3433509'; + $newPath = 'newPath1377204068'; + $request = (new MoveFileRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path) + ->setNewPath($newPath); + try { + $gapicClient->moveFile($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function pullGitCommitsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new GPBEmpty(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $author = new CommitAuthor(); + $authorName = 'authorName-1501539658'; + $author->setName($authorName); + $authorEmailAddress = 'authorEmailAddress-6398493'; + $author->setEmailAddress($authorEmailAddress); + $request = (new PullGitCommitsRequest()) + ->setName($formattedName) + ->setAuthor($author); + $gapicClient->pullGitCommits($request); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/PullGitCommits', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $actualValue = $actualRequestObject->getAuthor(); + $this->assertProtobufEquals($author, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function pullGitCommitsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $author = new CommitAuthor(); + $authorName = 'authorName-1501539658'; + $author->setName($authorName); + $authorEmailAddress = 'authorEmailAddress-6398493'; + $author->setEmailAddress($authorEmailAddress); + $request = (new PullGitCommitsRequest()) + ->setName($formattedName) + ->setAuthor($author); + try { + $gapicClient->pullGitCommits($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function pushGitCommitsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new GPBEmpty(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $request = (new PushGitCommitsRequest()) + ->setName($formattedName); + $gapicClient->pushGitCommits($request); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/PushGitCommits', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function pushGitCommitsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $request = (new PushGitCommitsRequest()) + ->setName($formattedName); + try { + $gapicClient->pushGitCommits($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function queryCompilationResultActionsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $compilationResultActionsElement = new CompilationResultAction(); + $compilationResultActions = [ + $compilationResultActionsElement, + ]; + $expectedResponse = new QueryCompilationResultActionsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setCompilationResultActions($compilationResultActions); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->compilationResultName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[COMPILATION_RESULT]'); + $request = (new QueryCompilationResultActionsRequest()) + ->setName($formattedName); + $response = $gapicClient->queryCompilationResultActions($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getCompilationResultActions()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/QueryCompilationResultActions', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function queryCompilationResultActionsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->compilationResultName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[COMPILATION_RESULT]'); + $request = (new QueryCompilationResultActionsRequest()) + ->setName($formattedName); + try { + $gapicClient->queryCompilationResultActions($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function queryDirectoryContentsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $directoryEntriesElement = new DirectoryEntry(); + $directoryEntries = [ + $directoryEntriesElement, + ]; + $expectedResponse = new QueryDirectoryContentsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setDirectoryEntries($directoryEntries); + $transport->addResponse($expectedResponse); + // Mock request + $formattedWorkspace = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $request = (new QueryDirectoryContentsRequest()) + ->setWorkspace($formattedWorkspace); + $response = $gapicClient->queryDirectoryContents($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getDirectoryEntries()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/QueryDirectoryContents', $actualFuncCall); + $actualValue = $actualRequestObject->getWorkspace(); + $this->assertProtobufEquals($formattedWorkspace, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function queryDirectoryContentsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedWorkspace = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $request = (new QueryDirectoryContentsRequest()) + ->setWorkspace($formattedWorkspace); + try { + $gapicClient->queryDirectoryContents($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function queryWorkflowInvocationActionsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $workflowInvocationActionsElement = new WorkflowInvocationAction(); + $workflowInvocationActions = [ + $workflowInvocationActionsElement, + ]; + $expectedResponse = new QueryWorkflowInvocationActionsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setWorkflowInvocationActions($workflowInvocationActions); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->workflowInvocationName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKFLOW_INVOCATION]'); + $request = (new QueryWorkflowInvocationActionsRequest()) + ->setName($formattedName); + $response = $gapicClient->queryWorkflowInvocationActions($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getWorkflowInvocationActions()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/QueryWorkflowInvocationActions', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function queryWorkflowInvocationActionsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->workflowInvocationName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKFLOW_INVOCATION]'); + $request = (new QueryWorkflowInvocationActionsRequest()) + ->setName($formattedName); + try { + $gapicClient->queryWorkflowInvocationActions($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function readFileTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $fileContents = '125'; + $expectedResponse = new ReadFileResponse(); + $expectedResponse->setFileContents($fileContents); + $transport->addResponse($expectedResponse); + // Mock request + $formattedWorkspace = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $path = 'path3433509'; + $request = (new ReadFileRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path); + $response = $gapicClient->readFile($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/ReadFile', $actualFuncCall); + $actualValue = $actualRequestObject->getWorkspace(); + $this->assertProtobufEquals($formattedWorkspace, $actualValue); + $actualValue = $actualRequestObject->getPath(); + $this->assertProtobufEquals($path, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function readFileExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedWorkspace = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $path = 'path3433509'; + $request = (new ReadFileRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path); + try { + $gapicClient->readFile($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function removeDirectoryTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new GPBEmpty(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedWorkspace = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $path = 'path3433509'; + $request = (new RemoveDirectoryRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path); + $gapicClient->removeDirectory($request); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/RemoveDirectory', $actualFuncCall); + $actualValue = $actualRequestObject->getWorkspace(); + $this->assertProtobufEquals($formattedWorkspace, $actualValue); + $actualValue = $actualRequestObject->getPath(); + $this->assertProtobufEquals($path, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function removeDirectoryExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedWorkspace = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $path = 'path3433509'; + $request = (new RemoveDirectoryRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path); + try { + $gapicClient->removeDirectory($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function removeFileTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new GPBEmpty(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedWorkspace = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $path = 'path3433509'; + $request = (new RemoveFileRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path); + $gapicClient->removeFile($request); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/RemoveFile', $actualFuncCall); + $actualValue = $actualRequestObject->getWorkspace(); + $this->assertProtobufEquals($formattedWorkspace, $actualValue); + $actualValue = $actualRequestObject->getPath(); + $this->assertProtobufEquals($path, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function removeFileExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedWorkspace = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $path = 'path3433509'; + $request = (new RemoveFileRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path); + try { + $gapicClient->removeFile($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function resetWorkspaceChangesTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new GPBEmpty(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $request = (new ResetWorkspaceChangesRequest()) + ->setName($formattedName); + $gapicClient->resetWorkspaceChanges($request); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/ResetWorkspaceChanges', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function resetWorkspaceChangesExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $request = (new ResetWorkspaceChangesRequest()) + ->setName($formattedName); + try { + $gapicClient->resetWorkspaceChanges($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function updateRepositoryTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name = 'name3373707'; + $expectedResponse = new Repository(); + $expectedResponse->setName($name); + $transport->addResponse($expectedResponse); + // Mock request + $repository = new Repository(); + $request = (new UpdateRepositoryRequest()) + ->setRepository($repository); + $response = $gapicClient->updateRepository($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/UpdateRepository', $actualFuncCall); + $actualValue = $actualRequestObject->getRepository(); + $this->assertProtobufEquals($repository, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function updateRepositoryExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $repository = new Repository(); + $request = (new UpdateRepositoryRequest()) + ->setRepository($repository); + try { + $gapicClient->updateRepository($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function writeFileTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new WriteFileResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedWorkspace = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $path = 'path3433509'; + $contents = '26'; + $request = (new WriteFileRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path) + ->setContents($contents); + $response = $gapicClient->writeFile($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/WriteFile', $actualFuncCall); + $actualValue = $actualRequestObject->getWorkspace(); + $this->assertProtobufEquals($formattedWorkspace, $actualValue); + $actualValue = $actualRequestObject->getPath(); + $this->assertProtobufEquals($path, $actualValue); + $actualValue = $actualRequestObject->getContents(); + $this->assertProtobufEquals($contents, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function writeFileExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedWorkspace = $gapicClient->workspaceName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKSPACE]'); + $path = 'path3433509'; + $contents = '26'; + $request = (new WriteFileRequest()) + ->setWorkspace($formattedWorkspace) + ->setPath($path) + ->setContents($contents); + try { + $gapicClient->writeFile($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getLocationTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $locationId = 'locationId552319461'; + $displayName = 'displayName1615086568'; + $expectedResponse = new Location(); + $expectedResponse->setName($name2); + $expectedResponse->setLocationId($locationId); + $expectedResponse->setDisplayName($displayName); + $transport->addResponse($expectedResponse); + $request = new GetLocationRequest(); + $response = $gapicClient->getLocation($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.location.Locations/GetLocation', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getLocationExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + $request = new GetLocationRequest(); + try { + $gapicClient->getLocation($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listLocationsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $locationsElement = new Location(); + $locations = [ + $locationsElement, + ]; + $expectedResponse = new ListLocationsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setLocations($locations); + $transport->addResponse($expectedResponse); + $request = new ListLocationsRequest(); + $response = $gapicClient->listLocations($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getLocations()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.location.Locations/ListLocations', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listLocationsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + $request = new ListLocationsRequest(); + try { + $gapicClient->listLocations($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function cancelWorkflowInvocationAsyncTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new GPBEmpty(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->workflowInvocationName('[PROJECT]', '[LOCATION]', '[REPOSITORY]', '[WORKFLOW_INVOCATION]'); + $request = (new CancelWorkflowInvocationRequest()) + ->setName($formattedName); + $gapicClient->cancelWorkflowInvocationAsync($request)->wait(); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.dataform.v1beta1.Dataform/CancelWorkflowInvocation', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } +} diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreClient/create_backup.php b/DataprocMetastore/samples/V1/DataprocMetastoreClient/create_backup.php index 71e359d7d943..2eac772b9a7c 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreClient/create_backup.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreClient/create_backup.php @@ -26,7 +26,8 @@ use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; use Google\Cloud\Metastore\V1\Backup; -use Google\Cloud\Metastore\V1\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\CreateBackupRequest; use Google\Rpc\Status; /** @@ -49,13 +50,17 @@ function create_backup_sample(string $formattedParent, string $backupId): void // Create a client. $dataprocMetastoreClient = new DataprocMetastoreClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $backup = new Backup(); + $request = (new CreateBackupRequest()) + ->setParent($formattedParent) + ->setBackupId($backupId) + ->setBackup($backup); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $dataprocMetastoreClient->createBackup($formattedParent, $backupId, $backup); + $response = $dataprocMetastoreClient->createBackup($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreClient/create_metadata_import.php b/DataprocMetastore/samples/V1/DataprocMetastoreClient/create_metadata_import.php index 9ff73e480ad5..8826b6c10f21 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreClient/create_metadata_import.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreClient/create_metadata_import.php @@ -25,7 +25,8 @@ // [START metastore_v1_generated_DataprocMetastore_CreateMetadataImport_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Metastore\V1\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\CreateMetadataImportRequest; use Google\Cloud\Metastore\V1\MetadataImport; use Google\Rpc\Status; @@ -49,17 +50,17 @@ function create_metadata_import_sample(string $formattedParent, string $metadata // Create a client. $dataprocMetastoreClient = new DataprocMetastoreClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $metadataImport = new MetadataImport(); + $request = (new CreateMetadataImportRequest()) + ->setParent($formattedParent) + ->setMetadataImportId($metadataImportId) + ->setMetadataImport($metadataImport); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $dataprocMetastoreClient->createMetadataImport( - $formattedParent, - $metadataImportId, - $metadataImport - ); + $response = $dataprocMetastoreClient->createMetadataImport($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreClient/create_service.php b/DataprocMetastore/samples/V1/DataprocMetastoreClient/create_service.php index f0d735201123..ff95c885d493 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreClient/create_service.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreClient/create_service.php @@ -25,7 +25,8 @@ // [START metastore_v1_generated_DataprocMetastore_CreateService_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Metastore\V1\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\CreateServiceRequest; use Google\Cloud\Metastore\V1\Service; use Google\Rpc\Status; @@ -49,13 +50,17 @@ function create_service_sample(string $formattedParent, string $serviceId): void // Create a client. $dataprocMetastoreClient = new DataprocMetastoreClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $service = new Service(); + $request = (new CreateServiceRequest()) + ->setParent($formattedParent) + ->setServiceId($serviceId) + ->setService($service); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $dataprocMetastoreClient->createService($formattedParent, $serviceId, $service); + $response = $dataprocMetastoreClient->createService($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreClient/delete_backup.php b/DataprocMetastore/samples/V1/DataprocMetastoreClient/delete_backup.php index 6ca9f548821a..16427ca91654 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreClient/delete_backup.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreClient/delete_backup.php @@ -25,7 +25,8 @@ // [START metastore_v1_generated_DataprocMetastore_DeleteBackup_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Metastore\V1\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\DeleteBackupRequest; use Google\Rpc\Status; /** @@ -42,10 +43,14 @@ function delete_backup_sample(string $formattedName): void // Create a client. $dataprocMetastoreClient = new DataprocMetastoreClient(); + // Prepare the request message. + $request = (new DeleteBackupRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $dataprocMetastoreClient->deleteBackup($formattedName); + $response = $dataprocMetastoreClient->deleteBackup($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreClient/delete_service.php b/DataprocMetastore/samples/V1/DataprocMetastoreClient/delete_service.php index 64311fec6882..3c0ac59ec3f4 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreClient/delete_service.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreClient/delete_service.php @@ -25,7 +25,8 @@ // [START metastore_v1_generated_DataprocMetastore_DeleteService_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Metastore\V1\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\DeleteServiceRequest; use Google\Rpc\Status; /** @@ -42,10 +43,14 @@ function delete_service_sample(string $formattedName): void // Create a client. $dataprocMetastoreClient = new DataprocMetastoreClient(); + // Prepare the request message. + $request = (new DeleteServiceRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $dataprocMetastoreClient->deleteService($formattedName); + $response = $dataprocMetastoreClient->deleteService($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreClient/export_metadata.php b/DataprocMetastore/samples/V1/DataprocMetastoreClient/export_metadata.php index 10bf14fb7e90..d9603e92c2f2 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreClient/export_metadata.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreClient/export_metadata.php @@ -25,7 +25,8 @@ // [START metastore_v1_generated_DataprocMetastore_ExportMetadata_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Metastore\V1\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\ExportMetadataRequest; use Google\Cloud\Metastore\V1\MetadataExport; use Google\Rpc\Status; @@ -43,10 +44,14 @@ function export_metadata_sample(string $formattedService): void // Create a client. $dataprocMetastoreClient = new DataprocMetastoreClient(); + // Prepare the request message. + $request = (new ExportMetadataRequest()) + ->setService($formattedService); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $dataprocMetastoreClient->exportMetadata($formattedService); + $response = $dataprocMetastoreClient->exportMetadata($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreClient/get_backup.php b/DataprocMetastore/samples/V1/DataprocMetastoreClient/get_backup.php index f93228cbbc26..499d77807578 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreClient/get_backup.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreClient/get_backup.php @@ -25,7 +25,8 @@ // [START metastore_v1_generated_DataprocMetastore_GetBackup_sync] use Google\ApiCore\ApiException; use Google\Cloud\Metastore\V1\Backup; -use Google\Cloud\Metastore\V1\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\GetBackupRequest; /** * Gets details of a single backup. @@ -41,10 +42,14 @@ function get_backup_sample(string $formattedName): void // Create a client. $dataprocMetastoreClient = new DataprocMetastoreClient(); + // Prepare the request message. + $request = (new GetBackupRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var Backup $response */ - $response = $dataprocMetastoreClient->getBackup($formattedName); + $response = $dataprocMetastoreClient->getBackup($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreClient/get_iam_policy.php b/DataprocMetastore/samples/V1/DataprocMetastoreClient/get_iam_policy.php index b3391453080c..ff2b200937bd 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreClient/get_iam_policy.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreClient/get_iam_policy.php @@ -24,8 +24,9 @@ // [START metastore_v1_generated_DataprocMetastore_GetIamPolicy_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Iam\V1\GetIamPolicyRequest; use Google\Cloud\Iam\V1\Policy; -use Google\Cloud\Metastore\V1\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreClient; /** * Gets the access control policy for a resource. Returns an empty policy @@ -39,10 +40,14 @@ function get_iam_policy_sample(string $resource): void // Create a client. $dataprocMetastoreClient = new DataprocMetastoreClient(); + // Prepare the request message. + $request = (new GetIamPolicyRequest()) + ->setResource($resource); + // Call the API and handle any network failures. try { /** @var Policy $response */ - $response = $dataprocMetastoreClient->getIamPolicy($resource); + $response = $dataprocMetastoreClient->getIamPolicy($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreClient/get_location.php b/DataprocMetastore/samples/V1/DataprocMetastoreClient/get_location.php index 3bd9d1d79318..10355f90bde7 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreClient/get_location.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreClient/get_location.php @@ -24,8 +24,9 @@ // [START metastore_v1_generated_DataprocMetastore_GetLocation_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Location\GetLocationRequest; use Google\Cloud\Location\Location; -use Google\Cloud\Metastore\V1\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreClient; /** * Gets information about a location. @@ -41,10 +42,13 @@ function get_location_sample(): void // Create a client. $dataprocMetastoreClient = new DataprocMetastoreClient(); + // Prepare the request message. + $request = new GetLocationRequest(); + // Call the API and handle any network failures. try { /** @var Location $response */ - $response = $dataprocMetastoreClient->getLocation(); + $response = $dataprocMetastoreClient->getLocation($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreClient/get_metadata_import.php b/DataprocMetastore/samples/V1/DataprocMetastoreClient/get_metadata_import.php index b52a8f4e2afc..f86573aec1d8 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreClient/get_metadata_import.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreClient/get_metadata_import.php @@ -24,7 +24,8 @@ // [START metastore_v1_generated_DataprocMetastore_GetMetadataImport_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Metastore\V1\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\GetMetadataImportRequest; use Google\Cloud\Metastore\V1\MetadataImport; /** @@ -41,10 +42,14 @@ function get_metadata_import_sample(string $formattedName): void // Create a client. $dataprocMetastoreClient = new DataprocMetastoreClient(); + // Prepare the request message. + $request = (new GetMetadataImportRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var MetadataImport $response */ - $response = $dataprocMetastoreClient->getMetadataImport($formattedName); + $response = $dataprocMetastoreClient->getMetadataImport($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreClient/get_service.php b/DataprocMetastore/samples/V1/DataprocMetastoreClient/get_service.php index dcc3b5f14955..7387fd7dd469 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreClient/get_service.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreClient/get_service.php @@ -24,7 +24,8 @@ // [START metastore_v1_generated_DataprocMetastore_GetService_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Metastore\V1\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\GetServiceRequest; use Google\Cloud\Metastore\V1\Service; /** @@ -41,10 +42,14 @@ function get_service_sample(string $formattedName): void // Create a client. $dataprocMetastoreClient = new DataprocMetastoreClient(); + // Prepare the request message. + $request = (new GetServiceRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var Service $response */ - $response = $dataprocMetastoreClient->getService($formattedName); + $response = $dataprocMetastoreClient->getService($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreClient/list_backups.php b/DataprocMetastore/samples/V1/DataprocMetastoreClient/list_backups.php index 0d188023bd1a..fd2b1e747fc4 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreClient/list_backups.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreClient/list_backups.php @@ -26,7 +26,8 @@ use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; use Google\Cloud\Metastore\V1\Backup; -use Google\Cloud\Metastore\V1\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\ListBackupsRequest; /** * Lists backups in a service. @@ -42,10 +43,14 @@ function list_backups_sample(string $formattedParent): void // Create a client. $dataprocMetastoreClient = new DataprocMetastoreClient(); + // Prepare the request message. + $request = (new ListBackupsRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $dataprocMetastoreClient->listBackups($formattedParent); + $response = $dataprocMetastoreClient->listBackups($request); /** @var Backup $element */ foreach ($response as $element) { diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreClient/list_locations.php b/DataprocMetastore/samples/V1/DataprocMetastoreClient/list_locations.php index 1df551880454..f5a53eca3bbc 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreClient/list_locations.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreClient/list_locations.php @@ -25,8 +25,9 @@ // [START metastore_v1_generated_DataprocMetastore_ListLocations_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; +use Google\Cloud\Location\ListLocationsRequest; use Google\Cloud\Location\Location; -use Google\Cloud\Metastore\V1\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreClient; /** * Lists information about the supported locations for this service. @@ -42,10 +43,13 @@ function list_locations_sample(): void // Create a client. $dataprocMetastoreClient = new DataprocMetastoreClient(); + // Prepare the request message. + $request = new ListLocationsRequest(); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $dataprocMetastoreClient->listLocations(); + $response = $dataprocMetastoreClient->listLocations($request); /** @var Location $element */ foreach ($response as $element) { diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreClient/list_metadata_imports.php b/DataprocMetastore/samples/V1/DataprocMetastoreClient/list_metadata_imports.php index c1e672317eb9..0c68d39b4c0c 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreClient/list_metadata_imports.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreClient/list_metadata_imports.php @@ -25,7 +25,8 @@ // [START metastore_v1_generated_DataprocMetastore_ListMetadataImports_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\Metastore\V1\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\ListMetadataImportsRequest; use Google\Cloud\Metastore\V1\MetadataImport; /** @@ -42,10 +43,14 @@ function list_metadata_imports_sample(string $formattedParent): void // Create a client. $dataprocMetastoreClient = new DataprocMetastoreClient(); + // Prepare the request message. + $request = (new ListMetadataImportsRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $dataprocMetastoreClient->listMetadataImports($formattedParent); + $response = $dataprocMetastoreClient->listMetadataImports($request); /** @var MetadataImport $element */ foreach ($response as $element) { diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreClient/list_services.php b/DataprocMetastore/samples/V1/DataprocMetastoreClient/list_services.php index 7763b6077266..46ceb3c06d64 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreClient/list_services.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreClient/list_services.php @@ -25,7 +25,8 @@ // [START metastore_v1_generated_DataprocMetastore_ListServices_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\Metastore\V1\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\ListServicesRequest; use Google\Cloud\Metastore\V1\Service; /** @@ -42,10 +43,14 @@ function list_services_sample(string $formattedParent): void // Create a client. $dataprocMetastoreClient = new DataprocMetastoreClient(); + // Prepare the request message. + $request = (new ListServicesRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $dataprocMetastoreClient->listServices($formattedParent); + $response = $dataprocMetastoreClient->listServices($request); /** @var Service $element */ foreach ($response as $element) { diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreClient/restore_service.php b/DataprocMetastore/samples/V1/DataprocMetastoreClient/restore_service.php index eef63152be9c..917550cda15a 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreClient/restore_service.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreClient/restore_service.php @@ -25,8 +25,9 @@ // [START metastore_v1_generated_DataprocMetastore_RestoreService_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Metastore\V1\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreClient; use Google\Cloud\Metastore\V1\Restore; +use Google\Cloud\Metastore\V1\RestoreServiceRequest; use Google\Rpc\Status; /** @@ -48,10 +49,15 @@ function restore_service_sample(string $formattedService, string $formattedBacku // Create a client. $dataprocMetastoreClient = new DataprocMetastoreClient(); + // Prepare the request message. + $request = (new RestoreServiceRequest()) + ->setService($formattedService) + ->setBackup($formattedBackup); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $dataprocMetastoreClient->restoreService($formattedService, $formattedBackup); + $response = $dataprocMetastoreClient->restoreService($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreClient/set_iam_policy.php b/DataprocMetastore/samples/V1/DataprocMetastoreClient/set_iam_policy.php index 7bb63ef82984..121d4cbe31c0 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreClient/set_iam_policy.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreClient/set_iam_policy.php @@ -25,7 +25,8 @@ // [START metastore_v1_generated_DataprocMetastore_SetIamPolicy_sync] use Google\ApiCore\ApiException; use Google\Cloud\Iam\V1\Policy; -use Google\Cloud\Metastore\V1\DataprocMetastoreClient; +use Google\Cloud\Iam\V1\SetIamPolicyRequest; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreClient; /** * Sets the access control policy on the specified resource. Replaces @@ -42,13 +43,16 @@ function set_iam_policy_sample(string $resource): void // Create a client. $dataprocMetastoreClient = new DataprocMetastoreClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $policy = new Policy(); + $request = (new SetIamPolicyRequest()) + ->setResource($resource) + ->setPolicy($policy); // Call the API and handle any network failures. try { /** @var Policy $response */ - $response = $dataprocMetastoreClient->setIamPolicy($resource, $policy); + $response = $dataprocMetastoreClient->setIamPolicy($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreClient/test_iam_permissions.php b/DataprocMetastore/samples/V1/DataprocMetastoreClient/test_iam_permissions.php index 2d41e61f6f82..0de4b26974e3 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreClient/test_iam_permissions.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreClient/test_iam_permissions.php @@ -24,8 +24,9 @@ // [START metastore_v1_generated_DataprocMetastore_TestIamPermissions_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Iam\V1\TestIamPermissionsRequest; use Google\Cloud\Iam\V1\TestIamPermissionsResponse; -use Google\Cloud\Metastore\V1\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreClient; /** * Returns permissions that a caller has on the specified resource. If the @@ -48,13 +49,16 @@ function test_iam_permissions_sample(string $resource, string $permissionsElemen // Create a client. $dataprocMetastoreClient = new DataprocMetastoreClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $permissions = [$permissionsElement,]; + $request = (new TestIamPermissionsRequest()) + ->setResource($resource) + ->setPermissions($permissions); // Call the API and handle any network failures. try { /** @var TestIamPermissionsResponse $response */ - $response = $dataprocMetastoreClient->testIamPermissions($resource, $permissions); + $response = $dataprocMetastoreClient->testIamPermissions($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreClient/update_metadata_import.php b/DataprocMetastore/samples/V1/DataprocMetastoreClient/update_metadata_import.php index efde62375128..9993fa0e9139 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreClient/update_metadata_import.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreClient/update_metadata_import.php @@ -25,8 +25,9 @@ // [START metastore_v1_generated_DataprocMetastore_UpdateMetadataImport_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Metastore\V1\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreClient; use Google\Cloud\Metastore\V1\MetadataImport; +use Google\Cloud\Metastore\V1\UpdateMetadataImportRequest; use Google\Protobuf\FieldMask; use Google\Rpc\Status; @@ -45,14 +46,17 @@ function update_metadata_import_sample(): void // Create a client. $dataprocMetastoreClient = new DataprocMetastoreClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $updateMask = new FieldMask(); $metadataImport = new MetadataImport(); + $request = (new UpdateMetadataImportRequest()) + ->setUpdateMask($updateMask) + ->setMetadataImport($metadataImport); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $dataprocMetastoreClient->updateMetadataImport($updateMask, $metadataImport); + $response = $dataprocMetastoreClient->updateMetadataImport($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreClient/update_service.php b/DataprocMetastore/samples/V1/DataprocMetastoreClient/update_service.php index 7d6bcd968f3e..f61d80d6e75b 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreClient/update_service.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreClient/update_service.php @@ -25,8 +25,9 @@ // [START metastore_v1_generated_DataprocMetastore_UpdateService_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Metastore\V1\DataprocMetastoreClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreClient; use Google\Cloud\Metastore\V1\Service; +use Google\Cloud\Metastore\V1\UpdateServiceRequest; use Google\Protobuf\FieldMask; use Google\Rpc\Status; @@ -44,14 +45,17 @@ function update_service_sample(): void // Create a client. $dataprocMetastoreClient = new DataprocMetastoreClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $updateMask = new FieldMask(); $service = new Service(); + $request = (new UpdateServiceRequest()) + ->setUpdateMask($updateMask) + ->setService($service); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $dataprocMetastoreClient->updateService($updateMask, $service); + $response = $dataprocMetastoreClient->updateService($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/create_federation.php b/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/create_federation.php index 13573eb4d550..a30ae858135e 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/create_federation.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/create_federation.php @@ -25,7 +25,8 @@ // [START metastore_v1_generated_DataprocMetastoreFederation_CreateFederation_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Metastore\V1\DataprocMetastoreFederationClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreFederationClient; +use Google\Cloud\Metastore\V1\CreateFederationRequest; use Google\Cloud\Metastore\V1\Federation; use Google\Rpc\Status; @@ -49,17 +50,17 @@ function create_federation_sample(string $formattedParent, string $federationId) // Create a client. $dataprocMetastoreFederationClient = new DataprocMetastoreFederationClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $federation = new Federation(); + $request = (new CreateFederationRequest()) + ->setParent($formattedParent) + ->setFederationId($federationId) + ->setFederation($federation); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $dataprocMetastoreFederationClient->createFederation( - $formattedParent, - $federationId, - $federation - ); + $response = $dataprocMetastoreFederationClient->createFederation($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/delete_federation.php b/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/delete_federation.php index 9bc155b00d97..f2b769ac8435 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/delete_federation.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/delete_federation.php @@ -25,7 +25,8 @@ // [START metastore_v1_generated_DataprocMetastoreFederation_DeleteFederation_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Metastore\V1\DataprocMetastoreFederationClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreFederationClient; +use Google\Cloud\Metastore\V1\DeleteFederationRequest; use Google\Rpc\Status; /** @@ -42,10 +43,14 @@ function delete_federation_sample(string $formattedName): void // Create a client. $dataprocMetastoreFederationClient = new DataprocMetastoreFederationClient(); + // Prepare the request message. + $request = (new DeleteFederationRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $dataprocMetastoreFederationClient->deleteFederation($formattedName); + $response = $dataprocMetastoreFederationClient->deleteFederation($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/get_federation.php b/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/get_federation.php index 41e0c5965701..ffb43a534cee 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/get_federation.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/get_federation.php @@ -24,8 +24,9 @@ // [START metastore_v1_generated_DataprocMetastoreFederation_GetFederation_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Metastore\V1\DataprocMetastoreFederationClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreFederationClient; use Google\Cloud\Metastore\V1\Federation; +use Google\Cloud\Metastore\V1\GetFederationRequest; /** * Gets the details of a single federation. @@ -41,10 +42,14 @@ function get_federation_sample(string $formattedName): void // Create a client. $dataprocMetastoreFederationClient = new DataprocMetastoreFederationClient(); + // Prepare the request message. + $request = (new GetFederationRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var Federation $response */ - $response = $dataprocMetastoreFederationClient->getFederation($formattedName); + $response = $dataprocMetastoreFederationClient->getFederation($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/get_iam_policy.php b/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/get_iam_policy.php index 5d10e219ba13..f0d1d9f042cf 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/get_iam_policy.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/get_iam_policy.php @@ -24,8 +24,9 @@ // [START metastore_v1_generated_DataprocMetastoreFederation_GetIamPolicy_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Iam\V1\GetIamPolicyRequest; use Google\Cloud\Iam\V1\Policy; -use Google\Cloud\Metastore\V1\DataprocMetastoreFederationClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreFederationClient; /** * Gets the access control policy for a resource. Returns an empty policy @@ -39,10 +40,14 @@ function get_iam_policy_sample(string $resource): void // Create a client. $dataprocMetastoreFederationClient = new DataprocMetastoreFederationClient(); + // Prepare the request message. + $request = (new GetIamPolicyRequest()) + ->setResource($resource); + // Call the API and handle any network failures. try { /** @var Policy $response */ - $response = $dataprocMetastoreFederationClient->getIamPolicy($resource); + $response = $dataprocMetastoreFederationClient->getIamPolicy($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/get_location.php b/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/get_location.php index d2da284303ff..a1af3288dcca 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/get_location.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/get_location.php @@ -24,8 +24,9 @@ // [START metastore_v1_generated_DataprocMetastoreFederation_GetLocation_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Location\GetLocationRequest; use Google\Cloud\Location\Location; -use Google\Cloud\Metastore\V1\DataprocMetastoreFederationClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreFederationClient; /** * Gets information about a location. @@ -41,10 +42,13 @@ function get_location_sample(): void // Create a client. $dataprocMetastoreFederationClient = new DataprocMetastoreFederationClient(); + // Prepare the request message. + $request = new GetLocationRequest(); + // Call the API and handle any network failures. try { /** @var Location $response */ - $response = $dataprocMetastoreFederationClient->getLocation(); + $response = $dataprocMetastoreFederationClient->getLocation($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/list_federations.php b/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/list_federations.php index f5384b4ca057..9e4f101498ff 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/list_federations.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/list_federations.php @@ -25,8 +25,9 @@ // [START metastore_v1_generated_DataprocMetastoreFederation_ListFederations_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\Metastore\V1\DataprocMetastoreFederationClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreFederationClient; use Google\Cloud\Metastore\V1\Federation; +use Google\Cloud\Metastore\V1\ListFederationsRequest; /** * Lists federations in a project and location. @@ -41,10 +42,14 @@ function list_federations_sample(string $formattedParent): void // Create a client. $dataprocMetastoreFederationClient = new DataprocMetastoreFederationClient(); + // Prepare the request message. + $request = (new ListFederationsRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $dataprocMetastoreFederationClient->listFederations($formattedParent); + $response = $dataprocMetastoreFederationClient->listFederations($request); /** @var Federation $element */ foreach ($response as $element) { diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/list_locations.php b/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/list_locations.php index 93c29368f420..b712c9799315 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/list_locations.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/list_locations.php @@ -25,8 +25,9 @@ // [START metastore_v1_generated_DataprocMetastoreFederation_ListLocations_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; +use Google\Cloud\Location\ListLocationsRequest; use Google\Cloud\Location\Location; -use Google\Cloud\Metastore\V1\DataprocMetastoreFederationClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreFederationClient; /** * Lists information about the supported locations for this service. @@ -42,10 +43,13 @@ function list_locations_sample(): void // Create a client. $dataprocMetastoreFederationClient = new DataprocMetastoreFederationClient(); + // Prepare the request message. + $request = new ListLocationsRequest(); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $dataprocMetastoreFederationClient->listLocations(); + $response = $dataprocMetastoreFederationClient->listLocations($request); /** @var Location $element */ foreach ($response as $element) { diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/set_iam_policy.php b/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/set_iam_policy.php index 4474217ac388..3704dbdc607b 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/set_iam_policy.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/set_iam_policy.php @@ -25,7 +25,8 @@ // [START metastore_v1_generated_DataprocMetastoreFederation_SetIamPolicy_sync] use Google\ApiCore\ApiException; use Google\Cloud\Iam\V1\Policy; -use Google\Cloud\Metastore\V1\DataprocMetastoreFederationClient; +use Google\Cloud\Iam\V1\SetIamPolicyRequest; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreFederationClient; /** * Sets the access control policy on the specified resource. Replaces @@ -42,13 +43,16 @@ function set_iam_policy_sample(string $resource): void // Create a client. $dataprocMetastoreFederationClient = new DataprocMetastoreFederationClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $policy = new Policy(); + $request = (new SetIamPolicyRequest()) + ->setResource($resource) + ->setPolicy($policy); // Call the API and handle any network failures. try { /** @var Policy $response */ - $response = $dataprocMetastoreFederationClient->setIamPolicy($resource, $policy); + $response = $dataprocMetastoreFederationClient->setIamPolicy($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/test_iam_permissions.php b/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/test_iam_permissions.php index c818b6577b7b..4e202f857ca6 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/test_iam_permissions.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/test_iam_permissions.php @@ -24,8 +24,9 @@ // [START metastore_v1_generated_DataprocMetastoreFederation_TestIamPermissions_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Iam\V1\TestIamPermissionsRequest; use Google\Cloud\Iam\V1\TestIamPermissionsResponse; -use Google\Cloud\Metastore\V1\DataprocMetastoreFederationClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreFederationClient; /** * Returns permissions that a caller has on the specified resource. If the @@ -48,13 +49,16 @@ function test_iam_permissions_sample(string $resource, string $permissionsElemen // Create a client. $dataprocMetastoreFederationClient = new DataprocMetastoreFederationClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $permissions = [$permissionsElement,]; + $request = (new TestIamPermissionsRequest()) + ->setResource($resource) + ->setPermissions($permissions); // Call the API and handle any network failures. try { /** @var TestIamPermissionsResponse $response */ - $response = $dataprocMetastoreFederationClient->testIamPermissions($resource, $permissions); + $response = $dataprocMetastoreFederationClient->testIamPermissions($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/update_federation.php b/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/update_federation.php index 624c1fb4ee5c..bbd80ab634b6 100644 --- a/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/update_federation.php +++ b/DataprocMetastore/samples/V1/DataprocMetastoreFederationClient/update_federation.php @@ -25,8 +25,9 @@ // [START metastore_v1_generated_DataprocMetastoreFederation_UpdateFederation_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Metastore\V1\DataprocMetastoreFederationClient; +use Google\Cloud\Metastore\V1\Client\DataprocMetastoreFederationClient; use Google\Cloud\Metastore\V1\Federation; +use Google\Cloud\Metastore\V1\UpdateFederationRequest; use Google\Protobuf\FieldMask; use Google\Rpc\Status; @@ -44,14 +45,17 @@ function update_federation_sample(): void // Create a client. $dataprocMetastoreFederationClient = new DataprocMetastoreFederationClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $updateMask = new FieldMask(); $federation = new Federation(); + $request = (new UpdateFederationRequest()) + ->setUpdateMask($updateMask) + ->setFederation($federation); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $dataprocMetastoreFederationClient->updateFederation($updateMask, $federation); + $response = $dataprocMetastoreFederationClient->updateFederation($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/DataprocMetastore/src/V1/Client/BaseClient/DataprocMetastoreBaseClient.php b/DataprocMetastore/src/V1/Client/BaseClient/DataprocMetastoreBaseClient.php new file mode 100644 index 000000000000..ab3258fefdbd --- /dev/null +++ b/DataprocMetastore/src/V1/Client/BaseClient/DataprocMetastoreBaseClient.php @@ -0,0 +1,899 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/dataproc_metastore_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/dataproc_metastore_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/dataproc_metastore_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/dataproc_metastore_rest_client_config.php', + ], + ], + ]; + } + + /** + * Return an OperationsClient object with the same endpoint as $this. + * + * @return OperationsClient + */ + public function getOperationsClient() + { + return $this->operationsClient; + } + + /** + * Resume an existing long running operation that was previously started by a long + * running API method. If $methodName is not provided, or does not match a long + * running API method, then the operation can still be resumed, but the + * OperationResponse object will not deserialize the final response. + * + * @param string $operationName The name of the long running operation + * @param string $methodName The name of the method used to start the operation + * + * @return OperationResponse + */ + public function resumeOperation($operationName, $methodName = null) + { + $options = isset($this->descriptors[$methodName]['longRunning']) ? $this->descriptors[$methodName]['longRunning'] : []; + $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); + $operation->reload(); + return $operation; + } + + /** + * Formats a string containing the fully-qualified path to represent a backup + * resource. + * + * @param string $project + * @param string $location + * @param string $service + * @param string $backup + * + * @return string The formatted backup resource. + */ + public static function backupName(string $project, string $location, string $service, string $backup): string + { + return self::getPathTemplate('backup')->render([ + 'project' => $project, + 'location' => $location, + 'service' => $service, + 'backup' => $backup, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a location + * resource. + * + * @param string $project + * @param string $location + * + * @return string The formatted location resource. + */ + public static function locationName(string $project, string $location): string + { + return self::getPathTemplate('location')->render([ + 'project' => $project, + 'location' => $location, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * metadata_import resource. + * + * @param string $project + * @param string $location + * @param string $service + * @param string $metadataImport + * + * @return string The formatted metadata_import resource. + */ + public static function metadataImportName(string $project, string $location, string $service, string $metadataImport): string + { + return self::getPathTemplate('metadataImport')->render([ + 'project' => $project, + 'location' => $location, + 'service' => $service, + 'metadata_import' => $metadataImport, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a network + * resource. + * + * @param string $project + * @param string $network + * + * @return string The formatted network resource. + */ + public static function networkName(string $project, string $network): string + { + return self::getPathTemplate('network')->render([ + 'project' => $project, + 'network' => $network, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a service + * resource. + * + * @param string $project + * @param string $location + * @param string $service + * + * @return string The formatted service resource. + */ + public static function serviceName(string $project, string $location, string $service): string + { + return self::getPathTemplate('service')->render([ + 'project' => $project, + 'location' => $location, + 'service' => $service, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a subnetwork + * resource. + * + * @param string $project + * @param string $region + * @param string $subnetwork + * + * @return string The formatted subnetwork resource. + */ + public static function subnetworkName(string $project, string $region, string $subnetwork): string + { + return self::getPathTemplate('subnetwork')->render([ + 'project' => $project, + 'region' => $region, + 'subnetwork' => $subnetwork, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - backup: projects/{project}/locations/{location}/services/{service}/backups/{backup} + * - location: projects/{project}/locations/{location} + * - metadataImport: projects/{project}/locations/{location}/services/{service}/metadataImports/{metadata_import} + * - network: projects/{project}/global/networks/{network} + * - service: projects/{project}/locations/{location}/services/{service} + * - subnetwork: projects/{project}/regions/{region}/subnetworks/{subnetwork} + * + * The optional $template argument can be supplied to specify a particular pattern, + * and must match one of the templates listed above. If no $template argument is + * provided, or if the $template argument does not match one of the templates + * listed, then parseName will check each of the supported templates, and return + * the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + */ + public static function parseName(string $formattedName, string $template = null): array + { + return self::parseFormattedName($formattedName, $template); + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'metastore.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + $this->operationsClient = $this->createOperationsClient($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Creates a new backup in a given project and location. + * + * The async variant is {@see self::createBackupAsync()} . + * + * @param CreateBackupRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createBackup(CreateBackupRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreateBackup', $request, $callOptions)->wait(); + } + + /** + * Creates a new MetadataImport in a given project and location. + * + * The async variant is {@see self::createMetadataImportAsync()} . + * + * @param CreateMetadataImportRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createMetadataImport(CreateMetadataImportRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreateMetadataImport', $request, $callOptions)->wait(); + } + + /** + * Creates a metastore service in a project and location. + * + * The async variant is {@see self::createServiceAsync()} . + * + * @param CreateServiceRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createService(CreateServiceRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreateService', $request, $callOptions)->wait(); + } + + /** + * Deletes a single backup. + * + * The async variant is {@see self::deleteBackupAsync()} . + * + * @param DeleteBackupRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteBackup(DeleteBackupRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('DeleteBackup', $request, $callOptions)->wait(); + } + + /** + * Deletes a single service. + * + * The async variant is {@see self::deleteServiceAsync()} . + * + * @param DeleteServiceRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteService(DeleteServiceRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('DeleteService', $request, $callOptions)->wait(); + } + + /** + * Exports metadata from a service. + * + * The async variant is {@see self::exportMetadataAsync()} . + * + * @param ExportMetadataRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function exportMetadata(ExportMetadataRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('ExportMetadata', $request, $callOptions)->wait(); + } + + /** + * Gets details of a single backup. + * + * The async variant is {@see self::getBackupAsync()} . + * + * @param GetBackupRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Backup + * + * @throws ApiException Thrown if the API call fails. + */ + public function getBackup(GetBackupRequest $request, array $callOptions = []): Backup + { + return $this->startApiCall('GetBackup', $request, $callOptions)->wait(); + } + + /** + * Gets details of a single import. + * + * The async variant is {@see self::getMetadataImportAsync()} . + * + * @param GetMetadataImportRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return MetadataImport + * + * @throws ApiException Thrown if the API call fails. + */ + public function getMetadataImport(GetMetadataImportRequest $request, array $callOptions = []): MetadataImport + { + return $this->startApiCall('GetMetadataImport', $request, $callOptions)->wait(); + } + + /** + * Gets the details of a single service. + * + * The async variant is {@see self::getServiceAsync()} . + * + * @param GetServiceRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Service + * + * @throws ApiException Thrown if the API call fails. + */ + public function getService(GetServiceRequest $request, array $callOptions = []): Service + { + return $this->startApiCall('GetService', $request, $callOptions)->wait(); + } + + /** + * Lists backups in a service. + * + * The async variant is {@see self::listBackupsAsync()} . + * + * @param ListBackupsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listBackups(ListBackupsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListBackups', $request, $callOptions); + } + + /** + * Lists imports in a service. + * + * The async variant is {@see self::listMetadataImportsAsync()} . + * + * @param ListMetadataImportsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listMetadataImports(ListMetadataImportsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListMetadataImports', $request, $callOptions); + } + + /** + * Lists services in a project and location. + * + * The async variant is {@see self::listServicesAsync()} . + * + * @param ListServicesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listServices(ListServicesRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListServices', $request, $callOptions); + } + + /** + * Restores a service from a backup. + * + * The async variant is {@see self::restoreServiceAsync()} . + * + * @param RestoreServiceRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function restoreService(RestoreServiceRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('RestoreService', $request, $callOptions)->wait(); + } + + /** + * Updates a single import. + * Only the description field of MetadataImport is supported to be updated. + * + * The async variant is {@see self::updateMetadataImportAsync()} . + * + * @param UpdateMetadataImportRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function updateMetadataImport(UpdateMetadataImportRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('UpdateMetadataImport', $request, $callOptions)->wait(); + } + + /** + * Updates the parameters of a single service. + * + * The async variant is {@see self::updateServiceAsync()} . + * + * @param UpdateServiceRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function updateService(UpdateServiceRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('UpdateService', $request, $callOptions)->wait(); + } + + /** + * Gets information about a location. + * + * The async variant is {@see self::getLocationAsync()} . + * + * @param GetLocationRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Location + * + * @throws ApiException Thrown if the API call fails. + */ + public function getLocation(GetLocationRequest $request, array $callOptions = []): Location + { + return $this->startApiCall('GetLocation', $request, $callOptions)->wait(); + } + + /** + * Lists information about the supported locations for this service. + * + * The async variant is {@see self::listLocationsAsync()} . + * + * @param ListLocationsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listLocations(ListLocationsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListLocations', $request, $callOptions); + } + + /** + * Gets the access control policy for a resource. Returns an empty policy + if the resource exists and does not have a policy set. + * + * The async variant is {@see self::getIamPolicyAsync()} . + * + * @param GetIamPolicyRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Policy + * + * @throws ApiException Thrown if the API call fails. + */ + public function getIamPolicy(GetIamPolicyRequest $request, array $callOptions = []): Policy + { + return $this->startApiCall('GetIamPolicy', $request, $callOptions)->wait(); + } + + /** + * Sets the access control policy on the specified resource. Replaces + any existing policy. + + Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` + errors. + * + * The async variant is {@see self::setIamPolicyAsync()} . + * + * @param SetIamPolicyRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Policy + * + * @throws ApiException Thrown if the API call fails. + */ + public function setIamPolicy(SetIamPolicyRequest $request, array $callOptions = []): Policy + { + return $this->startApiCall('SetIamPolicy', $request, $callOptions)->wait(); + } + + /** + * Returns permissions that a caller has on the specified resource. If the + resource does not exist, this will return an empty set of + permissions, not a `NOT_FOUND` error. + + Note: This operation is designed to be used for building + permission-aware UIs and command-line tools, not for authorization + checking. This operation may "fail open" without warning. + * + * The async variant is {@see self::testIamPermissionsAsync()} . + * + * @param TestIamPermissionsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return TestIamPermissionsResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function testIamPermissions(TestIamPermissionsRequest $request, array $callOptions = []): TestIamPermissionsResponse + { + return $this->startApiCall('TestIamPermissions', $request, $callOptions)->wait(); + } +} diff --git a/DataprocMetastore/src/V1/Client/BaseClient/DataprocMetastoreFederationBaseClient.php b/DataprocMetastore/src/V1/Client/BaseClient/DataprocMetastoreFederationBaseClient.php new file mode 100644 index 000000000000..36ababa04e23 --- /dev/null +++ b/DataprocMetastore/src/V1/Client/BaseClient/DataprocMetastoreFederationBaseClient.php @@ -0,0 +1,550 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/dataproc_metastore_federation_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/dataproc_metastore_federation_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/dataproc_metastore_federation_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/dataproc_metastore_federation_rest_client_config.php', + ], + ], + ]; + } + + /** + * Return an OperationsClient object with the same endpoint as $this. + * + * @return OperationsClient + */ + public function getOperationsClient() + { + return $this->operationsClient; + } + + /** + * Resume an existing long running operation that was previously started by a long + * running API method. If $methodName is not provided, or does not match a long + * running API method, then the operation can still be resumed, but the + * OperationResponse object will not deserialize the final response. + * + * @param string $operationName The name of the long running operation + * @param string $methodName The name of the method used to start the operation + * + * @return OperationResponse + */ + public function resumeOperation($operationName, $methodName = null) + { + $options = isset($this->descriptors[$methodName]['longRunning']) ? $this->descriptors[$methodName]['longRunning'] : []; + $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); + $operation->reload(); + return $operation; + } + + /** + * Formats a string containing the fully-qualified path to represent a federation + * resource. + * + * @param string $project + * @param string $location + * @param string $federation + * + * @return string The formatted federation resource. + */ + public static function federationName(string $project, string $location, string $federation): string + { + return self::getPathTemplate('federation')->render([ + 'project' => $project, + 'location' => $location, + 'federation' => $federation, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a location + * resource. + * + * @param string $project + * @param string $location + * + * @return string The formatted location resource. + */ + public static function locationName(string $project, string $location): string + { + return self::getPathTemplate('location')->render([ + 'project' => $project, + 'location' => $location, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - federation: projects/{project}/locations/{location}/federations/{federation} + * - location: projects/{project}/locations/{location} + * + * The optional $template argument can be supplied to specify a particular pattern, + * and must match one of the templates listed above. If no $template argument is + * provided, or if the $template argument does not match one of the templates + * listed, then parseName will check each of the supported templates, and return + * the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + */ + public static function parseName(string $formattedName, string $template = null): array + { + return self::parseFormattedName($formattedName, $template); + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'metastore.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + $this->operationsClient = $this->createOperationsClient($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Creates a metastore federation in a project and location. + * + * The async variant is {@see self::createFederationAsync()} . + * + * @param CreateFederationRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createFederation(CreateFederationRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreateFederation', $request, $callOptions)->wait(); + } + + /** + * Deletes a single federation. + * + * The async variant is {@see self::deleteFederationAsync()} . + * + * @param DeleteFederationRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteFederation(DeleteFederationRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('DeleteFederation', $request, $callOptions)->wait(); + } + + /** + * Gets the details of a single federation. + * + * The async variant is {@see self::getFederationAsync()} . + * + * @param GetFederationRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Federation + * + * @throws ApiException Thrown if the API call fails. + */ + public function getFederation(GetFederationRequest $request, array $callOptions = []): Federation + { + return $this->startApiCall('GetFederation', $request, $callOptions)->wait(); + } + + /** + * Lists federations in a project and location. + * + * The async variant is {@see self::listFederationsAsync()} . + * + * @param ListFederationsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listFederations(ListFederationsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListFederations', $request, $callOptions); + } + + /** + * Updates the fields of a federation. + * + * The async variant is {@see self::updateFederationAsync()} . + * + * @param UpdateFederationRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function updateFederation(UpdateFederationRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('UpdateFederation', $request, $callOptions)->wait(); + } + + /** + * Gets information about a location. + * + * The async variant is {@see self::getLocationAsync()} . + * + * @param GetLocationRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Location + * + * @throws ApiException Thrown if the API call fails. + */ + public function getLocation(GetLocationRequest $request, array $callOptions = []): Location + { + return $this->startApiCall('GetLocation', $request, $callOptions)->wait(); + } + + /** + * Lists information about the supported locations for this service. + * + * The async variant is {@see self::listLocationsAsync()} . + * + * @param ListLocationsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listLocations(ListLocationsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListLocations', $request, $callOptions); + } + + /** + * Gets the access control policy for a resource. Returns an empty policy + if the resource exists and does not have a policy set. + * + * The async variant is {@see self::getIamPolicyAsync()} . + * + * @param GetIamPolicyRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Policy + * + * @throws ApiException Thrown if the API call fails. + */ + public function getIamPolicy(GetIamPolicyRequest $request, array $callOptions = []): Policy + { + return $this->startApiCall('GetIamPolicy', $request, $callOptions)->wait(); + } + + /** + * Sets the access control policy on the specified resource. Replaces + any existing policy. + + Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` + errors. + * + * The async variant is {@see self::setIamPolicyAsync()} . + * + * @param SetIamPolicyRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Policy + * + * @throws ApiException Thrown if the API call fails. + */ + public function setIamPolicy(SetIamPolicyRequest $request, array $callOptions = []): Policy + { + return $this->startApiCall('SetIamPolicy', $request, $callOptions)->wait(); + } + + /** + * Returns permissions that a caller has on the specified resource. If the + resource does not exist, this will return an empty set of + permissions, not a `NOT_FOUND` error. + + Note: This operation is designed to be used for building + permission-aware UIs and command-line tools, not for authorization + checking. This operation may "fail open" without warning. + * + * The async variant is {@see self::testIamPermissionsAsync()} . + * + * @param TestIamPermissionsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return TestIamPermissionsResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function testIamPermissions(TestIamPermissionsRequest $request, array $callOptions = []): TestIamPermissionsResponse + { + return $this->startApiCall('TestIamPermissions', $request, $callOptions)->wait(); + } +} diff --git a/DataprocMetastore/src/V1/Client/DataprocMetastoreClient.php b/DataprocMetastore/src/V1/Client/DataprocMetastoreClient.php new file mode 100644 index 000000000000..6b5a5912c86c --- /dev/null +++ b/DataprocMetastore/src/V1/Client/DataprocMetastoreClient.php @@ -0,0 +1,40 @@ +setParent($parent) + ->setBackup($backup) + ->setBackupId($backupId); + } + /** * Constructor. * diff --git a/DataprocMetastore/src/V1/CreateFederationRequest.php b/DataprocMetastore/src/V1/CreateFederationRequest.php index 696d7128ffad..0d8c855ff915 100644 --- a/DataprocMetastore/src/V1/CreateFederationRequest.php +++ b/DataprocMetastore/src/V1/CreateFederationRequest.php @@ -57,6 +57,34 @@ class CreateFederationRequest extends \Google\Protobuf\Internal\Message */ private $request_id = ''; + /** + * @param string $parent Required. The relative resource name of the location in which to create a + * federation service, in the following form: + * + * `projects/{project_number}/locations/{location_id}`. Please see + * {@see DataprocMetastoreFederationClient::locationName()} for help formatting this field. + * @param \Google\Cloud\Metastore\V1\Federation $federation Required. The Metastore Federation to create. The `name` field is + * ignored. The ID of the created metastore federation must be + * provided in the request's `federation_id` field. + * @param string $federationId Required. The ID of the metastore federation, which is used as the final + * component of the metastore federation's name. + * + * This value must be between 2 and 63 characters long inclusive, begin with a + * letter, end with a letter or number, and consist of alpha-numeric + * ASCII characters or hyphens. + * + * @return \Google\Cloud\Metastore\V1\CreateFederationRequest + * + * @experimental + */ + public static function build(string $parent, \Google\Cloud\Metastore\V1\Federation $federation, string $federationId): self + { + return (new self()) + ->setParent($parent) + ->setFederation($federation) + ->setFederationId($federationId); + } + /** * Constructor. * diff --git a/DataprocMetastore/src/V1/CreateMetadataImportRequest.php b/DataprocMetastore/src/V1/CreateMetadataImportRequest.php index 842d3e73d2e2..0684c436278d 100644 --- a/DataprocMetastore/src/V1/CreateMetadataImportRequest.php +++ b/DataprocMetastore/src/V1/CreateMetadataImportRequest.php @@ -58,6 +58,34 @@ class CreateMetadataImportRequest extends \Google\Protobuf\Internal\Message */ private $request_id = ''; + /** + * @param string $parent Required. The relative resource name of the service in which to create a + * metastore import, in the following form: + * + * `projects/{project_number}/locations/{location_id}/services/{service_id}`. Please see + * {@see DataprocMetastoreClient::serviceName()} for help formatting this field. + * @param \Google\Cloud\Metastore\V1\MetadataImport $metadataImport Required. The metadata import to create. The `name` field is ignored. The + * ID of the created metadata import must be provided in the request's + * `metadata_import_id` field. + * @param string $metadataImportId Required. The ID of the metadata import, which is used as the final + * component of the metadata import's name. + * + * This value must be between 1 and 64 characters long, begin with a letter, + * end with a letter or number, and consist of alpha-numeric ASCII characters + * or hyphens. + * + * @return \Google\Cloud\Metastore\V1\CreateMetadataImportRequest + * + * @experimental + */ + public static function build(string $parent, \Google\Cloud\Metastore\V1\MetadataImport $metadataImport, string $metadataImportId): self + { + return (new self()) + ->setParent($parent) + ->setMetadataImport($metadataImport) + ->setMetadataImportId($metadataImportId); + } + /** * Constructor. * diff --git a/DataprocMetastore/src/V1/CreateServiceRequest.php b/DataprocMetastore/src/V1/CreateServiceRequest.php index c544f379fec3..ad624625ef70 100644 --- a/DataprocMetastore/src/V1/CreateServiceRequest.php +++ b/DataprocMetastore/src/V1/CreateServiceRequest.php @@ -58,6 +58,34 @@ class CreateServiceRequest extends \Google\Protobuf\Internal\Message */ private $request_id = ''; + /** + * @param string $parent Required. The relative resource name of the location in which to create a + * metastore service, in the following form: + * + * `projects/{project_number}/locations/{location_id}`. Please see + * {@see DataprocMetastoreClient::locationName()} for help formatting this field. + * @param \Google\Cloud\Metastore\V1\Service $service Required. The Metastore service to create. The `name` field is + * ignored. The ID of the created metastore service must be provided in + * the request's `service_id` field. + * @param string $serviceId Required. The ID of the metastore service, which is used as the final + * component of the metastore service's name. + * + * This value must be between 2 and 63 characters long inclusive, begin with a + * letter, end with a letter or number, and consist of alpha-numeric + * ASCII characters or hyphens. + * + * @return \Google\Cloud\Metastore\V1\CreateServiceRequest + * + * @experimental + */ + public static function build(string $parent, \Google\Cloud\Metastore\V1\Service $service, string $serviceId): self + { + return (new self()) + ->setParent($parent) + ->setService($service) + ->setServiceId($serviceId); + } + /** * Constructor. * diff --git a/DataprocMetastore/src/V1/DeleteBackupRequest.php b/DataprocMetastore/src/V1/DeleteBackupRequest.php index b15e6720c650..003d2ad64149 100644 --- a/DataprocMetastore/src/V1/DeleteBackupRequest.php +++ b/DataprocMetastore/src/V1/DeleteBackupRequest.php @@ -40,6 +40,23 @@ class DeleteBackupRequest extends \Google\Protobuf\Internal\Message */ private $request_id = ''; + /** + * @param string $name Required. The relative resource name of the backup to delete, in the + * following form: + * + * `projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}`. Please see + * {@see DataprocMetastoreClient::backupName()} for help formatting this field. + * + * @return \Google\Cloud\Metastore\V1\DeleteBackupRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/DataprocMetastore/src/V1/DeleteFederationRequest.php b/DataprocMetastore/src/V1/DeleteFederationRequest.php index 4a09bcf24c77..86c453e4495c 100644 --- a/DataprocMetastore/src/V1/DeleteFederationRequest.php +++ b/DataprocMetastore/src/V1/DeleteFederationRequest.php @@ -39,6 +39,23 @@ class DeleteFederationRequest extends \Google\Protobuf\Internal\Message */ private $request_id = ''; + /** + * @param string $name Required. The relative resource name of the metastore federation to delete, + * in the following form: + * + * `projects/{project_number}/locations/{location_id}/federations/{federation_id}`. Please see + * {@see DataprocMetastoreFederationClient::federationName()} for help formatting this field. + * + * @return \Google\Cloud\Metastore\V1\DeleteFederationRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/DataprocMetastore/src/V1/DeleteServiceRequest.php b/DataprocMetastore/src/V1/DeleteServiceRequest.php index 907e83206380..0c0af0792bac 100644 --- a/DataprocMetastore/src/V1/DeleteServiceRequest.php +++ b/DataprocMetastore/src/V1/DeleteServiceRequest.php @@ -40,6 +40,23 @@ class DeleteServiceRequest extends \Google\Protobuf\Internal\Message */ private $request_id = ''; + /** + * @param string $name Required. The relative resource name of the metastore service to delete, in + * the following form: + * + * `projects/{project_number}/locations/{location_id}/services/{service_id}`. Please see + * {@see DataprocMetastoreClient::serviceName()} for help formatting this field. + * + * @return \Google\Cloud\Metastore\V1\DeleteServiceRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/DataprocMetastore/src/V1/GetBackupRequest.php b/DataprocMetastore/src/V1/GetBackupRequest.php index afc986c9face..e87bf62fd7d7 100644 --- a/DataprocMetastore/src/V1/GetBackupRequest.php +++ b/DataprocMetastore/src/V1/GetBackupRequest.php @@ -25,6 +25,23 @@ class GetBackupRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The relative resource name of the backup to retrieve, in the + * following form: + * + * `projects/{project_number}/locations/{location_id}/services/{service_id}/backups/{backup_id}`. Please see + * {@see DataprocMetastoreClient::backupName()} for help formatting this field. + * + * @return \Google\Cloud\Metastore\V1\GetBackupRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/DataprocMetastore/src/V1/GetFederationRequest.php b/DataprocMetastore/src/V1/GetFederationRequest.php index 56708421bfc1..1dea2ac3c850 100644 --- a/DataprocMetastore/src/V1/GetFederationRequest.php +++ b/DataprocMetastore/src/V1/GetFederationRequest.php @@ -24,6 +24,23 @@ class GetFederationRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The relative resource name of the metastore federation to + * retrieve, in the following form: + * + * `projects/{project_number}/locations/{location_id}/federations/{federation_id}`. Please see + * {@see DataprocMetastoreFederationClient::federationName()} for help formatting this field. + * + * @return \Google\Cloud\Metastore\V1\GetFederationRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/DataprocMetastore/src/V1/GetMetadataImportRequest.php b/DataprocMetastore/src/V1/GetMetadataImportRequest.php index 715bd9f0ea13..846571ef9058 100644 --- a/DataprocMetastore/src/V1/GetMetadataImportRequest.php +++ b/DataprocMetastore/src/V1/GetMetadataImportRequest.php @@ -25,6 +25,23 @@ class GetMetadataImportRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The relative resource name of the metadata import to retrieve, in + * the following form: + * + * `projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports/{import_id}`. Please see + * {@see DataprocMetastoreClient::metadataImportName()} for help formatting this field. + * + * @return \Google\Cloud\Metastore\V1\GetMetadataImportRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/DataprocMetastore/src/V1/GetServiceRequest.php b/DataprocMetastore/src/V1/GetServiceRequest.php index 1cd9efcaa040..a9c900447330 100644 --- a/DataprocMetastore/src/V1/GetServiceRequest.php +++ b/DataprocMetastore/src/V1/GetServiceRequest.php @@ -25,6 +25,23 @@ class GetServiceRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The relative resource name of the metastore service to retrieve, + * in the following form: + * + * `projects/{project_number}/locations/{location_id}/services/{service_id}`. Please see + * {@see DataprocMetastoreClient::serviceName()} for help formatting this field. + * + * @return \Google\Cloud\Metastore\V1\GetServiceRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/DataprocMetastore/src/V1/ListBackupsRequest.php b/DataprocMetastore/src/V1/ListBackupsRequest.php index 248ad1d26602..b372b70a917b 100644 --- a/DataprocMetastore/src/V1/ListBackupsRequest.php +++ b/DataprocMetastore/src/V1/ListBackupsRequest.php @@ -59,6 +59,23 @@ class ListBackupsRequest extends \Google\Protobuf\Internal\Message */ private $order_by = ''; + /** + * @param string $parent Required. The relative resource name of the service whose backups to + * list, in the following form: + * + * `projects/{project_number}/locations/{location_id}/services/{service_id}/backups`. Please see + * {@see DataprocMetastoreClient::serviceName()} for help formatting this field. + * + * @return \Google\Cloud\Metastore\V1\ListBackupsRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/DataprocMetastore/src/V1/ListFederationsRequest.php b/DataprocMetastore/src/V1/ListFederationsRequest.php index 3fd18d10bfeb..8bcb97d635e0 100644 --- a/DataprocMetastore/src/V1/ListFederationsRequest.php +++ b/DataprocMetastore/src/V1/ListFederationsRequest.php @@ -58,6 +58,22 @@ class ListFederationsRequest extends \Google\Protobuf\Internal\Message */ private $order_by = ''; + /** + * @param string $parent Required. The relative resource name of the location of metastore + * federations to list, in the following form: + * `projects/{project_number}/locations/{location_id}`. Please see + * {@see DataprocMetastoreFederationClient::locationName()} for help formatting this field. + * + * @return \Google\Cloud\Metastore\V1\ListFederationsRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/DataprocMetastore/src/V1/ListMetadataImportsRequest.php b/DataprocMetastore/src/V1/ListMetadataImportsRequest.php index f991d085eabd..894d0ba2c557 100644 --- a/DataprocMetastore/src/V1/ListMetadataImportsRequest.php +++ b/DataprocMetastore/src/V1/ListMetadataImportsRequest.php @@ -59,6 +59,23 @@ class ListMetadataImportsRequest extends \Google\Protobuf\Internal\Message */ private $order_by = ''; + /** + * @param string $parent Required. The relative resource name of the service whose metadata imports + * to list, in the following form: + * + * `projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports`. Please see + * {@see DataprocMetastoreClient::serviceName()} for help formatting this field. + * + * @return \Google\Cloud\Metastore\V1\ListMetadataImportsRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/DataprocMetastore/src/V1/ListServicesRequest.php b/DataprocMetastore/src/V1/ListServicesRequest.php index 3122697541c2..163ff6277be1 100644 --- a/DataprocMetastore/src/V1/ListServicesRequest.php +++ b/DataprocMetastore/src/V1/ListServicesRequest.php @@ -60,6 +60,23 @@ class ListServicesRequest extends \Google\Protobuf\Internal\Message */ private $order_by = ''; + /** + * @param string $parent Required. The relative resource name of the location of metastore services + * to list, in the following form: + * + * `projects/{project_number}/locations/{location_id}`. Please see + * {@see DataprocMetastoreClient::locationName()} for help formatting this field. + * + * @return \Google\Cloud\Metastore\V1\ListServicesRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/DataprocMetastore/src/V1/RestoreServiceRequest.php b/DataprocMetastore/src/V1/RestoreServiceRequest.php index 04355d10805f..e659f8a96f64 100644 --- a/DataprocMetastore/src/V1/RestoreServiceRequest.php +++ b/DataprocMetastore/src/V1/RestoreServiceRequest.php @@ -53,6 +53,29 @@ class RestoreServiceRequest extends \Google\Protobuf\Internal\Message */ private $request_id = ''; + /** + * @param string $service Required. The relative resource name of the metastore service to run + * restore, in the following form: + * + * `projects/{project_id}/locations/{location_id}/services/{service_id}`. Please see + * {@see DataprocMetastoreClient::serviceName()} for help formatting this field. + * @param string $backup Required. The relative resource name of the metastore service backup to + * restore from, in the following form: + * + * `projects/{project_id}/locations/{location_id}/services/{service_id}/backups/{backup_id}`. Please see + * {@see DataprocMetastoreClient::backupName()} for help formatting this field. + * + * @return \Google\Cloud\Metastore\V1\RestoreServiceRequest + * + * @experimental + */ + public static function build(string $service, string $backup): self + { + return (new self()) + ->setService($service) + ->setBackup($backup); + } + /** * Constructor. * diff --git a/DataprocMetastore/src/V1/UpdateFederationRequest.php b/DataprocMetastore/src/V1/UpdateFederationRequest.php index 5817717826c2..59dafbd9adf0 100644 --- a/DataprocMetastore/src/V1/UpdateFederationRequest.php +++ b/DataprocMetastore/src/V1/UpdateFederationRequest.php @@ -49,6 +49,28 @@ class UpdateFederationRequest extends \Google\Protobuf\Internal\Message */ private $request_id = ''; + /** + * @param \Google\Cloud\Metastore\V1\Federation $federation Required. The metastore federation to update. The server only merges fields + * in the service if they are specified in `update_mask`. + * + * The metastore federation's `name` field is used to identify the + * metastore service to be updated. + * @param \Google\Protobuf\FieldMask $updateMask Required. A field mask used to specify the fields to be overwritten in the + * metastore federation resource by the update. + * Fields specified in the `update_mask` are relative to the resource (not + * to the full request). A field is overwritten if it is in the mask. + * + * @return \Google\Cloud\Metastore\V1\UpdateFederationRequest + * + * @experimental + */ + public static function build(\Google\Cloud\Metastore\V1\Federation $federation, \Google\Protobuf\FieldMask $updateMask): self + { + return (new self()) + ->setFederation($federation) + ->setUpdateMask($updateMask); + } + /** * Constructor. * diff --git a/DataprocMetastore/src/V1/UpdateMetadataImportRequest.php b/DataprocMetastore/src/V1/UpdateMetadataImportRequest.php index 7845dc3b902c..397fbcf178ca 100644 --- a/DataprocMetastore/src/V1/UpdateMetadataImportRequest.php +++ b/DataprocMetastore/src/V1/UpdateMetadataImportRequest.php @@ -50,6 +50,28 @@ class UpdateMetadataImportRequest extends \Google\Protobuf\Internal\Message */ private $request_id = ''; + /** + * @param \Google\Cloud\Metastore\V1\MetadataImport $metadataImport Required. The metadata import to update. The server only merges fields + * in the import if they are specified in `update_mask`. + * + * The metadata import's `name` field is used to identify the metastore + * import to be updated. + * @param \Google\Protobuf\FieldMask $updateMask Required. A field mask used to specify the fields to be overwritten in the + * metadata import resource by the update. + * Fields specified in the `update_mask` are relative to the resource (not + * to the full request). A field is overwritten if it is in the mask. + * + * @return \Google\Cloud\Metastore\V1\UpdateMetadataImportRequest + * + * @experimental + */ + public static function build(\Google\Cloud\Metastore\V1\MetadataImport $metadataImport, \Google\Protobuf\FieldMask $updateMask): self + { + return (new self()) + ->setMetadataImport($metadataImport) + ->setUpdateMask($updateMask); + } + /** * Constructor. * diff --git a/DataprocMetastore/src/V1/UpdateServiceRequest.php b/DataprocMetastore/src/V1/UpdateServiceRequest.php index d35aaa03fe97..d72f4db8e444 100644 --- a/DataprocMetastore/src/V1/UpdateServiceRequest.php +++ b/DataprocMetastore/src/V1/UpdateServiceRequest.php @@ -50,6 +50,28 @@ class UpdateServiceRequest extends \Google\Protobuf\Internal\Message */ private $request_id = ''; + /** + * @param \Google\Cloud\Metastore\V1\Service $service Required. The metastore service to update. The server only merges fields + * in the service if they are specified in `update_mask`. + * + * The metastore service's `name` field is used to identify the metastore + * service to be updated. + * @param \Google\Protobuf\FieldMask $updateMask Required. A field mask used to specify the fields to be overwritten in the + * metastore service resource by the update. + * Fields specified in the `update_mask` are relative to the resource (not + * to the full request). A field is overwritten if it is in the mask. + * + * @return \Google\Cloud\Metastore\V1\UpdateServiceRequest + * + * @experimental + */ + public static function build(\Google\Cloud\Metastore\V1\Service $service, \Google\Protobuf\FieldMask $updateMask): self + { + return (new self()) + ->setService($service) + ->setUpdateMask($updateMask); + } + /** * Constructor. * diff --git a/DataprocMetastore/src/V1/resources/dataproc_metastore_descriptor_config.php b/DataprocMetastore/src/V1/resources/dataproc_metastore_descriptor_config.php index 0ea310f38b8a..e7782fa07039 100644 --- a/DataprocMetastore/src/V1/resources/dataproc_metastore_descriptor_config.php +++ b/DataprocMetastore/src/V1/resources/dataproc_metastore_descriptor_config.php @@ -12,6 +12,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'CreateMetadataImport' => [ 'longRunning' => [ @@ -22,6 +31,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'CreateService' => [ 'longRunning' => [ @@ -32,6 +50,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'DeleteBackup' => [ 'longRunning' => [ @@ -42,6 +69,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'DeleteService' => [ 'longRunning' => [ @@ -52,6 +88,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'ExportMetadata' => [ 'longRunning' => [ @@ -62,6 +107,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'service', + 'fieldAccessors' => [ + 'getService', + ], + ], + ], ], 'RestoreService' => [ 'longRunning' => [ @@ -72,6 +126,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'service', + 'fieldAccessors' => [ + 'getService', + ], + ], + ], ], 'UpdateMetadataImport' => [ 'longRunning' => [ @@ -82,6 +145,16 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'metadata_import.name', + 'fieldAccessors' => [ + 'getMetadataImport', + 'getName', + ], + ], + ], ], 'UpdateService' => [ 'longRunning' => [ @@ -92,6 +165,52 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'service.name', + 'fieldAccessors' => [ + 'getService', + 'getName', + ], + ], + ], + ], + 'GetBackup' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Metastore\V1\Backup', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetMetadataImport' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Metastore\V1\MetadataImport', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetService' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Metastore\V1\Service', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'ListBackups' => [ 'pageStreaming' => [ @@ -102,6 +221,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getBackups', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Metastore\V1\ListBackupsResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'ListMetadataImports' => [ 'pageStreaming' => [ @@ -112,6 +241,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getMetadataImports', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Metastore\V1\ListMetadataImportsResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'ListServices' => [ 'pageStreaming' => [ @@ -122,8 +261,28 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getServices', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Metastore\V1\ListServicesResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'GetLocation' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Location\Location', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], 'interfaceOverride' => 'google.cloud.location.Locations', ], 'ListLocations' => [ @@ -135,17 +294,65 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getLocations', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Location\ListLocationsResponse', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], 'interfaceOverride' => 'google.cloud.location.Locations', ], 'GetIamPolicy' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Iam\V1\Policy', + 'headerParams' => [ + [ + 'keyName' => 'resource', + 'fieldAccessors' => [ + 'getResource', + ], + ], + ], 'interfaceOverride' => 'google.iam.v1.IAMPolicy', ], 'SetIamPolicy' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Iam\V1\Policy', + 'headerParams' => [ + [ + 'keyName' => 'resource', + 'fieldAccessors' => [ + 'getResource', + ], + ], + ], 'interfaceOverride' => 'google.iam.v1.IAMPolicy', ], 'TestIamPermissions' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Iam\V1\TestIamPermissionsResponse', + 'headerParams' => [ + [ + 'keyName' => 'resource', + 'fieldAccessors' => [ + 'getResource', + ], + ], + ], 'interfaceOverride' => 'google.iam.v1.IAMPolicy', ], + 'templateMap' => [ + 'backup' => 'projects/{project}/locations/{location}/services/{service}/backups/{backup}', + 'location' => 'projects/{project}/locations/{location}', + 'metadataImport' => 'projects/{project}/locations/{location}/services/{service}/metadataImports/{metadata_import}', + 'network' => 'projects/{project}/global/networks/{network}', + 'service' => 'projects/{project}/locations/{location}/services/{service}', + 'subnetwork' => 'projects/{project}/regions/{region}/subnetworks/{subnetwork}', + ], ], ], ]; diff --git a/DataprocMetastore/src/V1/resources/dataproc_metastore_federation_descriptor_config.php b/DataprocMetastore/src/V1/resources/dataproc_metastore_federation_descriptor_config.php index ddc95813d6bf..5ec02fe35edb 100644 --- a/DataprocMetastore/src/V1/resources/dataproc_metastore_federation_descriptor_config.php +++ b/DataprocMetastore/src/V1/resources/dataproc_metastore_federation_descriptor_config.php @@ -12,6 +12,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'DeleteFederation' => [ 'longRunning' => [ @@ -22,6 +31,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'UpdateFederation' => [ 'longRunning' => [ @@ -32,6 +50,28 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'federation.name', + 'fieldAccessors' => [ + 'getFederation', + 'getName', + ], + ], + ], + ], + 'GetFederation' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Metastore\V1\Federation', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'ListFederations' => [ 'pageStreaming' => [ @@ -42,8 +82,28 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getFederations', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Metastore\V1\ListFederationsResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'GetLocation' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Location\Location', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], 'interfaceOverride' => 'google.cloud.location.Locations', ], 'ListLocations' => [ @@ -55,17 +115,61 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getLocations', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Location\ListLocationsResponse', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], 'interfaceOverride' => 'google.cloud.location.Locations', ], 'GetIamPolicy' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Iam\V1\Policy', + 'headerParams' => [ + [ + 'keyName' => 'resource', + 'fieldAccessors' => [ + 'getResource', + ], + ], + ], 'interfaceOverride' => 'google.iam.v1.IAMPolicy', ], 'SetIamPolicy' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Iam\V1\Policy', + 'headerParams' => [ + [ + 'keyName' => 'resource', + 'fieldAccessors' => [ + 'getResource', + ], + ], + ], 'interfaceOverride' => 'google.iam.v1.IAMPolicy', ], 'TestIamPermissions' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Iam\V1\TestIamPermissionsResponse', + 'headerParams' => [ + [ + 'keyName' => 'resource', + 'fieldAccessors' => [ + 'getResource', + ], + ], + ], 'interfaceOverride' => 'google.iam.v1.IAMPolicy', ], + 'templateMap' => [ + 'federation' => 'projects/{project}/locations/{location}/federations/{federation}', + 'location' => 'projects/{project}/locations/{location}', + ], ], ], ]; diff --git a/DataprocMetastore/tests/Unit/V1/Client/DataprocMetastoreClientTest.php b/DataprocMetastore/tests/Unit/V1/Client/DataprocMetastoreClientTest.php new file mode 100644 index 000000000000..dda9f44cd452 --- /dev/null +++ b/DataprocMetastore/tests/Unit/V1/Client/DataprocMetastoreClientTest.php @@ -0,0 +1,2117 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return DataprocMetastoreClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new DataprocMetastoreClient($options); + } + + /** @test */ + public function createBackupTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createBackupTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $description = 'description-1724546052'; + $expectedResponse = new Backup(); + $expectedResponse->setName($name); + $expectedResponse->setDescription($description); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createBackupTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->serviceName('[PROJECT]', '[LOCATION]', '[SERVICE]'); + $backupId = 'backupId1355353272'; + $backup = new Backup(); + $request = (new CreateBackupRequest()) + ->setParent($formattedParent) + ->setBackupId($backupId) + ->setBackup($backup); + $response = $gapicClient->createBackup($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastore/CreateBackup', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getBackupId(); + $this->assertProtobufEquals($backupId, $actualValue); + $actualValue = $actualApiRequestObject->getBackup(); + $this->assertProtobufEquals($backup, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createBackupTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createBackupExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createBackupTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->serviceName('[PROJECT]', '[LOCATION]', '[SERVICE]'); + $backupId = 'backupId1355353272'; + $backup = new Backup(); + $request = (new CreateBackupRequest()) + ->setParent($formattedParent) + ->setBackupId($backupId) + ->setBackup($backup); + $response = $gapicClient->createBackup($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createBackupTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createMetadataImportTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createMetadataImportTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $description = 'description-1724546052'; + $expectedResponse = new MetadataImport(); + $expectedResponse->setName($name); + $expectedResponse->setDescription($description); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createMetadataImportTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->serviceName('[PROJECT]', '[LOCATION]', '[SERVICE]'); + $metadataImportId = 'metadataImportId-476076315'; + $metadataImport = new MetadataImport(); + $request = (new CreateMetadataImportRequest()) + ->setParent($formattedParent) + ->setMetadataImportId($metadataImportId) + ->setMetadataImport($metadataImport); + $response = $gapicClient->createMetadataImport($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastore/CreateMetadataImport', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getMetadataImportId(); + $this->assertProtobufEquals($metadataImportId, $actualValue); + $actualValue = $actualApiRequestObject->getMetadataImport(); + $this->assertProtobufEquals($metadataImport, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createMetadataImportTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createMetadataImportExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createMetadataImportTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->serviceName('[PROJECT]', '[LOCATION]', '[SERVICE]'); + $metadataImportId = 'metadataImportId-476076315'; + $metadataImport = new MetadataImport(); + $request = (new CreateMetadataImportRequest()) + ->setParent($formattedParent) + ->setMetadataImportId($metadataImportId) + ->setMetadataImport($metadataImport); + $response = $gapicClient->createMetadataImport($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createMetadataImportTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createServiceTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createServiceTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $network = 'network1843485230'; + $endpointUri = 'endpointUri-850313278'; + $port = 3446913; + $stateMessage = 'stateMessage29641305'; + $artifactGcsUri = 'artifactGcsUri1337121495'; + $uid = 'uid115792'; + $expectedResponse = new Service(); + $expectedResponse->setName($name); + $expectedResponse->setNetwork($network); + $expectedResponse->setEndpointUri($endpointUri); + $expectedResponse->setPort($port); + $expectedResponse->setStateMessage($stateMessage); + $expectedResponse->setArtifactGcsUri($artifactGcsUri); + $expectedResponse->setUid($uid); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createServiceTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $serviceId = 'serviceId-1724763419'; + $service = new Service(); + $request = (new CreateServiceRequest()) + ->setParent($formattedParent) + ->setServiceId($serviceId) + ->setService($service); + $response = $gapicClient->createService($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastore/CreateService', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getServiceId(); + $this->assertProtobufEquals($serviceId, $actualValue); + $actualValue = $actualApiRequestObject->getService(); + $this->assertProtobufEquals($service, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createServiceTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createServiceExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createServiceTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $serviceId = 'serviceId-1724763419'; + $service = new Service(); + $request = (new CreateServiceRequest()) + ->setParent($formattedParent) + ->setServiceId($serviceId) + ->setService($service); + $response = $gapicClient->createService($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createServiceTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteBackupTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteBackupTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new GPBEmpty(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/deleteBackupTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedName = $gapicClient->backupName('[PROJECT]', '[LOCATION]', '[SERVICE]', '[BACKUP]'); + $request = (new DeleteBackupRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteBackup($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastore/DeleteBackup', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteBackupTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteBackupExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteBackupTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->backupName('[PROJECT]', '[LOCATION]', '[SERVICE]', '[BACKUP]'); + $request = (new DeleteBackupRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteBackup($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteBackupTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteServiceTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteServiceTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new GPBEmpty(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/deleteServiceTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedName = $gapicClient->serviceName('[PROJECT]', '[LOCATION]', '[SERVICE]'); + $request = (new DeleteServiceRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteService($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastore/DeleteService', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteServiceTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteServiceExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteServiceTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->serviceName('[PROJECT]', '[LOCATION]', '[SERVICE]'); + $request = (new DeleteServiceRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteService($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteServiceTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function exportMetadataTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/exportMetadataTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $destinationGcsUri = 'destinationGcsUri1386421523'; + $expectedResponse = new MetadataExport(); + $expectedResponse->setDestinationGcsUri($destinationGcsUri); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/exportMetadataTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedService = $gapicClient->serviceName('[PROJECT]', '[LOCATION]', '[SERVICE]'); + $request = (new ExportMetadataRequest()) + ->setService($formattedService); + $response = $gapicClient->exportMetadata($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastore/ExportMetadata', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getService(); + $this->assertProtobufEquals($formattedService, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/exportMetadataTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function exportMetadataExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/exportMetadataTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedService = $gapicClient->serviceName('[PROJECT]', '[LOCATION]', '[SERVICE]'); + $request = (new ExportMetadataRequest()) + ->setService($formattedService); + $response = $gapicClient->exportMetadata($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/exportMetadataTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function getBackupTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $description = 'description-1724546052'; + $expectedResponse = new Backup(); + $expectedResponse->setName($name2); + $expectedResponse->setDescription($description); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->backupName('[PROJECT]', '[LOCATION]', '[SERVICE]', '[BACKUP]'); + $request = (new GetBackupRequest()) + ->setName($formattedName); + $response = $gapicClient->getBackup($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastore/GetBackup', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getBackupExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->backupName('[PROJECT]', '[LOCATION]', '[SERVICE]', '[BACKUP]'); + $request = (new GetBackupRequest()) + ->setName($formattedName); + try { + $gapicClient->getBackup($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getMetadataImportTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $description = 'description-1724546052'; + $expectedResponse = new MetadataImport(); + $expectedResponse->setName($name2); + $expectedResponse->setDescription($description); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->metadataImportName('[PROJECT]', '[LOCATION]', '[SERVICE]', '[METADATA_IMPORT]'); + $request = (new GetMetadataImportRequest()) + ->setName($formattedName); + $response = $gapicClient->getMetadataImport($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastore/GetMetadataImport', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getMetadataImportExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->metadataImportName('[PROJECT]', '[LOCATION]', '[SERVICE]', '[METADATA_IMPORT]'); + $request = (new GetMetadataImportRequest()) + ->setName($formattedName); + try { + $gapicClient->getMetadataImport($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getServiceTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $network = 'network1843485230'; + $endpointUri = 'endpointUri-850313278'; + $port = 3446913; + $stateMessage = 'stateMessage29641305'; + $artifactGcsUri = 'artifactGcsUri1337121495'; + $uid = 'uid115792'; + $expectedResponse = new Service(); + $expectedResponse->setName($name2); + $expectedResponse->setNetwork($network); + $expectedResponse->setEndpointUri($endpointUri); + $expectedResponse->setPort($port); + $expectedResponse->setStateMessage($stateMessage); + $expectedResponse->setArtifactGcsUri($artifactGcsUri); + $expectedResponse->setUid($uid); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->serviceName('[PROJECT]', '[LOCATION]', '[SERVICE]'); + $request = (new GetServiceRequest()) + ->setName($formattedName); + $response = $gapicClient->getService($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastore/GetService', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getServiceExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->serviceName('[PROJECT]', '[LOCATION]', '[SERVICE]'); + $request = (new GetServiceRequest()) + ->setName($formattedName); + try { + $gapicClient->getService($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listBackupsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $backupsElement = new Backup(); + $backups = [ + $backupsElement, + ]; + $expectedResponse = new ListBackupsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setBackups($backups); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->serviceName('[PROJECT]', '[LOCATION]', '[SERVICE]'); + $request = (new ListBackupsRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listBackups($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getBackups()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastore/ListBackups', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listBackupsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->serviceName('[PROJECT]', '[LOCATION]', '[SERVICE]'); + $request = (new ListBackupsRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listBackups($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listMetadataImportsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $metadataImportsElement = new MetadataImport(); + $metadataImports = [ + $metadataImportsElement, + ]; + $expectedResponse = new ListMetadataImportsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setMetadataImports($metadataImports); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->serviceName('[PROJECT]', '[LOCATION]', '[SERVICE]'); + $request = (new ListMetadataImportsRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listMetadataImports($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getMetadataImports()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastore/ListMetadataImports', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listMetadataImportsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->serviceName('[PROJECT]', '[LOCATION]', '[SERVICE]'); + $request = (new ListMetadataImportsRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listMetadataImports($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listServicesTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $servicesElement = new Service(); + $services = [ + $servicesElement, + ]; + $expectedResponse = new ListServicesResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setServices($services); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListServicesRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listServices($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getServices()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastore/ListServices', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listServicesExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListServicesRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listServices($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function restoreServiceTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/restoreServiceTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $backup2 = 'backup22121930997'; + $details = 'details1557721666'; + $expectedResponse = new Restore(); + $expectedResponse->setBackup($backup2); + $expectedResponse->setDetails($details); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/restoreServiceTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedService = $gapicClient->serviceName('[PROJECT]', '[LOCATION]', '[SERVICE]'); + $formattedBackup = $gapicClient->backupName('[PROJECT]', '[LOCATION]', '[SERVICE]', '[BACKUP]'); + $request = (new RestoreServiceRequest()) + ->setService($formattedService) + ->setBackup($formattedBackup); + $response = $gapicClient->restoreService($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastore/RestoreService', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getService(); + $this->assertProtobufEquals($formattedService, $actualValue); + $actualValue = $actualApiRequestObject->getBackup(); + $this->assertProtobufEquals($formattedBackup, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/restoreServiceTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function restoreServiceExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/restoreServiceTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedService = $gapicClient->serviceName('[PROJECT]', '[LOCATION]', '[SERVICE]'); + $formattedBackup = $gapicClient->backupName('[PROJECT]', '[LOCATION]', '[SERVICE]', '[BACKUP]'); + $request = (new RestoreServiceRequest()) + ->setService($formattedService) + ->setBackup($formattedBackup); + $response = $gapicClient->restoreService($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/restoreServiceTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateMetadataImportTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateMetadataImportTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $description = 'description-1724546052'; + $expectedResponse = new MetadataImport(); + $expectedResponse->setName($name); + $expectedResponse->setDescription($description); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/updateMetadataImportTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $updateMask = new FieldMask(); + $metadataImport = new MetadataImport(); + $request = (new UpdateMetadataImportRequest()) + ->setUpdateMask($updateMask) + ->setMetadataImport($metadataImport); + $response = $gapicClient->updateMetadataImport($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastore/UpdateMetadataImport', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getUpdateMask(); + $this->assertProtobufEquals($updateMask, $actualValue); + $actualValue = $actualApiRequestObject->getMetadataImport(); + $this->assertProtobufEquals($metadataImport, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateMetadataImportTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateMetadataImportExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateMetadataImportTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $updateMask = new FieldMask(); + $metadataImport = new MetadataImport(); + $request = (new UpdateMetadataImportRequest()) + ->setUpdateMask($updateMask) + ->setMetadataImport($metadataImport); + $response = $gapicClient->updateMetadataImport($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateMetadataImportTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateServiceTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateServiceTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $network = 'network1843485230'; + $endpointUri = 'endpointUri-850313278'; + $port = 3446913; + $stateMessage = 'stateMessage29641305'; + $artifactGcsUri = 'artifactGcsUri1337121495'; + $uid = 'uid115792'; + $expectedResponse = new Service(); + $expectedResponse->setName($name); + $expectedResponse->setNetwork($network); + $expectedResponse->setEndpointUri($endpointUri); + $expectedResponse->setPort($port); + $expectedResponse->setStateMessage($stateMessage); + $expectedResponse->setArtifactGcsUri($artifactGcsUri); + $expectedResponse->setUid($uid); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/updateServiceTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $updateMask = new FieldMask(); + $service = new Service(); + $request = (new UpdateServiceRequest()) + ->setUpdateMask($updateMask) + ->setService($service); + $response = $gapicClient->updateService($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastore/UpdateService', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getUpdateMask(); + $this->assertProtobufEquals($updateMask, $actualValue); + $actualValue = $actualApiRequestObject->getService(); + $this->assertProtobufEquals($service, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateServiceTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateServiceExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateServiceTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $updateMask = new FieldMask(); + $service = new Service(); + $request = (new UpdateServiceRequest()) + ->setUpdateMask($updateMask) + ->setService($service); + $response = $gapicClient->updateService($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateServiceTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function getLocationTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $locationId = 'locationId552319461'; + $displayName = 'displayName1615086568'; + $expectedResponse = new Location(); + $expectedResponse->setName($name2); + $expectedResponse->setLocationId($locationId); + $expectedResponse->setDisplayName($displayName); + $transport->addResponse($expectedResponse); + $request = new GetLocationRequest(); + $response = $gapicClient->getLocation($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.location.Locations/GetLocation', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getLocationExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + $request = new GetLocationRequest(); + try { + $gapicClient->getLocation($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listLocationsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $locationsElement = new Location(); + $locations = [ + $locationsElement, + ]; + $expectedResponse = new ListLocationsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setLocations($locations); + $transport->addResponse($expectedResponse); + $request = new ListLocationsRequest(); + $response = $gapicClient->listLocations($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getLocations()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.location.Locations/ListLocations', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listLocationsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + $request = new ListLocationsRequest(); + try { + $gapicClient->listLocations($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getIamPolicyTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $version = 351608024; + $etag = '21'; + $expectedResponse = new Policy(); + $expectedResponse->setVersion($version); + $expectedResponse->setEtag($etag); + $transport->addResponse($expectedResponse); + // Mock request + $resource = 'resource-341064690'; + $request = (new GetIamPolicyRequest()) + ->setResource($resource); + $response = $gapicClient->getIamPolicy($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.iam.v1.IAMPolicy/GetIamPolicy', $actualFuncCall); + $actualValue = $actualRequestObject->getResource(); + $this->assertProtobufEquals($resource, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getIamPolicyExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $resource = 'resource-341064690'; + $request = (new GetIamPolicyRequest()) + ->setResource($resource); + try { + $gapicClient->getIamPolicy($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function setIamPolicyTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $version = 351608024; + $etag = '21'; + $expectedResponse = new Policy(); + $expectedResponse->setVersion($version); + $expectedResponse->setEtag($etag); + $transport->addResponse($expectedResponse); + // Mock request + $resource = 'resource-341064690'; + $policy = new Policy(); + $request = (new SetIamPolicyRequest()) + ->setResource($resource) + ->setPolicy($policy); + $response = $gapicClient->setIamPolicy($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.iam.v1.IAMPolicy/SetIamPolicy', $actualFuncCall); + $actualValue = $actualRequestObject->getResource(); + $this->assertProtobufEquals($resource, $actualValue); + $actualValue = $actualRequestObject->getPolicy(); + $this->assertProtobufEquals($policy, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function setIamPolicyExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $resource = 'resource-341064690'; + $policy = new Policy(); + $request = (new SetIamPolicyRequest()) + ->setResource($resource) + ->setPolicy($policy); + try { + $gapicClient->setIamPolicy($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function testIamPermissionsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new TestIamPermissionsResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $resource = 'resource-341064690'; + $permissions = []; + $request = (new TestIamPermissionsRequest()) + ->setResource($resource) + ->setPermissions($permissions); + $response = $gapicClient->testIamPermissions($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.iam.v1.IAMPolicy/TestIamPermissions', $actualFuncCall); + $actualValue = $actualRequestObject->getResource(); + $this->assertProtobufEquals($resource, $actualValue); + $actualValue = $actualRequestObject->getPermissions(); + $this->assertProtobufEquals($permissions, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function testIamPermissionsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $resource = 'resource-341064690'; + $permissions = []; + $request = (new TestIamPermissionsRequest()) + ->setResource($resource) + ->setPermissions($permissions); + try { + $gapicClient->testIamPermissions($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createBackupAsyncTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createBackupTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $description = 'description-1724546052'; + $expectedResponse = new Backup(); + $expectedResponse->setName($name); + $expectedResponse->setDescription($description); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createBackupTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->serviceName('[PROJECT]', '[LOCATION]', '[SERVICE]'); + $backupId = 'backupId1355353272'; + $backup = new Backup(); + $request = (new CreateBackupRequest()) + ->setParent($formattedParent) + ->setBackupId($backupId) + ->setBackup($backup); + $response = $gapicClient->createBackupAsync($request)->wait(); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastore/CreateBackup', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getBackupId(); + $this->assertProtobufEquals($backupId, $actualValue); + $actualValue = $actualApiRequestObject->getBackup(); + $this->assertProtobufEquals($backup, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createBackupTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } +} diff --git a/DataprocMetastore/tests/Unit/V1/Client/DataprocMetastoreFederationClientTest.php b/DataprocMetastore/tests/Unit/V1/Client/DataprocMetastoreFederationClientTest.php new file mode 100644 index 000000000000..0c81a2c672e1 --- /dev/null +++ b/DataprocMetastore/tests/Unit/V1/Client/DataprocMetastoreFederationClientTest.php @@ -0,0 +1,1039 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return DataprocMetastoreFederationClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new DataprocMetastoreFederationClient($options); + } + + /** @test */ + public function createFederationTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createFederationTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $version = 'version351608024'; + $endpointUri = 'endpointUri-850313278'; + $stateMessage = 'stateMessage29641305'; + $uid = 'uid115792'; + $expectedResponse = new Federation(); + $expectedResponse->setName($name); + $expectedResponse->setVersion($version); + $expectedResponse->setEndpointUri($endpointUri); + $expectedResponse->setStateMessage($stateMessage); + $expectedResponse->setUid($uid); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createFederationTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $federationId = 'federationId-1338699881'; + $federation = new Federation(); + $request = (new CreateFederationRequest()) + ->setParent($formattedParent) + ->setFederationId($federationId) + ->setFederation($federation); + $response = $gapicClient->createFederation($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastoreFederation/CreateFederation', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getFederationId(); + $this->assertProtobufEquals($federationId, $actualValue); + $actualValue = $actualApiRequestObject->getFederation(); + $this->assertProtobufEquals($federation, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createFederationTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createFederationExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createFederationTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $federationId = 'federationId-1338699881'; + $federation = new Federation(); + $request = (new CreateFederationRequest()) + ->setParent($formattedParent) + ->setFederationId($federationId) + ->setFederation($federation); + $response = $gapicClient->createFederation($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createFederationTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteFederationTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteFederationTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new GPBEmpty(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/deleteFederationTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedName = $gapicClient->federationName('[PROJECT]', '[LOCATION]', '[FEDERATION]'); + $request = (new DeleteFederationRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteFederation($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastoreFederation/DeleteFederation', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteFederationTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteFederationExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteFederationTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->federationName('[PROJECT]', '[LOCATION]', '[FEDERATION]'); + $request = (new DeleteFederationRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteFederation($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteFederationTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function getFederationTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $version = 'version351608024'; + $endpointUri = 'endpointUri-850313278'; + $stateMessage = 'stateMessage29641305'; + $uid = 'uid115792'; + $expectedResponse = new Federation(); + $expectedResponse->setName($name2); + $expectedResponse->setVersion($version); + $expectedResponse->setEndpointUri($endpointUri); + $expectedResponse->setStateMessage($stateMessage); + $expectedResponse->setUid($uid); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->federationName('[PROJECT]', '[LOCATION]', '[FEDERATION]'); + $request = (new GetFederationRequest()) + ->setName($formattedName); + $response = $gapicClient->getFederation($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastoreFederation/GetFederation', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getFederationExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->federationName('[PROJECT]', '[LOCATION]', '[FEDERATION]'); + $request = (new GetFederationRequest()) + ->setName($formattedName); + try { + $gapicClient->getFederation($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listFederationsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $federationsElement = new Federation(); + $federations = [ + $federationsElement, + ]; + $expectedResponse = new ListFederationsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setFederations($federations); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListFederationsRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listFederations($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getFederations()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastoreFederation/ListFederations', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listFederationsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListFederationsRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listFederations($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function updateFederationTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateFederationTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $version = 'version351608024'; + $endpointUri = 'endpointUri-850313278'; + $stateMessage = 'stateMessage29641305'; + $uid = 'uid115792'; + $expectedResponse = new Federation(); + $expectedResponse->setName($name); + $expectedResponse->setVersion($version); + $expectedResponse->setEndpointUri($endpointUri); + $expectedResponse->setStateMessage($stateMessage); + $expectedResponse->setUid($uid); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/updateFederationTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $updateMask = new FieldMask(); + $federation = new Federation(); + $request = (new UpdateFederationRequest()) + ->setUpdateMask($updateMask) + ->setFederation($federation); + $response = $gapicClient->updateFederation($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastoreFederation/UpdateFederation', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getUpdateMask(); + $this->assertProtobufEquals($updateMask, $actualValue); + $actualValue = $actualApiRequestObject->getFederation(); + $this->assertProtobufEquals($federation, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateFederationTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateFederationExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateFederationTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $updateMask = new FieldMask(); + $federation = new Federation(); + $request = (new UpdateFederationRequest()) + ->setUpdateMask($updateMask) + ->setFederation($federation); + $response = $gapicClient->updateFederation($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateFederationTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function getLocationTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $locationId = 'locationId552319461'; + $displayName = 'displayName1615086568'; + $expectedResponse = new Location(); + $expectedResponse->setName($name2); + $expectedResponse->setLocationId($locationId); + $expectedResponse->setDisplayName($displayName); + $transport->addResponse($expectedResponse); + $request = new GetLocationRequest(); + $response = $gapicClient->getLocation($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.location.Locations/GetLocation', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getLocationExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + $request = new GetLocationRequest(); + try { + $gapicClient->getLocation($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listLocationsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $locationsElement = new Location(); + $locations = [ + $locationsElement, + ]; + $expectedResponse = new ListLocationsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setLocations($locations); + $transport->addResponse($expectedResponse); + $request = new ListLocationsRequest(); + $response = $gapicClient->listLocations($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getLocations()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.location.Locations/ListLocations', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listLocationsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + $request = new ListLocationsRequest(); + try { + $gapicClient->listLocations($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getIamPolicyTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $version = 351608024; + $etag = '21'; + $expectedResponse = new Policy(); + $expectedResponse->setVersion($version); + $expectedResponse->setEtag($etag); + $transport->addResponse($expectedResponse); + // Mock request + $resource = 'resource-341064690'; + $request = (new GetIamPolicyRequest()) + ->setResource($resource); + $response = $gapicClient->getIamPolicy($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.iam.v1.IAMPolicy/GetIamPolicy', $actualFuncCall); + $actualValue = $actualRequestObject->getResource(); + $this->assertProtobufEquals($resource, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getIamPolicyExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $resource = 'resource-341064690'; + $request = (new GetIamPolicyRequest()) + ->setResource($resource); + try { + $gapicClient->getIamPolicy($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function setIamPolicyTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $version = 351608024; + $etag = '21'; + $expectedResponse = new Policy(); + $expectedResponse->setVersion($version); + $expectedResponse->setEtag($etag); + $transport->addResponse($expectedResponse); + // Mock request + $resource = 'resource-341064690'; + $policy = new Policy(); + $request = (new SetIamPolicyRequest()) + ->setResource($resource) + ->setPolicy($policy); + $response = $gapicClient->setIamPolicy($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.iam.v1.IAMPolicy/SetIamPolicy', $actualFuncCall); + $actualValue = $actualRequestObject->getResource(); + $this->assertProtobufEquals($resource, $actualValue); + $actualValue = $actualRequestObject->getPolicy(); + $this->assertProtobufEquals($policy, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function setIamPolicyExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $resource = 'resource-341064690'; + $policy = new Policy(); + $request = (new SetIamPolicyRequest()) + ->setResource($resource) + ->setPolicy($policy); + try { + $gapicClient->setIamPolicy($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function testIamPermissionsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new TestIamPermissionsResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $resource = 'resource-341064690'; + $permissions = []; + $request = (new TestIamPermissionsRequest()) + ->setResource($resource) + ->setPermissions($permissions); + $response = $gapicClient->testIamPermissions($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.iam.v1.IAMPolicy/TestIamPermissions', $actualFuncCall); + $actualValue = $actualRequestObject->getResource(); + $this->assertProtobufEquals($resource, $actualValue); + $actualValue = $actualRequestObject->getPermissions(); + $this->assertProtobufEquals($permissions, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function testIamPermissionsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $resource = 'resource-341064690'; + $permissions = []; + $request = (new TestIamPermissionsRequest()) + ->setResource($resource) + ->setPermissions($permissions); + try { + $gapicClient->testIamPermissions($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createFederationAsyncTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createFederationTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $version = 'version351608024'; + $endpointUri = 'endpointUri-850313278'; + $stateMessage = 'stateMessage29641305'; + $uid = 'uid115792'; + $expectedResponse = new Federation(); + $expectedResponse->setName($name); + $expectedResponse->setVersion($version); + $expectedResponse->setEndpointUri($endpointUri); + $expectedResponse->setStateMessage($stateMessage); + $expectedResponse->setUid($uid); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createFederationTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $federationId = 'federationId-1338699881'; + $federation = new Federation(); + $request = (new CreateFederationRequest()) + ->setParent($formattedParent) + ->setFederationId($federationId) + ->setFederation($federation); + $response = $gapicClient->createFederationAsync($request)->wait(); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.metastore.v1.DataprocMetastoreFederation/CreateFederation', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getFederationId(); + $this->assertProtobufEquals($federationId, $actualValue); + $actualValue = $actualApiRequestObject->getFederation(); + $this->assertProtobufEquals($federation, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createFederationTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } +} diff --git a/DatastoreAdmin/samples/V1/DatastoreAdminClient/create_index.php b/DatastoreAdmin/samples/V1/DatastoreAdminClient/create_index.php index cb22ef478782..5ec7eaa03138 100644 --- a/DatastoreAdmin/samples/V1/DatastoreAdminClient/create_index.php +++ b/DatastoreAdmin/samples/V1/DatastoreAdminClient/create_index.php @@ -25,7 +25,8 @@ // [START datastore_v1_generated_DatastoreAdmin_CreateIndex_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Datastore\Admin\V1\DatastoreAdminClient; +use Google\Cloud\Datastore\Admin\V1\Client\DatastoreAdminClient; +use Google\Cloud\Datastore\Admin\V1\CreateIndexRequest; use Google\Cloud\Datastore\Admin\V1\Index; use Google\Rpc\Status; @@ -56,10 +57,13 @@ function create_index_sample(): void // Create a client. $datastoreAdminClient = new DatastoreAdminClient(); + // Prepare the request message. + $request = new CreateIndexRequest(); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $datastoreAdminClient->createIndex(); + $response = $datastoreAdminClient->createIndex($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/DatastoreAdmin/samples/V1/DatastoreAdminClient/delete_index.php b/DatastoreAdmin/samples/V1/DatastoreAdminClient/delete_index.php index f7e315a31ab3..27575e752c6c 100644 --- a/DatastoreAdmin/samples/V1/DatastoreAdminClient/delete_index.php +++ b/DatastoreAdmin/samples/V1/DatastoreAdminClient/delete_index.php @@ -25,7 +25,8 @@ // [START datastore_v1_generated_DatastoreAdmin_DeleteIndex_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Datastore\Admin\V1\DatastoreAdminClient; +use Google\Cloud\Datastore\Admin\V1\Client\DatastoreAdminClient; +use Google\Cloud\Datastore\Admin\V1\DeleteIndexRequest; use Google\Cloud\Datastore\Admin\V1\Index; use Google\Rpc\Status; @@ -52,10 +53,13 @@ function delete_index_sample(): void // Create a client. $datastoreAdminClient = new DatastoreAdminClient(); + // Prepare the request message. + $request = new DeleteIndexRequest(); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $datastoreAdminClient->deleteIndex(); + $response = $datastoreAdminClient->deleteIndex($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/DatastoreAdmin/samples/V1/DatastoreAdminClient/export_entities.php b/DatastoreAdmin/samples/V1/DatastoreAdminClient/export_entities.php index 8c2ded6389c9..ba7f2efa4c40 100644 --- a/DatastoreAdmin/samples/V1/DatastoreAdminClient/export_entities.php +++ b/DatastoreAdmin/samples/V1/DatastoreAdminClient/export_entities.php @@ -25,7 +25,8 @@ // [START datastore_v1_generated_DatastoreAdmin_ExportEntities_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Datastore\Admin\V1\DatastoreAdminClient; +use Google\Cloud\Datastore\Admin\V1\Client\DatastoreAdminClient; +use Google\Cloud\Datastore\Admin\V1\ExportEntitiesRequest; use Google\Cloud\Datastore\Admin\V1\ExportEntitiesResponse; use Google\Rpc\Status; @@ -64,10 +65,15 @@ function export_entities_sample(string $projectId, string $outputUrlPrefix): voi // Create a client. $datastoreAdminClient = new DatastoreAdminClient(); + // Prepare the request message. + $request = (new ExportEntitiesRequest()) + ->setProjectId($projectId) + ->setOutputUrlPrefix($outputUrlPrefix); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $datastoreAdminClient->exportEntities($projectId, $outputUrlPrefix); + $response = $datastoreAdminClient->exportEntities($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/DatastoreAdmin/samples/V1/DatastoreAdminClient/get_index.php b/DatastoreAdmin/samples/V1/DatastoreAdminClient/get_index.php index 630af1c43fe2..77a88606ce58 100644 --- a/DatastoreAdmin/samples/V1/DatastoreAdminClient/get_index.php +++ b/DatastoreAdmin/samples/V1/DatastoreAdminClient/get_index.php @@ -24,7 +24,8 @@ // [START datastore_v1_generated_DatastoreAdmin_GetIndex_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Datastore\Admin\V1\DatastoreAdminClient; +use Google\Cloud\Datastore\Admin\V1\Client\DatastoreAdminClient; +use Google\Cloud\Datastore\Admin\V1\GetIndexRequest; use Google\Cloud\Datastore\Admin\V1\Index; /** @@ -41,10 +42,13 @@ function get_index_sample(): void // Create a client. $datastoreAdminClient = new DatastoreAdminClient(); + // Prepare the request message. + $request = new GetIndexRequest(); + // Call the API and handle any network failures. try { /** @var Index $response */ - $response = $datastoreAdminClient->getIndex(); + $response = $datastoreAdminClient->getIndex($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/DatastoreAdmin/samples/V1/DatastoreAdminClient/import_entities.php b/DatastoreAdmin/samples/V1/DatastoreAdminClient/import_entities.php index 2b7d330f4738..7772be8baa18 100644 --- a/DatastoreAdmin/samples/V1/DatastoreAdminClient/import_entities.php +++ b/DatastoreAdmin/samples/V1/DatastoreAdminClient/import_entities.php @@ -25,7 +25,8 @@ // [START datastore_v1_generated_DatastoreAdmin_ImportEntities_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Datastore\Admin\V1\DatastoreAdminClient; +use Google\Cloud\Datastore\Admin\V1\Client\DatastoreAdminClient; +use Google\Cloud\Datastore\Admin\V1\ImportEntitiesRequest; use Google\Rpc\Status; /** @@ -55,10 +56,15 @@ function import_entities_sample(string $projectId, string $inputUrl): void // Create a client. $datastoreAdminClient = new DatastoreAdminClient(); + // Prepare the request message. + $request = (new ImportEntitiesRequest()) + ->setProjectId($projectId) + ->setInputUrl($inputUrl); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $datastoreAdminClient->importEntities($projectId, $inputUrl); + $response = $datastoreAdminClient->importEntities($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/DatastoreAdmin/samples/V1/DatastoreAdminClient/list_indexes.php b/DatastoreAdmin/samples/V1/DatastoreAdminClient/list_indexes.php index bd3724490493..49cd7af47c33 100644 --- a/DatastoreAdmin/samples/V1/DatastoreAdminClient/list_indexes.php +++ b/DatastoreAdmin/samples/V1/DatastoreAdminClient/list_indexes.php @@ -25,8 +25,9 @@ // [START datastore_v1_generated_DatastoreAdmin_ListIndexes_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\Datastore\Admin\V1\DatastoreAdminClient; +use Google\Cloud\Datastore\Admin\V1\Client\DatastoreAdminClient; use Google\Cloud\Datastore\Admin\V1\Index; +use Google\Cloud\Datastore\Admin\V1\ListIndexesRequest; /** * Lists the indexes that match the specified filters. Datastore uses an @@ -44,10 +45,13 @@ function list_indexes_sample(): void // Create a client. $datastoreAdminClient = new DatastoreAdminClient(); + // Prepare the request message. + $request = new ListIndexesRequest(); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $datastoreAdminClient->listIndexes(); + $response = $datastoreAdminClient->listIndexes($request); /** @var Index $element */ foreach ($response as $element) { diff --git a/DatastoreAdmin/src/V1/Client/BaseClient/DatastoreAdminBaseClient.php b/DatastoreAdmin/src/V1/Client/BaseClient/DatastoreAdminBaseClient.php new file mode 100644 index 000000000000..f3b056ae840a --- /dev/null +++ b/DatastoreAdmin/src/V1/Client/BaseClient/DatastoreAdminBaseClient.php @@ -0,0 +1,448 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/datastore_admin_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/datastore_admin_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/datastore_admin_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/datastore_admin_rest_client_config.php', + ], + ], + ]; + } + + /** + * Return an OperationsClient object with the same endpoint as $this. + * + * @return OperationsClient + */ + public function getOperationsClient() + { + return $this->operationsClient; + } + + /** + * Resume an existing long running operation that was previously started by a long + * running API method. If $methodName is not provided, or does not match a long + * running API method, then the operation can still be resumed, but the + * OperationResponse object will not deserialize the final response. + * + * @param string $operationName The name of the long running operation + * @param string $methodName The name of the method used to start the operation + * + * @return OperationResponse + */ + public function resumeOperation($operationName, $methodName = null) + { + $options = isset($this->descriptors[$methodName]['longRunning']) ? $this->descriptors[$methodName]['longRunning'] : []; + $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); + $operation->reload(); + return $operation; + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'datastore.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + $this->operationsClient = $this->createOperationsClient($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Creates the specified index. + * A newly created index's initial state is `CREATING`. On completion of the + * returned [google.longrunning.Operation][google.longrunning.Operation], the state will be `READY`. + * If the index already exists, the call will return an `ALREADY_EXISTS` + * status. + * + * During index creation, the process could result in an error, in which + * case the index will move to the `ERROR` state. The process can be recovered + * by fixing the data that caused the error, removing the index with + * [delete][google.datastore.admin.v1.DatastoreAdmin.DeleteIndex], then + * re-creating the index with [create] + * [google.datastore.admin.v1.DatastoreAdmin.CreateIndex]. + * + * Indexes with a single property cannot be created. + * + * The async variant is {@see self::createIndexAsync()} . + * + * @param CreateIndexRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createIndex(CreateIndexRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreateIndex', $request, $callOptions)->wait(); + } + + /** + * Deletes an existing index. + * An index can only be deleted if it is in a `READY` or `ERROR` state. On + * successful execution of the request, the index will be in a `DELETING` + * [state][google.datastore.admin.v1.Index.State]. And on completion of the + * returned [google.longrunning.Operation][google.longrunning.Operation], the index will be removed. + * + * During index deletion, the process could result in an error, in which + * case the index will move to the `ERROR` state. The process can be recovered + * by fixing the data that caused the error, followed by calling + * [delete][google.datastore.admin.v1.DatastoreAdmin.DeleteIndex] again. + * + * The async variant is {@see self::deleteIndexAsync()} . + * + * @param DeleteIndexRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteIndex(DeleteIndexRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('DeleteIndex', $request, $callOptions)->wait(); + } + + /** + * Exports a copy of all or a subset of entities from Google Cloud Datastore + * to another storage system, such as Google Cloud Storage. Recent updates to + * entities may not be reflected in the export. The export occurs in the + * background and its progress can be monitored and managed via the + * Operation resource that is created. The output of an export may only be + * used once the associated operation is done. If an export operation is + * cancelled before completion it may leave partial data behind in Google + * Cloud Storage. + * + * The async variant is {@see self::exportEntitiesAsync()} . + * + * @param ExportEntitiesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function exportEntities(ExportEntitiesRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('ExportEntities', $request, $callOptions)->wait(); + } + + /** + * Gets an index. + * + * The async variant is {@see self::getIndexAsync()} . + * + * @param GetIndexRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Index + * + * @throws ApiException Thrown if the API call fails. + */ + public function getIndex(GetIndexRequest $request, array $callOptions = []): Index + { + return $this->startApiCall('GetIndex', $request, $callOptions)->wait(); + } + + /** + * Imports entities into Google Cloud Datastore. Existing entities with the + * same key are overwritten. The import occurs in the background and its + * progress can be monitored and managed via the Operation resource that is + * created. If an ImportEntities operation is cancelled, it is possible + * that a subset of the data has already been imported to Cloud Datastore. + * + * The async variant is {@see self::importEntitiesAsync()} . + * + * @param ImportEntitiesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function importEntities(ImportEntitiesRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('ImportEntities', $request, $callOptions)->wait(); + } + + /** + * Lists the indexes that match the specified filters. Datastore uses an + * eventually consistent query to fetch the list of indexes and may + * occasionally return stale results. + * + * The async variant is {@see self::listIndexesAsync()} . + * + * @param ListIndexesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listIndexes(ListIndexesRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListIndexes', $request, $callOptions); + } +} diff --git a/DatastoreAdmin/src/V1/Client/DatastoreAdminClient.php b/DatastoreAdmin/src/V1/Client/DatastoreAdminClient.php new file mode 100644 index 000000000000..7b6254c8a128 --- /dev/null +++ b/DatastoreAdmin/src/V1/Client/DatastoreAdminClient.php @@ -0,0 +1,40 @@ +setProjectId($projectId) + ->setLabels($labels) + ->setEntityFilter($entityFilter) + ->setOutputUrlPrefix($outputUrlPrefix); + } + /** * Constructor. * diff --git a/DatastoreAdmin/src/V1/ImportEntitiesRequest.php b/DatastoreAdmin/src/V1/ImportEntitiesRequest.php index 7d123961a72d..cf4ef7b00dab 100644 --- a/DatastoreAdmin/src/V1/ImportEntitiesRequest.php +++ b/DatastoreAdmin/src/V1/ImportEntitiesRequest.php @@ -55,6 +55,40 @@ class ImportEntitiesRequest extends \Google\Protobuf\Internal\Message */ private $entity_filter = null; + /** + * @param string $projectId Required. Project ID against which to make the request. + * @param array $labels Client-assigned labels. + * @param string $inputUrl Required. The full resource URL of the external storage location. Currently, only + * Google Cloud Storage is supported. So input_url should be of the form: + * `gs://BUCKET_NAME[/NAMESPACE_PATH]/OVERALL_EXPORT_METADATA_FILE`, where + * `BUCKET_NAME` is the name of the Cloud Storage bucket, `NAMESPACE_PATH` is + * an optional Cloud Storage namespace path (this is not a Cloud Datastore + * namespace), and `OVERALL_EXPORT_METADATA_FILE` is the metadata file written + * by the ExportEntities operation. For more information about Cloud Storage + * namespace paths, see + * [Object name + * considerations](https://cloud.google.com/storage/docs/naming#object-considerations). + * + * For more information, see + * [google.datastore.admin.v1.ExportEntitiesResponse.output_url][google.datastore.admin.v1.ExportEntitiesResponse.output_url]. + * @param \Google\Cloud\Datastore\Admin\V1\EntityFilter $entityFilter Optionally specify which kinds/namespaces are to be imported. If provided, + * the list must be a subset of the EntityFilter used in creating the export, + * otherwise a FAILED_PRECONDITION error will be returned. If no filter is + * specified then all entities from the export are imported. + * + * @return \Google\Cloud\Datastore\Admin\V1\ImportEntitiesRequest + * + * @experimental + */ + public static function build(string $projectId, array $labels, string $inputUrl, \Google\Cloud\Datastore\Admin\V1\EntityFilter $entityFilter): self + { + return (new self()) + ->setProjectId($projectId) + ->setLabels($labels) + ->setInputUrl($inputUrl) + ->setEntityFilter($entityFilter); + } + /** * Constructor. * diff --git a/DatastoreAdmin/src/V1/resources/datastore_admin_descriptor_config.php b/DatastoreAdmin/src/V1/resources/datastore_admin_descriptor_config.php index 97ba938665e6..e2891b13099f 100644 --- a/DatastoreAdmin/src/V1/resources/datastore_admin_descriptor_config.php +++ b/DatastoreAdmin/src/V1/resources/datastore_admin_descriptor_config.php @@ -12,6 +12,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'project_id', + 'fieldAccessors' => [ + 'getProjectId', + ], + ], + ], ], 'DeleteIndex' => [ 'longRunning' => [ @@ -22,6 +31,21 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'project_id', + 'fieldAccessors' => [ + 'getProjectId', + ], + ], + [ + 'keyName' => 'index_id', + 'fieldAccessors' => [ + 'getIndexId', + ], + ], + ], ], 'ExportEntities' => [ 'longRunning' => [ @@ -32,6 +56,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'project_id', + 'fieldAccessors' => [ + 'getProjectId', + ], + ], + ], ], 'ImportEntities' => [ 'longRunning' => [ @@ -42,6 +75,33 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'project_id', + 'fieldAccessors' => [ + 'getProjectId', + ], + ], + ], + ], + 'GetIndex' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Datastore\Admin\V1\Index', + 'headerParams' => [ + [ + 'keyName' => 'project_id', + 'fieldAccessors' => [ + 'getProjectId', + ], + ], + [ + 'keyName' => 'index_id', + 'fieldAccessors' => [ + 'getIndexId', + ], + ], + ], ], 'ListIndexes' => [ 'pageStreaming' => [ @@ -52,6 +112,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getIndexes', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Datastore\Admin\V1\ListIndexesResponse', + 'headerParams' => [ + [ + 'keyName' => 'project_id', + 'fieldAccessors' => [ + 'getProjectId', + ], + ], + ], ], ], ], diff --git a/DatastoreAdmin/tests/Unit/V1/Client/DatastoreAdminClientTest.php b/DatastoreAdmin/tests/Unit/V1/Client/DatastoreAdminClientTest.php new file mode 100644 index 000000000000..f183c3c2f2ce --- /dev/null +++ b/DatastoreAdmin/tests/Unit/V1/Client/DatastoreAdminClientTest.php @@ -0,0 +1,757 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return DatastoreAdminClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new DatastoreAdminClient($options); + } + + /** @test */ + public function createIndexTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createIndexTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $projectId2 = 'projectId2939242356'; + $indexId = 'indexId112508840'; + $kind = 'kind3292052'; + $expectedResponse = new Index(); + $expectedResponse->setProjectId($projectId2); + $expectedResponse->setIndexId($indexId); + $expectedResponse->setKind($kind); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createIndexTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + $request = new CreateIndexRequest(); + $response = $gapicClient->createIndex($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.datastore.admin.v1.DatastoreAdmin/CreateIndex', $actualApiFuncCall); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createIndexTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createIndexExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createIndexTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + $request = new CreateIndexRequest(); + $response = $gapicClient->createIndex($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createIndexTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteIndexTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteIndexTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $projectId2 = 'projectId2939242356'; + $indexId2 = 'indexId2746815835'; + $kind = 'kind3292052'; + $expectedResponse = new Index(); + $expectedResponse->setProjectId($projectId2); + $expectedResponse->setIndexId($indexId2); + $expectedResponse->setKind($kind); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/deleteIndexTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + $request = new DeleteIndexRequest(); + $response = $gapicClient->deleteIndex($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.datastore.admin.v1.DatastoreAdmin/DeleteIndex', $actualApiFuncCall); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteIndexTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteIndexExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteIndexTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + $request = new DeleteIndexRequest(); + $response = $gapicClient->deleteIndex($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteIndexTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function exportEntitiesTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/exportEntitiesTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $outputUrl = 'outputUrl-1273518799'; + $expectedResponse = new ExportEntitiesResponse(); + $expectedResponse->setOutputUrl($outputUrl); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/exportEntitiesTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $projectId = 'projectId-1969970175'; + $outputUrlPrefix = 'outputUrlPrefix1058210144'; + $request = (new ExportEntitiesRequest()) + ->setProjectId($projectId) + ->setOutputUrlPrefix($outputUrlPrefix); + $response = $gapicClient->exportEntities($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.datastore.admin.v1.DatastoreAdmin/ExportEntities', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getProjectId(); + $this->assertProtobufEquals($projectId, $actualValue); + $actualValue = $actualApiRequestObject->getOutputUrlPrefix(); + $this->assertProtobufEquals($outputUrlPrefix, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/exportEntitiesTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function exportEntitiesExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/exportEntitiesTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $projectId = 'projectId-1969970175'; + $outputUrlPrefix = 'outputUrlPrefix1058210144'; + $request = (new ExportEntitiesRequest()) + ->setProjectId($projectId) + ->setOutputUrlPrefix($outputUrlPrefix); + $response = $gapicClient->exportEntities($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/exportEntitiesTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function getIndexTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $projectId2 = 'projectId2939242356'; + $indexId2 = 'indexId2746815835'; + $kind = 'kind3292052'; + $expectedResponse = new Index(); + $expectedResponse->setProjectId($projectId2); + $expectedResponse->setIndexId($indexId2); + $expectedResponse->setKind($kind); + $transport->addResponse($expectedResponse); + $request = new GetIndexRequest(); + $response = $gapicClient->getIndex($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.datastore.admin.v1.DatastoreAdmin/GetIndex', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getIndexExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + $request = new GetIndexRequest(); + try { + $gapicClient->getIndex($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function importEntitiesTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/importEntitiesTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new GPBEmpty(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/importEntitiesTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $projectId = 'projectId-1969970175'; + $inputUrl = 'inputUrl1707300730'; + $request = (new ImportEntitiesRequest()) + ->setProjectId($projectId) + ->setInputUrl($inputUrl); + $response = $gapicClient->importEntities($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.datastore.admin.v1.DatastoreAdmin/ImportEntities', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getProjectId(); + $this->assertProtobufEquals($projectId, $actualValue); + $actualValue = $actualApiRequestObject->getInputUrl(); + $this->assertProtobufEquals($inputUrl, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/importEntitiesTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function importEntitiesExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/importEntitiesTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $projectId = 'projectId-1969970175'; + $inputUrl = 'inputUrl1707300730'; + $request = (new ImportEntitiesRequest()) + ->setProjectId($projectId) + ->setInputUrl($inputUrl); + $response = $gapicClient->importEntities($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/importEntitiesTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function listIndexesTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $indexesElement = new Index(); + $indexes = [ + $indexesElement, + ]; + $expectedResponse = new ListIndexesResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setIndexes($indexes); + $transport->addResponse($expectedResponse); + $request = new ListIndexesRequest(); + $response = $gapicClient->listIndexes($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getIndexes()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.datastore.admin.v1.DatastoreAdmin/ListIndexes', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listIndexesExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + $request = new ListIndexesRequest(); + try { + $gapicClient->listIndexes($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createIndexAsyncTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createIndexTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $projectId2 = 'projectId2939242356'; + $indexId = 'indexId112508840'; + $kind = 'kind3292052'; + $expectedResponse = new Index(); + $expectedResponse->setProjectId($projectId2); + $expectedResponse->setIndexId($indexId); + $expectedResponse->setKind($kind); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createIndexTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + $request = new CreateIndexRequest(); + $response = $gapicClient->createIndexAsync($request)->wait(); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.datastore.admin.v1.DatastoreAdmin/CreateIndex', $actualApiFuncCall); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createIndexTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } +} diff --git a/Deploy/samples/V1/CloudDeployClient/abandon_release.php b/Deploy/samples/V1/CloudDeployClient/abandon_release.php index 84898e2f584b..82bf477492b3 100644 --- a/Deploy/samples/V1/CloudDeployClient/abandon_release.php +++ b/Deploy/samples/V1/CloudDeployClient/abandon_release.php @@ -24,8 +24,9 @@ // [START clouddeploy_v1_generated_CloudDeploy_AbandonRelease_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Deploy\V1\AbandonReleaseRequest; use Google\Cloud\Deploy\V1\AbandonReleaseResponse; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; /** * Abandons a Release in the Delivery Pipeline. @@ -40,10 +41,14 @@ function abandon_release_sample(string $formattedName): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new AbandonReleaseRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var AbandonReleaseResponse $response */ - $response = $cloudDeployClient->abandonRelease($formattedName); + $response = $cloudDeployClient->abandonRelease($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Deploy/samples/V1/CloudDeployClient/advance_rollout.php b/Deploy/samples/V1/CloudDeployClient/advance_rollout.php index 7fb43404c725..a4e29ebaa7fb 100644 --- a/Deploy/samples/V1/CloudDeployClient/advance_rollout.php +++ b/Deploy/samples/V1/CloudDeployClient/advance_rollout.php @@ -24,8 +24,9 @@ // [START clouddeploy_v1_generated_CloudDeploy_AdvanceRollout_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Deploy\V1\AdvanceRolloutRequest; use Google\Cloud\Deploy\V1\AdvanceRolloutResponse; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; /** * Advances a Rollout in a given project and location. @@ -41,10 +42,15 @@ function advance_rollout_sample(string $formattedName, string $phaseId): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new AdvanceRolloutRequest()) + ->setName($formattedName) + ->setPhaseId($phaseId); + // Call the API and handle any network failures. try { /** @var AdvanceRolloutResponse $response */ - $response = $cloudDeployClient->advanceRollout($formattedName, $phaseId); + $response = $cloudDeployClient->advanceRollout($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Deploy/samples/V1/CloudDeployClient/approve_rollout.php b/Deploy/samples/V1/CloudDeployClient/approve_rollout.php index 8cf59d5d5658..f2da1166c019 100644 --- a/Deploy/samples/V1/CloudDeployClient/approve_rollout.php +++ b/Deploy/samples/V1/CloudDeployClient/approve_rollout.php @@ -24,8 +24,9 @@ // [START clouddeploy_v1_generated_CloudDeploy_ApproveRollout_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Deploy\V1\ApproveRolloutRequest; use Google\Cloud\Deploy\V1\ApproveRolloutResponse; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; /** * Approves a Rollout. @@ -41,10 +42,15 @@ function approve_rollout_sample(string $formattedName, bool $approved): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new ApproveRolloutRequest()) + ->setName($formattedName) + ->setApproved($approved); + // Call the API and handle any network failures. try { /** @var ApproveRolloutResponse $response */ - $response = $cloudDeployClient->approveRollout($formattedName, $approved); + $response = $cloudDeployClient->approveRollout($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Deploy/samples/V1/CloudDeployClient/cancel_rollout.php b/Deploy/samples/V1/CloudDeployClient/cancel_rollout.php index e33a97cafe8c..2f06b27d86a9 100644 --- a/Deploy/samples/V1/CloudDeployClient/cancel_rollout.php +++ b/Deploy/samples/V1/CloudDeployClient/cancel_rollout.php @@ -24,8 +24,9 @@ // [START clouddeploy_v1_generated_CloudDeploy_CancelRollout_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Deploy\V1\CancelRolloutRequest; use Google\Cloud\Deploy\V1\CancelRolloutResponse; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; /** * Cancels a Rollout in a given project and location. @@ -40,10 +41,14 @@ function cancel_rollout_sample(string $formattedName): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new CancelRolloutRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var CancelRolloutResponse $response */ - $response = $cloudDeployClient->cancelRollout($formattedName); + $response = $cloudDeployClient->cancelRollout($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Deploy/samples/V1/CloudDeployClient/create_delivery_pipeline.php b/Deploy/samples/V1/CloudDeployClient/create_delivery_pipeline.php index df856bfe57fc..bf8a7ac6d3a3 100644 --- a/Deploy/samples/V1/CloudDeployClient/create_delivery_pipeline.php +++ b/Deploy/samples/V1/CloudDeployClient/create_delivery_pipeline.php @@ -25,7 +25,8 @@ // [START clouddeploy_v1_generated_CloudDeploy_CreateDeliveryPipeline_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; +use Google\Cloud\Deploy\V1\CreateDeliveryPipelineRequest; use Google\Cloud\Deploy\V1\DeliveryPipeline; use Google\Rpc\Status; @@ -44,17 +45,17 @@ function create_delivery_pipeline_sample( // Create a client. $cloudDeployClient = new CloudDeployClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $deliveryPipeline = new DeliveryPipeline(); + $request = (new CreateDeliveryPipelineRequest()) + ->setParent($formattedParent) + ->setDeliveryPipelineId($deliveryPipelineId) + ->setDeliveryPipeline($deliveryPipeline); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $cloudDeployClient->createDeliveryPipeline( - $formattedParent, - $deliveryPipelineId, - $deliveryPipeline - ); + $response = $cloudDeployClient->createDeliveryPipeline($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/Deploy/samples/V1/CloudDeployClient/create_release.php b/Deploy/samples/V1/CloudDeployClient/create_release.php index f2f62524a6de..e5446b1c445e 100644 --- a/Deploy/samples/V1/CloudDeployClient/create_release.php +++ b/Deploy/samples/V1/CloudDeployClient/create_release.php @@ -25,7 +25,8 @@ // [START clouddeploy_v1_generated_CloudDeploy_CreateRelease_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; +use Google\Cloud\Deploy\V1\CreateReleaseRequest; use Google\Cloud\Deploy\V1\Release; use Google\Rpc\Status; @@ -43,13 +44,17 @@ function create_release_sample(string $formattedParent, string $releaseId): void // Create a client. $cloudDeployClient = new CloudDeployClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $release = new Release(); + $request = (new CreateReleaseRequest()) + ->setParent($formattedParent) + ->setReleaseId($releaseId) + ->setRelease($release); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $cloudDeployClient->createRelease($formattedParent, $releaseId, $release); + $response = $cloudDeployClient->createRelease($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/Deploy/samples/V1/CloudDeployClient/create_rollout.php b/Deploy/samples/V1/CloudDeployClient/create_rollout.php index 926bb53fd1b4..c46ab0213837 100644 --- a/Deploy/samples/V1/CloudDeployClient/create_rollout.php +++ b/Deploy/samples/V1/CloudDeployClient/create_rollout.php @@ -25,7 +25,8 @@ // [START clouddeploy_v1_generated_CloudDeploy_CreateRollout_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; +use Google\Cloud\Deploy\V1\CreateRolloutRequest; use Google\Cloud\Deploy\V1\Rollout; use Google\Rpc\Status; @@ -47,14 +48,18 @@ function create_rollout_sample( // Create a client. $cloudDeployClient = new CloudDeployClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $rollout = (new Rollout()) ->setTargetId($rolloutTargetId); + $request = (new CreateRolloutRequest()) + ->setParent($formattedParent) + ->setRolloutId($rolloutId) + ->setRollout($rollout); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $cloudDeployClient->createRollout($formattedParent, $rolloutId, $rollout); + $response = $cloudDeployClient->createRollout($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/Deploy/samples/V1/CloudDeployClient/create_target.php b/Deploy/samples/V1/CloudDeployClient/create_target.php index 0b43dc26da1d..18601019c823 100644 --- a/Deploy/samples/V1/CloudDeployClient/create_target.php +++ b/Deploy/samples/V1/CloudDeployClient/create_target.php @@ -25,7 +25,8 @@ // [START clouddeploy_v1_generated_CloudDeploy_CreateTarget_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; +use Google\Cloud\Deploy\V1\CreateTargetRequest; use Google\Cloud\Deploy\V1\Target; use Google\Rpc\Status; @@ -43,13 +44,17 @@ function create_target_sample(string $formattedParent, string $targetId): void // Create a client. $cloudDeployClient = new CloudDeployClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $target = new Target(); + $request = (new CreateTargetRequest()) + ->setParent($formattedParent) + ->setTargetId($targetId) + ->setTarget($target); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $cloudDeployClient->createTarget($formattedParent, $targetId, $target); + $response = $cloudDeployClient->createTarget($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/Deploy/samples/V1/CloudDeployClient/delete_delivery_pipeline.php b/Deploy/samples/V1/CloudDeployClient/delete_delivery_pipeline.php index 0f05b43d7461..ba31ce72c6ce 100644 --- a/Deploy/samples/V1/CloudDeployClient/delete_delivery_pipeline.php +++ b/Deploy/samples/V1/CloudDeployClient/delete_delivery_pipeline.php @@ -25,7 +25,8 @@ // [START clouddeploy_v1_generated_CloudDeploy_DeleteDeliveryPipeline_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; +use Google\Cloud\Deploy\V1\DeleteDeliveryPipelineRequest; use Google\Rpc\Status; /** @@ -40,10 +41,14 @@ function delete_delivery_pipeline_sample(string $formattedName): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new DeleteDeliveryPipelineRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $cloudDeployClient->deleteDeliveryPipeline($formattedName); + $response = $cloudDeployClient->deleteDeliveryPipeline($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/Deploy/samples/V1/CloudDeployClient/delete_target.php b/Deploy/samples/V1/CloudDeployClient/delete_target.php index 3beaab22b23d..418ebf348524 100644 --- a/Deploy/samples/V1/CloudDeployClient/delete_target.php +++ b/Deploy/samples/V1/CloudDeployClient/delete_target.php @@ -25,7 +25,8 @@ // [START clouddeploy_v1_generated_CloudDeploy_DeleteTarget_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; +use Google\Cloud\Deploy\V1\DeleteTargetRequest; use Google\Rpc\Status; /** @@ -40,10 +41,14 @@ function delete_target_sample(string $formattedName): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new DeleteTargetRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $cloudDeployClient->deleteTarget($formattedName); + $response = $cloudDeployClient->deleteTarget($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/Deploy/samples/V1/CloudDeployClient/get_config.php b/Deploy/samples/V1/CloudDeployClient/get_config.php index 84db5f263bc0..b50f4f8819d2 100644 --- a/Deploy/samples/V1/CloudDeployClient/get_config.php +++ b/Deploy/samples/V1/CloudDeployClient/get_config.php @@ -24,8 +24,9 @@ // [START clouddeploy_v1_generated_CloudDeploy_GetConfig_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; use Google\Cloud\Deploy\V1\Config; +use Google\Cloud\Deploy\V1\GetConfigRequest; /** * Gets the configuration for a location. @@ -38,10 +39,14 @@ function get_config_sample(string $formattedName): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new GetConfigRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var Config $response */ - $response = $cloudDeployClient->getConfig($formattedName); + $response = $cloudDeployClient->getConfig($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Deploy/samples/V1/CloudDeployClient/get_delivery_pipeline.php b/Deploy/samples/V1/CloudDeployClient/get_delivery_pipeline.php index 1dd92c619233..2c41013e1fab 100644 --- a/Deploy/samples/V1/CloudDeployClient/get_delivery_pipeline.php +++ b/Deploy/samples/V1/CloudDeployClient/get_delivery_pipeline.php @@ -24,8 +24,9 @@ // [START clouddeploy_v1_generated_CloudDeploy_GetDeliveryPipeline_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; use Google\Cloud\Deploy\V1\DeliveryPipeline; +use Google\Cloud\Deploy\V1\GetDeliveryPipelineRequest; /** * Gets details of a single DeliveryPipeline. @@ -39,10 +40,14 @@ function get_delivery_pipeline_sample(string $formattedName): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new GetDeliveryPipelineRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var DeliveryPipeline $response */ - $response = $cloudDeployClient->getDeliveryPipeline($formattedName); + $response = $cloudDeployClient->getDeliveryPipeline($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Deploy/samples/V1/CloudDeployClient/get_iam_policy.php b/Deploy/samples/V1/CloudDeployClient/get_iam_policy.php index 362249597843..1f99bf9ab655 100644 --- a/Deploy/samples/V1/CloudDeployClient/get_iam_policy.php +++ b/Deploy/samples/V1/CloudDeployClient/get_iam_policy.php @@ -24,7 +24,8 @@ // [START clouddeploy_v1_generated_CloudDeploy_GetIamPolicy_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; +use Google\Cloud\Iam\V1\GetIamPolicyRequest; use Google\Cloud\Iam\V1\Policy; /** @@ -39,10 +40,14 @@ function get_iam_policy_sample(string $resource): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new GetIamPolicyRequest()) + ->setResource($resource); + // Call the API and handle any network failures. try { /** @var Policy $response */ - $response = $cloudDeployClient->getIamPolicy($resource); + $response = $cloudDeployClient->getIamPolicy($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Deploy/samples/V1/CloudDeployClient/get_job_run.php b/Deploy/samples/V1/CloudDeployClient/get_job_run.php index bcc553a2a349..464dfb132a12 100644 --- a/Deploy/samples/V1/CloudDeployClient/get_job_run.php +++ b/Deploy/samples/V1/CloudDeployClient/get_job_run.php @@ -24,7 +24,8 @@ // [START clouddeploy_v1_generated_CloudDeploy_GetJobRun_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; +use Google\Cloud\Deploy\V1\GetJobRunRequest; use Google\Cloud\Deploy\V1\JobRun; /** @@ -39,10 +40,14 @@ function get_job_run_sample(string $formattedName): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new GetJobRunRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var JobRun $response */ - $response = $cloudDeployClient->getJobRun($formattedName); + $response = $cloudDeployClient->getJobRun($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Deploy/samples/V1/CloudDeployClient/get_location.php b/Deploy/samples/V1/CloudDeployClient/get_location.php index c84dfd4366d2..bd44680a4f6d 100644 --- a/Deploy/samples/V1/CloudDeployClient/get_location.php +++ b/Deploy/samples/V1/CloudDeployClient/get_location.php @@ -24,7 +24,8 @@ // [START clouddeploy_v1_generated_CloudDeploy_GetLocation_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; +use Google\Cloud\Location\GetLocationRequest; use Google\Cloud\Location\Location; /** @@ -41,10 +42,13 @@ function get_location_sample(): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = new GetLocationRequest(); + // Call the API and handle any network failures. try { /** @var Location $response */ - $response = $cloudDeployClient->getLocation(); + $response = $cloudDeployClient->getLocation($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Deploy/samples/V1/CloudDeployClient/get_release.php b/Deploy/samples/V1/CloudDeployClient/get_release.php index 68c9aef00e02..fc99a2eab671 100644 --- a/Deploy/samples/V1/CloudDeployClient/get_release.php +++ b/Deploy/samples/V1/CloudDeployClient/get_release.php @@ -24,7 +24,8 @@ // [START clouddeploy_v1_generated_CloudDeploy_GetRelease_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; +use Google\Cloud\Deploy\V1\GetReleaseRequest; use Google\Cloud\Deploy\V1\Release; /** @@ -39,10 +40,14 @@ function get_release_sample(string $formattedName): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new GetReleaseRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var Release $response */ - $response = $cloudDeployClient->getRelease($formattedName); + $response = $cloudDeployClient->getRelease($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Deploy/samples/V1/CloudDeployClient/get_rollout.php b/Deploy/samples/V1/CloudDeployClient/get_rollout.php index bb852864c78f..667b70399884 100644 --- a/Deploy/samples/V1/CloudDeployClient/get_rollout.php +++ b/Deploy/samples/V1/CloudDeployClient/get_rollout.php @@ -24,7 +24,8 @@ // [START clouddeploy_v1_generated_CloudDeploy_GetRollout_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; +use Google\Cloud\Deploy\V1\GetRolloutRequest; use Google\Cloud\Deploy\V1\Rollout; /** @@ -39,10 +40,14 @@ function get_rollout_sample(string $formattedName): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new GetRolloutRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var Rollout $response */ - $response = $cloudDeployClient->getRollout($formattedName); + $response = $cloudDeployClient->getRollout($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Deploy/samples/V1/CloudDeployClient/get_target.php b/Deploy/samples/V1/CloudDeployClient/get_target.php index df39a82c675c..f70889e7980d 100644 --- a/Deploy/samples/V1/CloudDeployClient/get_target.php +++ b/Deploy/samples/V1/CloudDeployClient/get_target.php @@ -24,7 +24,8 @@ // [START clouddeploy_v1_generated_CloudDeploy_GetTarget_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; +use Google\Cloud\Deploy\V1\GetTargetRequest; use Google\Cloud\Deploy\V1\Target; /** @@ -39,10 +40,14 @@ function get_target_sample(string $formattedName): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new GetTargetRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var Target $response */ - $response = $cloudDeployClient->getTarget($formattedName); + $response = $cloudDeployClient->getTarget($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Deploy/samples/V1/CloudDeployClient/ignore_job.php b/Deploy/samples/V1/CloudDeployClient/ignore_job.php index 38fa06686ada..a6299b104e6e 100644 --- a/Deploy/samples/V1/CloudDeployClient/ignore_job.php +++ b/Deploy/samples/V1/CloudDeployClient/ignore_job.php @@ -24,7 +24,8 @@ // [START clouddeploy_v1_generated_CloudDeploy_IgnoreJob_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; +use Google\Cloud\Deploy\V1\IgnoreJobRequest; use Google\Cloud\Deploy\V1\IgnoreJobResponse; /** @@ -42,10 +43,16 @@ function ignore_job_sample(string $formattedRollout, string $phaseId, string $jo // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new IgnoreJobRequest()) + ->setRollout($formattedRollout) + ->setPhaseId($phaseId) + ->setJobId($jobId); + // Call the API and handle any network failures. try { /** @var IgnoreJobResponse $response */ - $response = $cloudDeployClient->ignoreJob($formattedRollout, $phaseId, $jobId); + $response = $cloudDeployClient->ignoreJob($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Deploy/samples/V1/CloudDeployClient/list_delivery_pipelines.php b/Deploy/samples/V1/CloudDeployClient/list_delivery_pipelines.php index b6a701169de9..447dbe52066c 100644 --- a/Deploy/samples/V1/CloudDeployClient/list_delivery_pipelines.php +++ b/Deploy/samples/V1/CloudDeployClient/list_delivery_pipelines.php @@ -25,8 +25,9 @@ // [START clouddeploy_v1_generated_CloudDeploy_ListDeliveryPipelines_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; use Google\Cloud\Deploy\V1\DeliveryPipeline; +use Google\Cloud\Deploy\V1\ListDeliveryPipelinesRequest; /** * Lists DeliveryPipelines in a given project and location. @@ -40,10 +41,14 @@ function list_delivery_pipelines_sample(string $formattedParent): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new ListDeliveryPipelinesRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $cloudDeployClient->listDeliveryPipelines($formattedParent); + $response = $cloudDeployClient->listDeliveryPipelines($request); /** @var DeliveryPipeline $element */ foreach ($response as $element) { diff --git a/Deploy/samples/V1/CloudDeployClient/list_job_runs.php b/Deploy/samples/V1/CloudDeployClient/list_job_runs.php index eea012f1b829..29230d6be7d8 100644 --- a/Deploy/samples/V1/CloudDeployClient/list_job_runs.php +++ b/Deploy/samples/V1/CloudDeployClient/list_job_runs.php @@ -25,8 +25,9 @@ // [START clouddeploy_v1_generated_CloudDeploy_ListJobRuns_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; use Google\Cloud\Deploy\V1\JobRun; +use Google\Cloud\Deploy\V1\ListJobRunsRequest; /** * Lists JobRuns in a given project and location. @@ -39,10 +40,14 @@ function list_job_runs_sample(string $formattedParent): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new ListJobRunsRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $cloudDeployClient->listJobRuns($formattedParent); + $response = $cloudDeployClient->listJobRuns($request); /** @var JobRun $element */ foreach ($response as $element) { diff --git a/Deploy/samples/V1/CloudDeployClient/list_locations.php b/Deploy/samples/V1/CloudDeployClient/list_locations.php index 79f8dff1e5ef..95adcee559ad 100644 --- a/Deploy/samples/V1/CloudDeployClient/list_locations.php +++ b/Deploy/samples/V1/CloudDeployClient/list_locations.php @@ -25,7 +25,8 @@ // [START clouddeploy_v1_generated_CloudDeploy_ListLocations_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; +use Google\Cloud\Location\ListLocationsRequest; use Google\Cloud\Location\Location; /** @@ -42,10 +43,13 @@ function list_locations_sample(): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = new ListLocationsRequest(); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $cloudDeployClient->listLocations(); + $response = $cloudDeployClient->listLocations($request); /** @var Location $element */ foreach ($response as $element) { diff --git a/Deploy/samples/V1/CloudDeployClient/list_releases.php b/Deploy/samples/V1/CloudDeployClient/list_releases.php index 2928f47b609a..32773cda6616 100644 --- a/Deploy/samples/V1/CloudDeployClient/list_releases.php +++ b/Deploy/samples/V1/CloudDeployClient/list_releases.php @@ -25,7 +25,8 @@ // [START clouddeploy_v1_generated_CloudDeploy_ListReleases_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; +use Google\Cloud\Deploy\V1\ListReleasesRequest; use Google\Cloud\Deploy\V1\Release; /** @@ -40,10 +41,14 @@ function list_releases_sample(string $formattedParent): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new ListReleasesRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $cloudDeployClient->listReleases($formattedParent); + $response = $cloudDeployClient->listReleases($request); /** @var Release $element */ foreach ($response as $element) { diff --git a/Deploy/samples/V1/CloudDeployClient/list_rollouts.php b/Deploy/samples/V1/CloudDeployClient/list_rollouts.php index 0018d727af6e..fdd6a27c9f93 100644 --- a/Deploy/samples/V1/CloudDeployClient/list_rollouts.php +++ b/Deploy/samples/V1/CloudDeployClient/list_rollouts.php @@ -25,7 +25,8 @@ // [START clouddeploy_v1_generated_CloudDeploy_ListRollouts_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; +use Google\Cloud\Deploy\V1\ListRolloutsRequest; use Google\Cloud\Deploy\V1\Rollout; /** @@ -39,10 +40,14 @@ function list_rollouts_sample(string $formattedParent): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new ListRolloutsRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $cloudDeployClient->listRollouts($formattedParent); + $response = $cloudDeployClient->listRollouts($request); /** @var Rollout $element */ foreach ($response as $element) { diff --git a/Deploy/samples/V1/CloudDeployClient/list_targets.php b/Deploy/samples/V1/CloudDeployClient/list_targets.php index 955e7a45d18e..9a60148f6746 100644 --- a/Deploy/samples/V1/CloudDeployClient/list_targets.php +++ b/Deploy/samples/V1/CloudDeployClient/list_targets.php @@ -25,7 +25,8 @@ // [START clouddeploy_v1_generated_CloudDeploy_ListTargets_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; +use Google\Cloud\Deploy\V1\ListTargetsRequest; use Google\Cloud\Deploy\V1\Target; /** @@ -40,10 +41,14 @@ function list_targets_sample(string $formattedParent): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new ListTargetsRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $cloudDeployClient->listTargets($formattedParent); + $response = $cloudDeployClient->listTargets($request); /** @var Target $element */ foreach ($response as $element) { diff --git a/Deploy/samples/V1/CloudDeployClient/retry_job.php b/Deploy/samples/V1/CloudDeployClient/retry_job.php index 01580dfe48eb..1b7a6dc8cd22 100644 --- a/Deploy/samples/V1/CloudDeployClient/retry_job.php +++ b/Deploy/samples/V1/CloudDeployClient/retry_job.php @@ -24,7 +24,8 @@ // [START clouddeploy_v1_generated_CloudDeploy_RetryJob_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; +use Google\Cloud\Deploy\V1\RetryJobRequest; use Google\Cloud\Deploy\V1\RetryJobResponse; /** @@ -42,10 +43,16 @@ function retry_job_sample(string $formattedRollout, string $phaseId, string $job // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new RetryJobRequest()) + ->setRollout($formattedRollout) + ->setPhaseId($phaseId) + ->setJobId($jobId); + // Call the API and handle any network failures. try { /** @var RetryJobResponse $response */ - $response = $cloudDeployClient->retryJob($formattedRollout, $phaseId, $jobId); + $response = $cloudDeployClient->retryJob($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Deploy/samples/V1/CloudDeployClient/set_iam_policy.php b/Deploy/samples/V1/CloudDeployClient/set_iam_policy.php index 58f4a615c66b..c2f9cb10c9a1 100644 --- a/Deploy/samples/V1/CloudDeployClient/set_iam_policy.php +++ b/Deploy/samples/V1/CloudDeployClient/set_iam_policy.php @@ -24,8 +24,9 @@ // [START clouddeploy_v1_generated_CloudDeploy_SetIamPolicy_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; use Google\Cloud\Iam\V1\Policy; +use Google\Cloud\Iam\V1\SetIamPolicyRequest; /** * Sets the access control policy on the specified resource. Replaces @@ -42,13 +43,16 @@ function set_iam_policy_sample(string $resource): void // Create a client. $cloudDeployClient = new CloudDeployClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $policy = new Policy(); + $request = (new SetIamPolicyRequest()) + ->setResource($resource) + ->setPolicy($policy); // Call the API and handle any network failures. try { /** @var Policy $response */ - $response = $cloudDeployClient->setIamPolicy($resource, $policy); + $response = $cloudDeployClient->setIamPolicy($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Deploy/samples/V1/CloudDeployClient/terminate_job_run.php b/Deploy/samples/V1/CloudDeployClient/terminate_job_run.php index 72c345566632..8be2add33f13 100644 --- a/Deploy/samples/V1/CloudDeployClient/terminate_job_run.php +++ b/Deploy/samples/V1/CloudDeployClient/terminate_job_run.php @@ -24,7 +24,8 @@ // [START clouddeploy_v1_generated_CloudDeploy_TerminateJobRun_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; +use Google\Cloud\Deploy\V1\TerminateJobRunRequest; use Google\Cloud\Deploy\V1\TerminateJobRunResponse; /** @@ -40,10 +41,14 @@ function terminate_job_run_sample(string $formattedName): void // Create a client. $cloudDeployClient = new CloudDeployClient(); + // Prepare the request message. + $request = (new TerminateJobRunRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var TerminateJobRunResponse $response */ - $response = $cloudDeployClient->terminateJobRun($formattedName); + $response = $cloudDeployClient->terminateJobRun($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Deploy/samples/V1/CloudDeployClient/test_iam_permissions.php b/Deploy/samples/V1/CloudDeployClient/test_iam_permissions.php index 9100efd60d9c..346128d68307 100644 --- a/Deploy/samples/V1/CloudDeployClient/test_iam_permissions.php +++ b/Deploy/samples/V1/CloudDeployClient/test_iam_permissions.php @@ -24,7 +24,8 @@ // [START clouddeploy_v1_generated_CloudDeploy_TestIamPermissions_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; +use Google\Cloud\Iam\V1\TestIamPermissionsRequest; use Google\Cloud\Iam\V1\TestIamPermissionsResponse; /** @@ -48,13 +49,16 @@ function test_iam_permissions_sample(string $resource, string $permissionsElemen // Create a client. $cloudDeployClient = new CloudDeployClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $permissions = [$permissionsElement,]; + $request = (new TestIamPermissionsRequest()) + ->setResource($resource) + ->setPermissions($permissions); // Call the API and handle any network failures. try { /** @var TestIamPermissionsResponse $response */ - $response = $cloudDeployClient->testIamPermissions($resource, $permissions); + $response = $cloudDeployClient->testIamPermissions($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Deploy/samples/V1/CloudDeployClient/update_delivery_pipeline.php b/Deploy/samples/V1/CloudDeployClient/update_delivery_pipeline.php index dbabfe69474e..511739fb415b 100644 --- a/Deploy/samples/V1/CloudDeployClient/update_delivery_pipeline.php +++ b/Deploy/samples/V1/CloudDeployClient/update_delivery_pipeline.php @@ -25,8 +25,9 @@ // [START clouddeploy_v1_generated_CloudDeploy_UpdateDeliveryPipeline_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; use Google\Cloud\Deploy\V1\DeliveryPipeline; +use Google\Cloud\Deploy\V1\UpdateDeliveryPipelineRequest; use Google\Protobuf\FieldMask; use Google\Rpc\Status; @@ -44,14 +45,17 @@ function update_delivery_pipeline_sample(): void // Create a client. $cloudDeployClient = new CloudDeployClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $updateMask = new FieldMask(); $deliveryPipeline = new DeliveryPipeline(); + $request = (new UpdateDeliveryPipelineRequest()) + ->setUpdateMask($updateMask) + ->setDeliveryPipeline($deliveryPipeline); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $cloudDeployClient->updateDeliveryPipeline($updateMask, $deliveryPipeline); + $response = $cloudDeployClient->updateDeliveryPipeline($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/Deploy/samples/V1/CloudDeployClient/update_target.php b/Deploy/samples/V1/CloudDeployClient/update_target.php index eb39965caa01..6474ba6adc55 100644 --- a/Deploy/samples/V1/CloudDeployClient/update_target.php +++ b/Deploy/samples/V1/CloudDeployClient/update_target.php @@ -25,8 +25,9 @@ // [START clouddeploy_v1_generated_CloudDeploy_UpdateTarget_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Deploy\V1\CloudDeployClient; +use Google\Cloud\Deploy\V1\Client\CloudDeployClient; use Google\Cloud\Deploy\V1\Target; +use Google\Cloud\Deploy\V1\UpdateTargetRequest; use Google\Protobuf\FieldMask; use Google\Rpc\Status; @@ -44,14 +45,17 @@ function update_target_sample(): void // Create a client. $cloudDeployClient = new CloudDeployClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $updateMask = new FieldMask(); $target = new Target(); + $request = (new UpdateTargetRequest()) + ->setUpdateMask($updateMask) + ->setTarget($target); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $cloudDeployClient->updateTarget($updateMask, $target); + $response = $cloudDeployClient->updateTarget($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/Deploy/src/V1/AbandonReleaseRequest.php b/Deploy/src/V1/AbandonReleaseRequest.php index e6b6675238a9..e1f06a8e0f14 100644 --- a/Deploy/src/V1/AbandonReleaseRequest.php +++ b/Deploy/src/V1/AbandonReleaseRequest.php @@ -24,6 +24,22 @@ class AbandonReleaseRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. Name of the Release. Format is + * projects/{project}/locations/{location}/deliveryPipelines/{deliveryPipeline}/ + * releases/{release}. Please see + * {@see CloudDeployClient::releaseName()} for help formatting this field. + * + * @return \Google\Cloud\Deploy\V1\AbandonReleaseRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Deploy/src/V1/AdvanceRolloutRequest.php b/Deploy/src/V1/AdvanceRolloutRequest.php index 8616afee668d..5a5b88966f3d 100644 --- a/Deploy/src/V1/AdvanceRolloutRequest.php +++ b/Deploy/src/V1/AdvanceRolloutRequest.php @@ -30,6 +30,24 @@ class AdvanceRolloutRequest extends \Google\Protobuf\Internal\Message */ private $phase_id = ''; + /** + * @param string $name Required. Name of the Rollout. Format is + * projects/{project}/locations/{location}/deliveryPipelines/{deliveryPipeline}/ + * releases/{release}/rollouts/{rollout}. Please see + * {@see CloudDeployClient::rolloutName()} for help formatting this field. + * @param string $phaseId Required. The phase ID to advance the `Rollout` to. + * + * @return \Google\Cloud\Deploy\V1\AdvanceRolloutRequest + * + * @experimental + */ + public static function build(string $name, string $phaseId): self + { + return (new self()) + ->setName($name) + ->setPhaseId($phaseId); + } + /** * Constructor. * diff --git a/Deploy/src/V1/ApproveRolloutRequest.php b/Deploy/src/V1/ApproveRolloutRequest.php index d5aff8e5c3a9..693f1b278317 100644 --- a/Deploy/src/V1/ApproveRolloutRequest.php +++ b/Deploy/src/V1/ApproveRolloutRequest.php @@ -30,6 +30,22 @@ class ApproveRolloutRequest extends \Google\Protobuf\Internal\Message */ private $approved = false; + /** + * @param string $name Required. Name of the Rollout. Format is + * projects/{project}/locations/{location}/deliveryPipelines/{deliveryPipeline}/ + * releases/{release}/rollouts/{rollout}. Please see + * {@see CloudDeployClient::rolloutName()} for help formatting this field. + * + * @return \Google\Cloud\Deploy\V1\ApproveRolloutRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Deploy/src/V1/CancelRolloutRequest.php b/Deploy/src/V1/CancelRolloutRequest.php index fd10b8461482..6a89985c2af0 100644 --- a/Deploy/src/V1/CancelRolloutRequest.php +++ b/Deploy/src/V1/CancelRolloutRequest.php @@ -24,6 +24,22 @@ class CancelRolloutRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. Name of the Rollout. Format is + * projects/{project}/locations/{location}/deliveryPipelines/{deliveryPipeline}/ + * releases/{release}/rollouts/{rollout}. Please see + * {@see CloudDeployClient::rolloutName()} for help formatting this field. + * + * @return \Google\Cloud\Deploy\V1\CancelRolloutRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Deploy/src/V1/Client/BaseClient/CloudDeployBaseClient.php b/Deploy/src/V1/Client/BaseClient/CloudDeployBaseClient.php new file mode 100644 index 000000000000..94001d9d0a8c --- /dev/null +++ b/Deploy/src/V1/Client/BaseClient/CloudDeployBaseClient.php @@ -0,0 +1,1307 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/cloud_deploy_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/cloud_deploy_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/cloud_deploy_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/cloud_deploy_rest_client_config.php', + ], + ], + ]; + } + + /** + * Return an OperationsClient object with the same endpoint as $this. + * + * @return OperationsClient + */ + public function getOperationsClient() + { + return $this->operationsClient; + } + + /** + * Resume an existing long running operation that was previously started by a long + * running API method. If $methodName is not provided, or does not match a long + * running API method, then the operation can still be resumed, but the + * OperationResponse object will not deserialize the final response. + * + * @param string $operationName The name of the long running operation + * @param string $methodName The name of the method used to start the operation + * + * @return OperationResponse + */ + public function resumeOperation($operationName, $methodName = null) + { + $options = isset($this->descriptors[$methodName]['longRunning']) ? $this->descriptors[$methodName]['longRunning'] : []; + $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); + $operation->reload(); + return $operation; + } + + /** + * Formats a string containing the fully-qualified path to represent a build + * resource. + * + * @param string $project + * @param string $location + * @param string $build + * + * @return string The formatted build resource. + */ + public static function buildName(string $project, string $location, string $build): string + { + return self::getPathTemplate('build')->render([ + 'project' => $project, + 'location' => $location, + 'build' => $build, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a cluster + * resource. + * + * @param string $project + * @param string $location + * @param string $cluster + * + * @return string The formatted cluster resource. + */ + public static function clusterName(string $project, string $location, string $cluster): string + { + return self::getPathTemplate('cluster')->render([ + 'project' => $project, + 'location' => $location, + 'cluster' => $cluster, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a config + * resource. + * + * @param string $project + * @param string $location + * + * @return string The formatted config resource. + */ + public static function configName(string $project, string $location): string + { + return self::getPathTemplate('config')->render([ + 'project' => $project, + 'location' => $location, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * delivery_pipeline resource. + * + * @param string $project + * @param string $location + * @param string $deliveryPipeline + * + * @return string The formatted delivery_pipeline resource. + */ + public static function deliveryPipelineName(string $project, string $location, string $deliveryPipeline): string + { + return self::getPathTemplate('deliveryPipeline')->render([ + 'project' => $project, + 'location' => $location, + 'delivery_pipeline' => $deliveryPipeline, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a job_run + * resource. + * + * @param string $project + * @param string $location + * @param string $deliveryPipeline + * @param string $release + * @param string $rollout + * @param string $jobRun + * + * @return string The formatted job_run resource. + */ + public static function jobRunName(string $project, string $location, string $deliveryPipeline, string $release, string $rollout, string $jobRun): string + { + return self::getPathTemplate('jobRun')->render([ + 'project' => $project, + 'location' => $location, + 'delivery_pipeline' => $deliveryPipeline, + 'release' => $release, + 'rollout' => $rollout, + 'job_run' => $jobRun, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a location + * resource. + * + * @param string $project + * @param string $location + * + * @return string The formatted location resource. + */ + public static function locationName(string $project, string $location): string + { + return self::getPathTemplate('location')->render([ + 'project' => $project, + 'location' => $location, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a membership + * resource. + * + * @param string $project + * @param string $location + * @param string $membership + * + * @return string The formatted membership resource. + */ + public static function membershipName(string $project, string $location, string $membership): string + { + return self::getPathTemplate('membership')->render([ + 'project' => $project, + 'location' => $location, + 'membership' => $membership, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a release + * resource. + * + * @param string $project + * @param string $location + * @param string $deliveryPipeline + * @param string $release + * + * @return string The formatted release resource. + */ + public static function releaseName(string $project, string $location, string $deliveryPipeline, string $release): string + { + return self::getPathTemplate('release')->render([ + 'project' => $project, + 'location' => $location, + 'delivery_pipeline' => $deliveryPipeline, + 'release' => $release, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a rollout + * resource. + * + * @param string $project + * @param string $location + * @param string $deliveryPipeline + * @param string $release + * @param string $rollout + * + * @return string The formatted rollout resource. + */ + public static function rolloutName(string $project, string $location, string $deliveryPipeline, string $release, string $rollout): string + { + return self::getPathTemplate('rollout')->render([ + 'project' => $project, + 'location' => $location, + 'delivery_pipeline' => $deliveryPipeline, + 'release' => $release, + 'rollout' => $rollout, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a service + * resource. + * + * @param string $project + * @param string $location + * @param string $service + * + * @return string The formatted service resource. + */ + public static function serviceName(string $project, string $location, string $service): string + { + return self::getPathTemplate('service')->render([ + 'project' => $project, + 'location' => $location, + 'service' => $service, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a target + * resource. + * + * @param string $project + * @param string $location + * @param string $target + * + * @return string The formatted target resource. + */ + public static function targetName(string $project, string $location, string $target): string + { + return self::getPathTemplate('target')->render([ + 'project' => $project, + 'location' => $location, + 'target' => $target, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a worker_pool + * resource. + * + * @param string $project + * @param string $location + * @param string $workerPool + * + * @return string The formatted worker_pool resource. + */ + public static function workerPoolName(string $project, string $location, string $workerPool): string + { + return self::getPathTemplate('workerPool')->render([ + 'project' => $project, + 'location' => $location, + 'worker_pool' => $workerPool, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - build: projects/{project}/locations/{location}/builds/{build} + * - cluster: projects/{project}/locations/{location}/clusters/{cluster} + * - config: projects/{project}/locations/{location}/config + * - deliveryPipeline: projects/{project}/locations/{location}/deliveryPipelines/{delivery_pipeline} + * - jobRun: projects/{project}/locations/{location}/deliveryPipelines/{delivery_pipeline}/releases/{release}/rollouts/{rollout}/jobRuns/{job_run} + * - location: projects/{project}/locations/{location} + * - membership: projects/{project}/locations/{location}/memberships/{membership} + * - release: projects/{project}/locations/{location}/deliveryPipelines/{delivery_pipeline}/releases/{release} + * - rollout: projects/{project}/locations/{location}/deliveryPipelines/{delivery_pipeline}/releases/{release}/rollouts/{rollout} + * - service: projects/{project}/locations/{location}/services/{service} + * - target: projects/{project}/locations/{location}/targets/{target} + * - workerPool: projects/{project}/locations/{location}/workerPools/{worker_pool} + * + * The optional $template argument can be supplied to specify a particular pattern, + * and must match one of the templates listed above. If no $template argument is + * provided, or if the $template argument does not match one of the templates + * listed, then parseName will check each of the supported templates, and return + * the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + */ + public static function parseName(string $formattedName, string $template = null): array + { + return self::parseFormattedName($formattedName, $template); + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'clouddeploy.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + $this->operationsClient = $this->createOperationsClient($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Abandons a Release in the Delivery Pipeline. + * + * The async variant is {@see self::abandonReleaseAsync()} . + * + * @param AbandonReleaseRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return AbandonReleaseResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function abandonRelease(AbandonReleaseRequest $request, array $callOptions = []): AbandonReleaseResponse + { + return $this->startApiCall('AbandonRelease', $request, $callOptions)->wait(); + } + + /** + * Advances a Rollout in a given project and location. + * + * The async variant is {@see self::advanceRolloutAsync()} . + * + * @param AdvanceRolloutRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return AdvanceRolloutResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function advanceRollout(AdvanceRolloutRequest $request, array $callOptions = []): AdvanceRolloutResponse + { + return $this->startApiCall('AdvanceRollout', $request, $callOptions)->wait(); + } + + /** + * Approves a Rollout. + * + * The async variant is {@see self::approveRolloutAsync()} . + * + * @param ApproveRolloutRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return ApproveRolloutResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function approveRollout(ApproveRolloutRequest $request, array $callOptions = []): ApproveRolloutResponse + { + return $this->startApiCall('ApproveRollout', $request, $callOptions)->wait(); + } + + /** + * Cancels a Rollout in a given project and location. + * + * The async variant is {@see self::cancelRolloutAsync()} . + * + * @param CancelRolloutRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return CancelRolloutResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function cancelRollout(CancelRolloutRequest $request, array $callOptions = []): CancelRolloutResponse + { + return $this->startApiCall('CancelRollout', $request, $callOptions)->wait(); + } + + /** + * Creates a new DeliveryPipeline in a given project and location. + * + * The async variant is {@see self::createDeliveryPipelineAsync()} . + * + * @param CreateDeliveryPipelineRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createDeliveryPipeline(CreateDeliveryPipelineRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreateDeliveryPipeline', $request, $callOptions)->wait(); + } + + /** + * Creates a new Release in a given project and location. + * + * The async variant is {@see self::createReleaseAsync()} . + * + * @param CreateReleaseRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createRelease(CreateReleaseRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreateRelease', $request, $callOptions)->wait(); + } + + /** + * Creates a new Rollout in a given project and location. + * + * The async variant is {@see self::createRolloutAsync()} . + * + * @param CreateRolloutRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createRollout(CreateRolloutRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreateRollout', $request, $callOptions)->wait(); + } + + /** + * Creates a new Target in a given project and location. + * + * The async variant is {@see self::createTargetAsync()} . + * + * @param CreateTargetRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createTarget(CreateTargetRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreateTarget', $request, $callOptions)->wait(); + } + + /** + * Deletes a single DeliveryPipeline. + * + * The async variant is {@see self::deleteDeliveryPipelineAsync()} . + * + * @param DeleteDeliveryPipelineRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteDeliveryPipeline(DeleteDeliveryPipelineRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('DeleteDeliveryPipeline', $request, $callOptions)->wait(); + } + + /** + * Deletes a single Target. + * + * The async variant is {@see self::deleteTargetAsync()} . + * + * @param DeleteTargetRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteTarget(DeleteTargetRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('DeleteTarget', $request, $callOptions)->wait(); + } + + /** + * Gets the configuration for a location. + * + * The async variant is {@see self::getConfigAsync()} . + * + * @param GetConfigRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Config + * + * @throws ApiException Thrown if the API call fails. + */ + public function getConfig(GetConfigRequest $request, array $callOptions = []): Config + { + return $this->startApiCall('GetConfig', $request, $callOptions)->wait(); + } + + /** + * Gets details of a single DeliveryPipeline. + * + * The async variant is {@see self::getDeliveryPipelineAsync()} . + * + * @param GetDeliveryPipelineRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return DeliveryPipeline + * + * @throws ApiException Thrown if the API call fails. + */ + public function getDeliveryPipeline(GetDeliveryPipelineRequest $request, array $callOptions = []): DeliveryPipeline + { + return $this->startApiCall('GetDeliveryPipeline', $request, $callOptions)->wait(); + } + + /** + * Gets details of a single JobRun. + * + * The async variant is {@see self::getJobRunAsync()} . + * + * @param GetJobRunRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return JobRun + * + * @throws ApiException Thrown if the API call fails. + */ + public function getJobRun(GetJobRunRequest $request, array $callOptions = []): JobRun + { + return $this->startApiCall('GetJobRun', $request, $callOptions)->wait(); + } + + /** + * Gets details of a single Release. + * + * The async variant is {@see self::getReleaseAsync()} . + * + * @param GetReleaseRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Release + * + * @throws ApiException Thrown if the API call fails. + */ + public function getRelease(GetReleaseRequest $request, array $callOptions = []): Release + { + return $this->startApiCall('GetRelease', $request, $callOptions)->wait(); + } + + /** + * Gets details of a single Rollout. + * + * The async variant is {@see self::getRolloutAsync()} . + * + * @param GetRolloutRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Rollout + * + * @throws ApiException Thrown if the API call fails. + */ + public function getRollout(GetRolloutRequest $request, array $callOptions = []): Rollout + { + return $this->startApiCall('GetRollout', $request, $callOptions)->wait(); + } + + /** + * Gets details of a single Target. + * + * The async variant is {@see self::getTargetAsync()} . + * + * @param GetTargetRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Target + * + * @throws ApiException Thrown if the API call fails. + */ + public function getTarget(GetTargetRequest $request, array $callOptions = []): Target + { + return $this->startApiCall('GetTarget', $request, $callOptions)->wait(); + } + + /** + * Ignores the specified Job in a Rollout. + * + * The async variant is {@see self::ignoreJobAsync()} . + * + * @param IgnoreJobRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return IgnoreJobResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function ignoreJob(IgnoreJobRequest $request, array $callOptions = []): IgnoreJobResponse + { + return $this->startApiCall('IgnoreJob', $request, $callOptions)->wait(); + } + + /** + * Lists DeliveryPipelines in a given project and location. + * + * The async variant is {@see self::listDeliveryPipelinesAsync()} . + * + * @param ListDeliveryPipelinesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listDeliveryPipelines(ListDeliveryPipelinesRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListDeliveryPipelines', $request, $callOptions); + } + + /** + * Lists JobRuns in a given project and location. + * + * The async variant is {@see self::listJobRunsAsync()} . + * + * @param ListJobRunsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listJobRuns(ListJobRunsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListJobRuns', $request, $callOptions); + } + + /** + * Lists Releases in a given project and location. + * + * The async variant is {@see self::listReleasesAsync()} . + * + * @param ListReleasesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listReleases(ListReleasesRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListReleases', $request, $callOptions); + } + + /** + * Lists Rollouts in a given project and location. + * + * The async variant is {@see self::listRolloutsAsync()} . + * + * @param ListRolloutsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listRollouts(ListRolloutsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListRollouts', $request, $callOptions); + } + + /** + * Lists Targets in a given project and location. + * + * The async variant is {@see self::listTargetsAsync()} . + * + * @param ListTargetsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listTargets(ListTargetsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListTargets', $request, $callOptions); + } + + /** + * Retries the specified Job in a Rollout. + * + * The async variant is {@see self::retryJobAsync()} . + * + * @param RetryJobRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return RetryJobResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function retryJob(RetryJobRequest $request, array $callOptions = []): RetryJobResponse + { + return $this->startApiCall('RetryJob', $request, $callOptions)->wait(); + } + + /** + * Terminates a Job Run in a given project and location. + * + * The async variant is {@see self::terminateJobRunAsync()} . + * + * @param TerminateJobRunRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return TerminateJobRunResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function terminateJobRun(TerminateJobRunRequest $request, array $callOptions = []): TerminateJobRunResponse + { + return $this->startApiCall('TerminateJobRun', $request, $callOptions)->wait(); + } + + /** + * Updates the parameters of a single DeliveryPipeline. + * + * The async variant is {@see self::updateDeliveryPipelineAsync()} . + * + * @param UpdateDeliveryPipelineRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function updateDeliveryPipeline(UpdateDeliveryPipelineRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('UpdateDeliveryPipeline', $request, $callOptions)->wait(); + } + + /** + * Updates the parameters of a single Target. + * + * The async variant is {@see self::updateTargetAsync()} . + * + * @param UpdateTargetRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function updateTarget(UpdateTargetRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('UpdateTarget', $request, $callOptions)->wait(); + } + + /** + * Gets information about a location. + * + * The async variant is {@see self::getLocationAsync()} . + * + * @param GetLocationRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Location + * + * @throws ApiException Thrown if the API call fails. + */ + public function getLocation(GetLocationRequest $request, array $callOptions = []): Location + { + return $this->startApiCall('GetLocation', $request, $callOptions)->wait(); + } + + /** + * Lists information about the supported locations for this service. + * + * The async variant is {@see self::listLocationsAsync()} . + * + * @param ListLocationsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listLocations(ListLocationsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListLocations', $request, $callOptions); + } + + /** + * Gets the access control policy for a resource. Returns an empty policy + if the resource exists and does not have a policy set. + * + * The async variant is {@see self::getIamPolicyAsync()} . + * + * @param GetIamPolicyRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Policy + * + * @throws ApiException Thrown if the API call fails. + */ + public function getIamPolicy(GetIamPolicyRequest $request, array $callOptions = []): Policy + { + return $this->startApiCall('GetIamPolicy', $request, $callOptions)->wait(); + } + + /** + * Sets the access control policy on the specified resource. Replaces + any existing policy. + + Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` + errors. + * + * The async variant is {@see self::setIamPolicyAsync()} . + * + * @param SetIamPolicyRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Policy + * + * @throws ApiException Thrown if the API call fails. + */ + public function setIamPolicy(SetIamPolicyRequest $request, array $callOptions = []): Policy + { + return $this->startApiCall('SetIamPolicy', $request, $callOptions)->wait(); + } + + /** + * Returns permissions that a caller has on the specified resource. If the + resource does not exist, this will return an empty set of + permissions, not a `NOT_FOUND` error. + + Note: This operation is designed to be used for building + permission-aware UIs and command-line tools, not for authorization + checking. This operation may "fail open" without warning. + * + * The async variant is {@see self::testIamPermissionsAsync()} . + * + * @param TestIamPermissionsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return TestIamPermissionsResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function testIamPermissions(TestIamPermissionsRequest $request, array $callOptions = []): TestIamPermissionsResponse + { + return $this->startApiCall('TestIamPermissions', $request, $callOptions)->wait(); + } +} diff --git a/Deploy/src/V1/Client/CloudDeployClient.php b/Deploy/src/V1/Client/CloudDeployClient.php new file mode 100644 index 000000000000..56001b0b4c94 --- /dev/null +++ b/Deploy/src/V1/Client/CloudDeployClient.php @@ -0,0 +1,40 @@ +setParent($parent) + ->setDeliveryPipeline($deliveryPipeline) + ->setDeliveryPipelineId($deliveryPipelineId); + } + /** * Constructor. * diff --git a/Deploy/src/V1/CreateReleaseRequest.php b/Deploy/src/V1/CreateReleaseRequest.php index c2179002916d..dc22d99105cd 100644 --- a/Deploy/src/V1/CreateReleaseRequest.php +++ b/Deploy/src/V1/CreateReleaseRequest.php @@ -59,6 +59,26 @@ class CreateReleaseRequest extends \Google\Protobuf\Internal\Message */ private $validate_only = false; + /** + * @param string $parent Required. The parent collection in which the `Release` should be created. + * Format should be + * projects/{project_id}/locations/{location_name}/deliveryPipelines/{pipeline_name}. Please see + * {@see CloudDeployClient::deliveryPipelineName()} for help formatting this field. + * @param \Google\Cloud\Deploy\V1\Release $release Required. The `Release` to create. + * @param string $releaseId Required. ID of the `Release`. + * + * @return \Google\Cloud\Deploy\V1\CreateReleaseRequest + * + * @experimental + */ + public static function build(string $parent, \Google\Cloud\Deploy\V1\Release $release, string $releaseId): self + { + return (new self()) + ->setParent($parent) + ->setRelease($release) + ->setReleaseId($releaseId); + } + /** * Constructor. * diff --git a/Deploy/src/V1/CreateRolloutRequest.php b/Deploy/src/V1/CreateRolloutRequest.php index d5c3a4522840..35df462ff684 100644 --- a/Deploy/src/V1/CreateRolloutRequest.php +++ b/Deploy/src/V1/CreateRolloutRequest.php @@ -66,6 +66,26 @@ class CreateRolloutRequest extends \Google\Protobuf\Internal\Message */ private $starting_phase_id = ''; + /** + * @param string $parent Required. The parent collection in which the `Rollout` should be created. + * Format should be + * projects/{project_id}/locations/{location_name}/deliveryPipelines/{pipeline_name}/releases/{release_name}. Please see + * {@see CloudDeployClient::releaseName()} for help formatting this field. + * @param \Google\Cloud\Deploy\V1\Rollout $rollout Required. The `Rollout` to create. + * @param string $rolloutId Required. ID of the `Rollout`. + * + * @return \Google\Cloud\Deploy\V1\CreateRolloutRequest + * + * @experimental + */ + public static function build(string $parent, \Google\Cloud\Deploy\V1\Rollout $rollout, string $rolloutId): self + { + return (new self()) + ->setParent($parent) + ->setRollout($rollout) + ->setRolloutId($rolloutId); + } + /** * Constructor. * diff --git a/Deploy/src/V1/CreateTargetRequest.php b/Deploy/src/V1/CreateTargetRequest.php index b4dc6faa024b..86da967d90a6 100644 --- a/Deploy/src/V1/CreateTargetRequest.php +++ b/Deploy/src/V1/CreateTargetRequest.php @@ -59,6 +59,26 @@ class CreateTargetRequest extends \Google\Protobuf\Internal\Message */ private $validate_only = false; + /** + * @param string $parent Required. The parent collection in which the `Target` should be created. + * Format should be + * projects/{project_id}/locations/{location_name}. Please see + * {@see CloudDeployClient::locationName()} for help formatting this field. + * @param \Google\Cloud\Deploy\V1\Target $target Required. The `Target` to create. + * @param string $targetId Required. ID of the `Target`. + * + * @return \Google\Cloud\Deploy\V1\CreateTargetRequest + * + * @experimental + */ + public static function build(string $parent, \Google\Cloud\Deploy\V1\Target $target, string $targetId): self + { + return (new self()) + ->setParent($parent) + ->setTarget($target) + ->setTargetId($targetId); + } + /** * Constructor. * diff --git a/Deploy/src/V1/DeleteDeliveryPipelineRequest.php b/Deploy/src/V1/DeleteDeliveryPipelineRequest.php index c440006b7c5b..37a8d3ddca88 100644 --- a/Deploy/src/V1/DeleteDeliveryPipelineRequest.php +++ b/Deploy/src/V1/DeleteDeliveryPipelineRequest.php @@ -69,6 +69,21 @@ class DeleteDeliveryPipelineRequest extends \Google\Protobuf\Internal\Message */ private $etag = ''; + /** + * @param string $name Required. The name of the `DeliveryPipeline` to delete. Format should be + * projects/{project_id}/locations/{location_name}/deliveryPipelines/{pipeline_name}. Please see + * {@see CloudDeployClient::deliveryPipelineName()} for help formatting this field. + * + * @return \Google\Cloud\Deploy\V1\DeleteDeliveryPipelineRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Deploy/src/V1/DeleteTargetRequest.php b/Deploy/src/V1/DeleteTargetRequest.php index fef5e5c92985..f82ff495c716 100644 --- a/Deploy/src/V1/DeleteTargetRequest.php +++ b/Deploy/src/V1/DeleteTargetRequest.php @@ -61,6 +61,21 @@ class DeleteTargetRequest extends \Google\Protobuf\Internal\Message */ private $etag = ''; + /** + * @param string $name Required. The name of the `Target` to delete. Format should be + * projects/{project_id}/locations/{location_name}/targets/{target_name}. Please see + * {@see CloudDeployClient::targetName()} for help formatting this field. + * + * @return \Google\Cloud\Deploy\V1\DeleteTargetRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Deploy/src/V1/GetConfigRequest.php b/Deploy/src/V1/GetConfigRequest.php index b537f964636c..ea1950297147 100644 --- a/Deploy/src/V1/GetConfigRequest.php +++ b/Deploy/src/V1/GetConfigRequest.php @@ -22,6 +22,20 @@ class GetConfigRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. Name of requested configuration. Please see + * {@see CloudDeployClient::configName()} for help formatting this field. + * + * @return \Google\Cloud\Deploy\V1\GetConfigRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Deploy/src/V1/GetDeliveryPipelineRequest.php b/Deploy/src/V1/GetDeliveryPipelineRequest.php index c6e7a834d357..c006f8d7e0d5 100644 --- a/Deploy/src/V1/GetDeliveryPipelineRequest.php +++ b/Deploy/src/V1/GetDeliveryPipelineRequest.php @@ -23,6 +23,21 @@ class GetDeliveryPipelineRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. Name of the `DeliveryPipeline`. Format must be + * projects/{project_id}/locations/{location_name}/deliveryPipelines/{pipeline_name}. Please see + * {@see CloudDeployClient::deliveryPipelineName()} for help formatting this field. + * + * @return \Google\Cloud\Deploy\V1\GetDeliveryPipelineRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Deploy/src/V1/GetJobRunRequest.php b/Deploy/src/V1/GetJobRunRequest.php index 66cc0b4c13dd..51dea861e3e4 100644 --- a/Deploy/src/V1/GetJobRunRequest.php +++ b/Deploy/src/V1/GetJobRunRequest.php @@ -23,6 +23,21 @@ class GetJobRunRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. Name of the `JobRun`. Format must be + * projects/{project_id}/locations/{location_name}/deliveryPipelines/{pipeline_name}/releases/{release_name}/rollouts/{rollout_name}/jobRuns/{job_run_name}. Please see + * {@see CloudDeployClient::jobRunName()} for help formatting this field. + * + * @return \Google\Cloud\Deploy\V1\GetJobRunRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Deploy/src/V1/GetReleaseRequest.php b/Deploy/src/V1/GetReleaseRequest.php index 676443445832..c558a0d9e5c4 100644 --- a/Deploy/src/V1/GetReleaseRequest.php +++ b/Deploy/src/V1/GetReleaseRequest.php @@ -23,6 +23,21 @@ class GetReleaseRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. Name of the `Release`. Format must be + * projects/{project_id}/locations/{location_name}/deliveryPipelines/{pipeline_name}/releases/{release_name}. Please see + * {@see CloudDeployClient::releaseName()} for help formatting this field. + * + * @return \Google\Cloud\Deploy\V1\GetReleaseRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Deploy/src/V1/GetRolloutRequest.php b/Deploy/src/V1/GetRolloutRequest.php index 135d8db5e1bf..43f81d521799 100644 --- a/Deploy/src/V1/GetRolloutRequest.php +++ b/Deploy/src/V1/GetRolloutRequest.php @@ -23,6 +23,21 @@ class GetRolloutRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. Name of the `Rollout`. Format must be + * projects/{project_id}/locations/{location_name}/deliveryPipelines/{pipeline_name}/releases/{release_name}/rollouts/{rollout_name}. Please see + * {@see CloudDeployClient::rolloutName()} for help formatting this field. + * + * @return \Google\Cloud\Deploy\V1\GetRolloutRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Deploy/src/V1/GetTargetRequest.php b/Deploy/src/V1/GetTargetRequest.php index eb8866909e73..43469cb122e1 100644 --- a/Deploy/src/V1/GetTargetRequest.php +++ b/Deploy/src/V1/GetTargetRequest.php @@ -23,6 +23,21 @@ class GetTargetRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. Name of the `Target`. Format must be + * projects/{project_id}/locations/{location_name}/targets/{target_name}. Please see + * {@see CloudDeployClient::targetName()} for help formatting this field. + * + * @return \Google\Cloud\Deploy\V1\GetTargetRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Deploy/src/V1/IgnoreJobRequest.php b/Deploy/src/V1/IgnoreJobRequest.php index b0723539f227..9f855f4d1b50 100644 --- a/Deploy/src/V1/IgnoreJobRequest.php +++ b/Deploy/src/V1/IgnoreJobRequest.php @@ -36,6 +36,26 @@ class IgnoreJobRequest extends \Google\Protobuf\Internal\Message */ private $job_id = ''; + /** + * @param string $rollout Required. Name of the Rollout. Format is + * projects/{project}/locations/{location}/deliveryPipelines/{deliveryPipeline}/ + * releases/{release}/rollouts/{rollout}. Please see + * {@see CloudDeployClient::rolloutName()} for help formatting this field. + * @param string $phaseId Required. The phase ID the Job to ignore belongs to. + * @param string $jobId Required. The job ID for the Job to ignore. + * + * @return \Google\Cloud\Deploy\V1\IgnoreJobRequest + * + * @experimental + */ + public static function build(string $rollout, string $phaseId, string $jobId): self + { + return (new self()) + ->setRollout($rollout) + ->setPhaseId($phaseId) + ->setJobId($jobId); + } + /** * Constructor. * diff --git a/Deploy/src/V1/ListDeliveryPipelinesRequest.php b/Deploy/src/V1/ListDeliveryPipelinesRequest.php index 0455599674db..34aa60dca53d 100644 --- a/Deploy/src/V1/ListDeliveryPipelinesRequest.php +++ b/Deploy/src/V1/ListDeliveryPipelinesRequest.php @@ -54,6 +54,21 @@ class ListDeliveryPipelinesRequest extends \Google\Protobuf\Internal\Message */ private $order_by = ''; + /** + * @param string $parent Required. The parent, which owns this collection of pipelines. Format must + * be projects/{project_id}/locations/{location_name}. Please see + * {@see CloudDeployClient::locationName()} for help formatting this field. + * + * @return \Google\Cloud\Deploy\V1\ListDeliveryPipelinesRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/Deploy/src/V1/ListJobRunsRequest.php b/Deploy/src/V1/ListJobRunsRequest.php index 1be612ef809d..c6c362305fc1 100644 --- a/Deploy/src/V1/ListJobRunsRequest.php +++ b/Deploy/src/V1/ListJobRunsRequest.php @@ -54,6 +54,20 @@ class ListJobRunsRequest extends \Google\Protobuf\Internal\Message */ private $order_by = ''; + /** + * @param string $parent Required. The `Rollout` which owns this collection of `JobRun` objects. Please see + * {@see CloudDeployClient::rolloutName()} for help formatting this field. + * + * @return \Google\Cloud\Deploy\V1\ListJobRunsRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/Deploy/src/V1/ListReleasesRequest.php b/Deploy/src/V1/ListReleasesRequest.php index b35db8af4ba1..25c4de06de60 100644 --- a/Deploy/src/V1/ListReleasesRequest.php +++ b/Deploy/src/V1/ListReleasesRequest.php @@ -55,6 +55,21 @@ class ListReleasesRequest extends \Google\Protobuf\Internal\Message */ private $order_by = ''; + /** + * @param string $parent Required. The `DeliveryPipeline` which owns this collection of `Release` + * objects. Please see + * {@see CloudDeployClient::deliveryPipelineName()} for help formatting this field. + * + * @return \Google\Cloud\Deploy\V1\ListReleasesRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/Deploy/src/V1/ListRolloutsRequest.php b/Deploy/src/V1/ListRolloutsRequest.php index 291622dc35f7..9b2536e10068 100644 --- a/Deploy/src/V1/ListRolloutsRequest.php +++ b/Deploy/src/V1/ListRolloutsRequest.php @@ -54,6 +54,20 @@ class ListRolloutsRequest extends \Google\Protobuf\Internal\Message */ private $order_by = ''; + /** + * @param string $parent Required. The `Release` which owns this collection of `Rollout` objects. Please see + * {@see CloudDeployClient::releaseName()} for help formatting this field. + * + * @return \Google\Cloud\Deploy\V1\ListRolloutsRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/Deploy/src/V1/ListTargetsRequest.php b/Deploy/src/V1/ListTargetsRequest.php index 804851eb90c3..6395c1708e89 100644 --- a/Deploy/src/V1/ListTargetsRequest.php +++ b/Deploy/src/V1/ListTargetsRequest.php @@ -55,6 +55,21 @@ class ListTargetsRequest extends \Google\Protobuf\Internal\Message */ private $order_by = ''; + /** + * @param string $parent Required. The parent, which owns this collection of targets. Format must be + * projects/{project_id}/locations/{location_name}. Please see + * {@see CloudDeployClient::locationName()} for help formatting this field. + * + * @return \Google\Cloud\Deploy\V1\ListTargetsRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/Deploy/src/V1/RetryJobRequest.php b/Deploy/src/V1/RetryJobRequest.php index 64a808a9b0ef..3b7d9bf73fcd 100644 --- a/Deploy/src/V1/RetryJobRequest.php +++ b/Deploy/src/V1/RetryJobRequest.php @@ -36,6 +36,26 @@ class RetryJobRequest extends \Google\Protobuf\Internal\Message */ private $job_id = ''; + /** + * @param string $rollout Required. Name of the Rollout. Format is + * projects/{project}/locations/{location}/deliveryPipelines/{deliveryPipeline}/ + * releases/{release}/rollouts/{rollout}. Please see + * {@see CloudDeployClient::rolloutName()} for help formatting this field. + * @param string $phaseId Required. The phase ID the Job to retry belongs to. + * @param string $jobId Required. The job ID for the Job to retry. + * + * @return \Google\Cloud\Deploy\V1\RetryJobRequest + * + * @experimental + */ + public static function build(string $rollout, string $phaseId, string $jobId): self + { + return (new self()) + ->setRollout($rollout) + ->setPhaseId($phaseId) + ->setJobId($jobId); + } + /** * Constructor. * diff --git a/Deploy/src/V1/TerminateJobRunRequest.php b/Deploy/src/V1/TerminateJobRunRequest.php index 14d42a205af2..9a47303c4748 100644 --- a/Deploy/src/V1/TerminateJobRunRequest.php +++ b/Deploy/src/V1/TerminateJobRunRequest.php @@ -24,6 +24,22 @@ class TerminateJobRunRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. Name of the `JobRun`. Format must be + * projects/{project}/locations/{location}/deliveryPipelines/{deliveryPipeline}/ + * releases/{release}/rollouts/{rollout}/jobRuns/{jobRun}. Please see + * {@see CloudDeployClient::jobRunName()} for help formatting this field. + * + * @return \Google\Cloud\Deploy\V1\TerminateJobRunRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Deploy/src/V1/UpdateDeliveryPipelineRequest.php b/Deploy/src/V1/UpdateDeliveryPipelineRequest.php index 2570911bf5b2..1909aedc66b8 100644 --- a/Deploy/src/V1/UpdateDeliveryPipelineRequest.php +++ b/Deploy/src/V1/UpdateDeliveryPipelineRequest.php @@ -62,6 +62,25 @@ class UpdateDeliveryPipelineRequest extends \Google\Protobuf\Internal\Message */ private $validate_only = false; + /** + * @param \Google\Cloud\Deploy\V1\DeliveryPipeline $deliveryPipeline Required. The `DeliveryPipeline` to update. + * @param \Google\Protobuf\FieldMask $updateMask Required. Field mask is used to specify the fields to be overwritten in the + * `DeliveryPipeline` resource by the update. + * The fields specified in the update_mask are relative to the resource, not + * the full request. A field will be overwritten if it is in the mask. If the + * user does not provide a mask then all fields will be overwritten. + * + * @return \Google\Cloud\Deploy\V1\UpdateDeliveryPipelineRequest + * + * @experimental + */ + public static function build(\Google\Cloud\Deploy\V1\DeliveryPipeline $deliveryPipeline, \Google\Protobuf\FieldMask $updateMask): self + { + return (new self()) + ->setDeliveryPipeline($deliveryPipeline) + ->setUpdateMask($updateMask); + } + /** * Constructor. * diff --git a/Deploy/src/V1/UpdateTargetRequest.php b/Deploy/src/V1/UpdateTargetRequest.php index 8a1ffec2de7d..8f26b73400f8 100644 --- a/Deploy/src/V1/UpdateTargetRequest.php +++ b/Deploy/src/V1/UpdateTargetRequest.php @@ -62,6 +62,25 @@ class UpdateTargetRequest extends \Google\Protobuf\Internal\Message */ private $validate_only = false; + /** + * @param \Google\Cloud\Deploy\V1\Target $target Required. The `Target` to update. + * @param \Google\Protobuf\FieldMask $updateMask Required. Field mask is used to specify the fields to be overwritten in the + * Target resource by the update. + * The fields specified in the update_mask are relative to the resource, not + * the full request. A field will be overwritten if it is in the mask. If the + * user does not provide a mask then all fields will be overwritten. + * + * @return \Google\Cloud\Deploy\V1\UpdateTargetRequest + * + * @experimental + */ + public static function build(\Google\Cloud\Deploy\V1\Target $target, \Google\Protobuf\FieldMask $updateMask): self + { + return (new self()) + ->setTarget($target) + ->setUpdateMask($updateMask); + } + /** * Constructor. * diff --git a/Deploy/src/V1/resources/cloud_deploy_descriptor_config.php b/Deploy/src/V1/resources/cloud_deploy_descriptor_config.php index 1196a4a1cb71..3cad10a76835 100644 --- a/Deploy/src/V1/resources/cloud_deploy_descriptor_config.php +++ b/Deploy/src/V1/resources/cloud_deploy_descriptor_config.php @@ -12,6 +12,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'CreateRelease' => [ 'longRunning' => [ @@ -22,6 +31,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'CreateRollout' => [ 'longRunning' => [ @@ -32,6 +50,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'CreateTarget' => [ 'longRunning' => [ @@ -42,6 +69,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'DeleteDeliveryPipeline' => [ 'longRunning' => [ @@ -52,6 +88,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'DeleteTarget' => [ 'longRunning' => [ @@ -62,6 +107,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'UpdateDeliveryPipeline' => [ 'longRunning' => [ @@ -72,6 +126,16 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'delivery_pipeline.name', + 'fieldAccessors' => [ + 'getDeliveryPipeline', + 'getName', + ], + ], + ], ], 'UpdateTarget' => [ 'longRunning' => [ @@ -82,6 +146,148 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'target.name', + 'fieldAccessors' => [ + 'getTarget', + 'getName', + ], + ], + ], + ], + 'AbandonRelease' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Deploy\V1\AbandonReleaseResponse', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'AdvanceRollout' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Deploy\V1\AdvanceRolloutResponse', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'ApproveRollout' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Deploy\V1\ApproveRolloutResponse', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'CancelRollout' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Deploy\V1\CancelRolloutResponse', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetConfig' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Deploy\V1\Config', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetDeliveryPipeline' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Deploy\V1\DeliveryPipeline', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetJobRun' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Deploy\V1\JobRun', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetRelease' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Deploy\V1\Release', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetRollout' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Deploy\V1\Rollout', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetTarget' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Deploy\V1\Target', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'IgnoreJob' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Deploy\V1\IgnoreJobResponse', + 'headerParams' => [ + [ + 'keyName' => 'rollout', + 'fieldAccessors' => [ + 'getRollout', + ], + ], + ], ], 'ListDeliveryPipelines' => [ 'pageStreaming' => [ @@ -92,6 +298,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getDeliveryPipelines', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Deploy\V1\ListDeliveryPipelinesResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'ListJobRuns' => [ 'pageStreaming' => [ @@ -102,6 +318,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getJobRuns', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Deploy\V1\ListJobRunsResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'ListReleases' => [ 'pageStreaming' => [ @@ -112,6 +338,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getReleases', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Deploy\V1\ListReleasesResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'ListRollouts' => [ 'pageStreaming' => [ @@ -122,6 +358,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getRollouts', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Deploy\V1\ListRolloutsResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'ListTargets' => [ 'pageStreaming' => [ @@ -132,8 +378,52 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getTargets', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Deploy\V1\ListTargetsResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'RetryJob' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Deploy\V1\RetryJobResponse', + 'headerParams' => [ + [ + 'keyName' => 'rollout', + 'fieldAccessors' => [ + 'getRollout', + ], + ], + ], + ], + 'TerminateJobRun' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Deploy\V1\TerminateJobRunResponse', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'GetLocation' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Location\Location', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], 'interfaceOverride' => 'google.cloud.location.Locations', ], 'ListLocations' => [ @@ -145,17 +435,71 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getLocations', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Location\ListLocationsResponse', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], 'interfaceOverride' => 'google.cloud.location.Locations', ], 'GetIamPolicy' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Iam\V1\Policy', + 'headerParams' => [ + [ + 'keyName' => 'resource', + 'fieldAccessors' => [ + 'getResource', + ], + ], + ], 'interfaceOverride' => 'google.iam.v1.IAMPolicy', ], 'SetIamPolicy' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Iam\V1\Policy', + 'headerParams' => [ + [ + 'keyName' => 'resource', + 'fieldAccessors' => [ + 'getResource', + ], + ], + ], 'interfaceOverride' => 'google.iam.v1.IAMPolicy', ], 'TestIamPermissions' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Iam\V1\TestIamPermissionsResponse', + 'headerParams' => [ + [ + 'keyName' => 'resource', + 'fieldAccessors' => [ + 'getResource', + ], + ], + ], 'interfaceOverride' => 'google.iam.v1.IAMPolicy', ], + 'templateMap' => [ + 'build' => 'projects/{project}/locations/{location}/builds/{build}', + 'cluster' => 'projects/{project}/locations/{location}/clusters/{cluster}', + 'config' => 'projects/{project}/locations/{location}/config', + 'deliveryPipeline' => 'projects/{project}/locations/{location}/deliveryPipelines/{delivery_pipeline}', + 'jobRun' => 'projects/{project}/locations/{location}/deliveryPipelines/{delivery_pipeline}/releases/{release}/rollouts/{rollout}/jobRuns/{job_run}', + 'location' => 'projects/{project}/locations/{location}', + 'membership' => 'projects/{project}/locations/{location}/memberships/{membership}', + 'release' => 'projects/{project}/locations/{location}/deliveryPipelines/{delivery_pipeline}/releases/{release}', + 'rollout' => 'projects/{project}/locations/{location}/deliveryPipelines/{delivery_pipeline}/releases/{release}/rollouts/{rollout}', + 'service' => 'projects/{project}/locations/{location}/services/{service}', + 'target' => 'projects/{project}/locations/{location}/targets/{target}', + 'workerPool' => 'projects/{project}/locations/{location}/workerPools/{worker_pool}', + ], ], ], ]; diff --git a/Deploy/tests/Unit/V1/Client/CloudDeployClientTest.php b/Deploy/tests/Unit/V1/Client/CloudDeployClientTest.php new file mode 100644 index 000000000000..5ac54ab9a28d --- /dev/null +++ b/Deploy/tests/Unit/V1/Client/CloudDeployClientTest.php @@ -0,0 +1,2854 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return CloudDeployClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new CloudDeployClient($options); + } + + /** @test */ + public function abandonReleaseTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new AbandonReleaseResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->releaseName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]'); + $request = (new AbandonReleaseRequest()) + ->setName($formattedName); + $response = $gapicClient->abandonRelease($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/AbandonRelease', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function abandonReleaseExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->releaseName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]'); + $request = (new AbandonReleaseRequest()) + ->setName($formattedName); + try { + $gapicClient->abandonRelease($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function advanceRolloutTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new AdvanceRolloutResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->rolloutName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]', '[ROLLOUT]'); + $phaseId = 'phaseId-1676299681'; + $request = (new AdvanceRolloutRequest()) + ->setName($formattedName) + ->setPhaseId($phaseId); + $response = $gapicClient->advanceRollout($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/AdvanceRollout', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $actualValue = $actualRequestObject->getPhaseId(); + $this->assertProtobufEquals($phaseId, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function advanceRolloutExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->rolloutName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]', '[ROLLOUT]'); + $phaseId = 'phaseId-1676299681'; + $request = (new AdvanceRolloutRequest()) + ->setName($formattedName) + ->setPhaseId($phaseId); + try { + $gapicClient->advanceRollout($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function approveRolloutTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new ApproveRolloutResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->rolloutName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]', '[ROLLOUT]'); + $approved = false; + $request = (new ApproveRolloutRequest()) + ->setName($formattedName) + ->setApproved($approved); + $response = $gapicClient->approveRollout($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/ApproveRollout', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $actualValue = $actualRequestObject->getApproved(); + $this->assertProtobufEquals($approved, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function approveRolloutExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->rolloutName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]', '[ROLLOUT]'); + $approved = false; + $request = (new ApproveRolloutRequest()) + ->setName($formattedName) + ->setApproved($approved); + try { + $gapicClient->approveRollout($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function cancelRolloutTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new CancelRolloutResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->rolloutName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]', '[ROLLOUT]'); + $request = (new CancelRolloutRequest()) + ->setName($formattedName); + $response = $gapicClient->cancelRollout($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/CancelRollout', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function cancelRolloutExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->rolloutName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]', '[ROLLOUT]'); + $request = (new CancelRolloutRequest()) + ->setName($formattedName); + try { + $gapicClient->cancelRollout($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createDeliveryPipelineTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createDeliveryPipelineTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $uid = 'uid115792'; + $description = 'description-1724546052'; + $etag = 'etag3123477'; + $suspended = false; + $expectedResponse = new DeliveryPipeline(); + $expectedResponse->setName($name); + $expectedResponse->setUid($uid); + $expectedResponse->setDescription($description); + $expectedResponse->setEtag($etag); + $expectedResponse->setSuspended($suspended); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createDeliveryPipelineTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $deliveryPipelineId = 'deliveryPipelineId1972590605'; + $deliveryPipeline = new DeliveryPipeline(); + $request = (new CreateDeliveryPipelineRequest()) + ->setParent($formattedParent) + ->setDeliveryPipelineId($deliveryPipelineId) + ->setDeliveryPipeline($deliveryPipeline); + $response = $gapicClient->createDeliveryPipeline($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/CreateDeliveryPipeline', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getDeliveryPipelineId(); + $this->assertProtobufEquals($deliveryPipelineId, $actualValue); + $actualValue = $actualApiRequestObject->getDeliveryPipeline(); + $this->assertProtobufEquals($deliveryPipeline, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createDeliveryPipelineTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createDeliveryPipelineExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createDeliveryPipelineTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $deliveryPipelineId = 'deliveryPipelineId1972590605'; + $deliveryPipeline = new DeliveryPipeline(); + $request = (new CreateDeliveryPipelineRequest()) + ->setParent($formattedParent) + ->setDeliveryPipelineId($deliveryPipelineId) + ->setDeliveryPipeline($deliveryPipeline); + $response = $gapicClient->createDeliveryPipeline($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createDeliveryPipelineTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createReleaseTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createReleaseTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $uid = 'uid115792'; + $description = 'description-1724546052'; + $abandoned = true; + $skaffoldConfigUri = 'skaffoldConfigUri-860592176'; + $skaffoldConfigPath = 'skaffoldConfigPath-908718527'; + $etag = 'etag3123477'; + $skaffoldVersion = 'skaffoldVersion-1146663017'; + $expectedResponse = new Release(); + $expectedResponse->setName($name); + $expectedResponse->setUid($uid); + $expectedResponse->setDescription($description); + $expectedResponse->setAbandoned($abandoned); + $expectedResponse->setSkaffoldConfigUri($skaffoldConfigUri); + $expectedResponse->setSkaffoldConfigPath($skaffoldConfigPath); + $expectedResponse->setEtag($etag); + $expectedResponse->setSkaffoldVersion($skaffoldVersion); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createReleaseTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->deliveryPipelineName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]'); + $releaseId = 'releaseId-1517127597'; + $release = new Release(); + $request = (new CreateReleaseRequest()) + ->setParent($formattedParent) + ->setReleaseId($releaseId) + ->setRelease($release); + $response = $gapicClient->createRelease($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/CreateRelease', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getReleaseId(); + $this->assertProtobufEquals($releaseId, $actualValue); + $actualValue = $actualApiRequestObject->getRelease(); + $this->assertProtobufEquals($release, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createReleaseTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createReleaseExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createReleaseTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->deliveryPipelineName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]'); + $releaseId = 'releaseId-1517127597'; + $release = new Release(); + $request = (new CreateReleaseRequest()) + ->setParent($formattedParent) + ->setReleaseId($releaseId) + ->setRelease($release); + $response = $gapicClient->createRelease($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createReleaseTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createRolloutTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createRolloutTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $uid = 'uid115792'; + $description = 'description-1724546052'; + $targetId = 'targetId-815576439'; + $failureReason = 'failureReason1743941273'; + $deployingBuild = 'deployingBuild931623626'; + $etag = 'etag3123477'; + $controllerRollout = 'controllerRollout-146558962'; + $expectedResponse = new Rollout(); + $expectedResponse->setName($name); + $expectedResponse->setUid($uid); + $expectedResponse->setDescription($description); + $expectedResponse->setTargetId($targetId); + $expectedResponse->setFailureReason($failureReason); + $expectedResponse->setDeployingBuild($deployingBuild); + $expectedResponse->setEtag($etag); + $expectedResponse->setControllerRollout($controllerRollout); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createRolloutTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->releaseName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]'); + $rolloutId = 'rolloutId-91142551'; + $rollout = new Rollout(); + $rolloutTargetId = 'rolloutTargetId509050717'; + $rollout->setTargetId($rolloutTargetId); + $request = (new CreateRolloutRequest()) + ->setParent($formattedParent) + ->setRolloutId($rolloutId) + ->setRollout($rollout); + $response = $gapicClient->createRollout($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/CreateRollout', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getRolloutId(); + $this->assertProtobufEquals($rolloutId, $actualValue); + $actualValue = $actualApiRequestObject->getRollout(); + $this->assertProtobufEquals($rollout, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createRolloutTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createRolloutExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createRolloutTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->releaseName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]'); + $rolloutId = 'rolloutId-91142551'; + $rollout = new Rollout(); + $rolloutTargetId = 'rolloutTargetId509050717'; + $rollout->setTargetId($rolloutTargetId); + $request = (new CreateRolloutRequest()) + ->setParent($formattedParent) + ->setRolloutId($rolloutId) + ->setRollout($rollout); + $response = $gapicClient->createRollout($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createRolloutTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createTargetTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createTargetTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $targetId2 = 'targetId2-2084907012'; + $uid = 'uid115792'; + $description = 'description-1724546052'; + $requireApproval = false; + $etag = 'etag3123477'; + $expectedResponse = new Target(); + $expectedResponse->setName($name); + $expectedResponse->setTargetId($targetId2); + $expectedResponse->setUid($uid); + $expectedResponse->setDescription($description); + $expectedResponse->setRequireApproval($requireApproval); + $expectedResponse->setEtag($etag); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createTargetTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $targetId = 'targetId-815576439'; + $target = new Target(); + $request = (new CreateTargetRequest()) + ->setParent($formattedParent) + ->setTargetId($targetId) + ->setTarget($target); + $response = $gapicClient->createTarget($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/CreateTarget', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getTargetId(); + $this->assertProtobufEquals($targetId, $actualValue); + $actualValue = $actualApiRequestObject->getTarget(); + $this->assertProtobufEquals($target, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createTargetTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createTargetExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createTargetTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $targetId = 'targetId-815576439'; + $target = new Target(); + $request = (new CreateTargetRequest()) + ->setParent($formattedParent) + ->setTargetId($targetId) + ->setTarget($target); + $response = $gapicClient->createTarget($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createTargetTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteDeliveryPipelineTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteDeliveryPipelineTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new GPBEmpty(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/deleteDeliveryPipelineTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedName = $gapicClient->deliveryPipelineName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]'); + $request = (new DeleteDeliveryPipelineRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteDeliveryPipeline($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/DeleteDeliveryPipeline', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteDeliveryPipelineTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteDeliveryPipelineExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteDeliveryPipelineTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->deliveryPipelineName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]'); + $request = (new DeleteDeliveryPipelineRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteDeliveryPipeline($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteDeliveryPipelineTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteTargetTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteTargetTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new GPBEmpty(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/deleteTargetTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedName = $gapicClient->targetName('[PROJECT]', '[LOCATION]', '[TARGET]'); + $request = (new DeleteTargetRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteTarget($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/DeleteTarget', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteTargetTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteTargetExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteTargetTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->targetName('[PROJECT]', '[LOCATION]', '[TARGET]'); + $request = (new DeleteTargetRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteTarget($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteTargetTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function getConfigTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $defaultSkaffoldVersion = 'defaultSkaffoldVersion1930298837'; + $expectedResponse = new Config(); + $expectedResponse->setName($name2); + $expectedResponse->setDefaultSkaffoldVersion($defaultSkaffoldVersion); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->configName('[PROJECT]', '[LOCATION]'); + $request = (new GetConfigRequest()) + ->setName($formattedName); + $response = $gapicClient->getConfig($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/GetConfig', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getConfigExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->configName('[PROJECT]', '[LOCATION]'); + $request = (new GetConfigRequest()) + ->setName($formattedName); + try { + $gapicClient->getConfig($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getDeliveryPipelineTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $uid = 'uid115792'; + $description = 'description-1724546052'; + $etag = 'etag3123477'; + $suspended = false; + $expectedResponse = new DeliveryPipeline(); + $expectedResponse->setName($name2); + $expectedResponse->setUid($uid); + $expectedResponse->setDescription($description); + $expectedResponse->setEtag($etag); + $expectedResponse->setSuspended($suspended); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->deliveryPipelineName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]'); + $request = (new GetDeliveryPipelineRequest()) + ->setName($formattedName); + $response = $gapicClient->getDeliveryPipeline($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/GetDeliveryPipeline', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getDeliveryPipelineExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->deliveryPipelineName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]'); + $request = (new GetDeliveryPipelineRequest()) + ->setName($formattedName); + try { + $gapicClient->getDeliveryPipeline($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getJobRunTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $uid = 'uid115792'; + $phaseId = 'phaseId-1676299681'; + $jobId = 'jobId-1154752291'; + $etag = 'etag3123477'; + $expectedResponse = new JobRun(); + $expectedResponse->setName($name2); + $expectedResponse->setUid($uid); + $expectedResponse->setPhaseId($phaseId); + $expectedResponse->setJobId($jobId); + $expectedResponse->setEtag($etag); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->jobRunName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]', '[ROLLOUT]', '[JOB_RUN]'); + $request = (new GetJobRunRequest()) + ->setName($formattedName); + $response = $gapicClient->getJobRun($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/GetJobRun', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getJobRunExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->jobRunName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]', '[ROLLOUT]', '[JOB_RUN]'); + $request = (new GetJobRunRequest()) + ->setName($formattedName); + try { + $gapicClient->getJobRun($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getReleaseTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $uid = 'uid115792'; + $description = 'description-1724546052'; + $abandoned = true; + $skaffoldConfigUri = 'skaffoldConfigUri-860592176'; + $skaffoldConfigPath = 'skaffoldConfigPath-908718527'; + $etag = 'etag3123477'; + $skaffoldVersion = 'skaffoldVersion-1146663017'; + $expectedResponse = new Release(); + $expectedResponse->setName($name2); + $expectedResponse->setUid($uid); + $expectedResponse->setDescription($description); + $expectedResponse->setAbandoned($abandoned); + $expectedResponse->setSkaffoldConfigUri($skaffoldConfigUri); + $expectedResponse->setSkaffoldConfigPath($skaffoldConfigPath); + $expectedResponse->setEtag($etag); + $expectedResponse->setSkaffoldVersion($skaffoldVersion); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->releaseName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]'); + $request = (new GetReleaseRequest()) + ->setName($formattedName); + $response = $gapicClient->getRelease($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/GetRelease', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getReleaseExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->releaseName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]'); + $request = (new GetReleaseRequest()) + ->setName($formattedName); + try { + $gapicClient->getRelease($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getRolloutTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $uid = 'uid115792'; + $description = 'description-1724546052'; + $targetId = 'targetId-815576439'; + $failureReason = 'failureReason1743941273'; + $deployingBuild = 'deployingBuild931623626'; + $etag = 'etag3123477'; + $controllerRollout = 'controllerRollout-146558962'; + $expectedResponse = new Rollout(); + $expectedResponse->setName($name2); + $expectedResponse->setUid($uid); + $expectedResponse->setDescription($description); + $expectedResponse->setTargetId($targetId); + $expectedResponse->setFailureReason($failureReason); + $expectedResponse->setDeployingBuild($deployingBuild); + $expectedResponse->setEtag($etag); + $expectedResponse->setControllerRollout($controllerRollout); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->rolloutName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]', '[ROLLOUT]'); + $request = (new GetRolloutRequest()) + ->setName($formattedName); + $response = $gapicClient->getRollout($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/GetRollout', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getRolloutExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->rolloutName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]', '[ROLLOUT]'); + $request = (new GetRolloutRequest()) + ->setName($formattedName); + try { + $gapicClient->getRollout($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getTargetTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $targetId = 'targetId-815576439'; + $uid = 'uid115792'; + $description = 'description-1724546052'; + $requireApproval = false; + $etag = 'etag3123477'; + $expectedResponse = new Target(); + $expectedResponse->setName($name2); + $expectedResponse->setTargetId($targetId); + $expectedResponse->setUid($uid); + $expectedResponse->setDescription($description); + $expectedResponse->setRequireApproval($requireApproval); + $expectedResponse->setEtag($etag); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->targetName('[PROJECT]', '[LOCATION]', '[TARGET]'); + $request = (new GetTargetRequest()) + ->setName($formattedName); + $response = $gapicClient->getTarget($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/GetTarget', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getTargetExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->targetName('[PROJECT]', '[LOCATION]', '[TARGET]'); + $request = (new GetTargetRequest()) + ->setName($formattedName); + try { + $gapicClient->getTarget($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function ignoreJobTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new IgnoreJobResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedRollout = $gapicClient->rolloutName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]', '[ROLLOUT]'); + $phaseId = 'phaseId-1676299681'; + $jobId = 'jobId-1154752291'; + $request = (new IgnoreJobRequest()) + ->setRollout($formattedRollout) + ->setPhaseId($phaseId) + ->setJobId($jobId); + $response = $gapicClient->ignoreJob($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/IgnoreJob', $actualFuncCall); + $actualValue = $actualRequestObject->getRollout(); + $this->assertProtobufEquals($formattedRollout, $actualValue); + $actualValue = $actualRequestObject->getPhaseId(); + $this->assertProtobufEquals($phaseId, $actualValue); + $actualValue = $actualRequestObject->getJobId(); + $this->assertProtobufEquals($jobId, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function ignoreJobExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedRollout = $gapicClient->rolloutName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]', '[ROLLOUT]'); + $phaseId = 'phaseId-1676299681'; + $jobId = 'jobId-1154752291'; + $request = (new IgnoreJobRequest()) + ->setRollout($formattedRollout) + ->setPhaseId($phaseId) + ->setJobId($jobId); + try { + $gapicClient->ignoreJob($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listDeliveryPipelinesTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $deliveryPipelinesElement = new DeliveryPipeline(); + $deliveryPipelines = [ + $deliveryPipelinesElement, + ]; + $expectedResponse = new ListDeliveryPipelinesResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setDeliveryPipelines($deliveryPipelines); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListDeliveryPipelinesRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listDeliveryPipelines($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getDeliveryPipelines()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/ListDeliveryPipelines', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listDeliveryPipelinesExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListDeliveryPipelinesRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listDeliveryPipelines($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listJobRunsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $jobRunsElement = new JobRun(); + $jobRuns = [ + $jobRunsElement, + ]; + $expectedResponse = new ListJobRunsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setJobRuns($jobRuns); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->rolloutName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]', '[ROLLOUT]'); + $request = (new ListJobRunsRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listJobRuns($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getJobRuns()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/ListJobRuns', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listJobRunsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->rolloutName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]', '[ROLLOUT]'); + $request = (new ListJobRunsRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listJobRuns($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listReleasesTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $releasesElement = new Release(); + $releases = [ + $releasesElement, + ]; + $expectedResponse = new ListReleasesResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setReleases($releases); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->deliveryPipelineName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]'); + $request = (new ListReleasesRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listReleases($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getReleases()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/ListReleases', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listReleasesExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->deliveryPipelineName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]'); + $request = (new ListReleasesRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listReleases($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listRolloutsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $rolloutsElement = new Rollout(); + $rollouts = [ + $rolloutsElement, + ]; + $expectedResponse = new ListRolloutsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setRollouts($rollouts); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->releaseName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]'); + $request = (new ListRolloutsRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listRollouts($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getRollouts()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/ListRollouts', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listRolloutsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->releaseName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]'); + $request = (new ListRolloutsRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listRollouts($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listTargetsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $targetsElement = new Target(); + $targets = [ + $targetsElement, + ]; + $expectedResponse = new ListTargetsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setTargets($targets); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListTargetsRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listTargets($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getTargets()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/ListTargets', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listTargetsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListTargetsRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listTargets($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function retryJobTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new RetryJobResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedRollout = $gapicClient->rolloutName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]', '[ROLLOUT]'); + $phaseId = 'phaseId-1676299681'; + $jobId = 'jobId-1154752291'; + $request = (new RetryJobRequest()) + ->setRollout($formattedRollout) + ->setPhaseId($phaseId) + ->setJobId($jobId); + $response = $gapicClient->retryJob($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/RetryJob', $actualFuncCall); + $actualValue = $actualRequestObject->getRollout(); + $this->assertProtobufEquals($formattedRollout, $actualValue); + $actualValue = $actualRequestObject->getPhaseId(); + $this->assertProtobufEquals($phaseId, $actualValue); + $actualValue = $actualRequestObject->getJobId(); + $this->assertProtobufEquals($jobId, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function retryJobExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedRollout = $gapicClient->rolloutName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]', '[ROLLOUT]'); + $phaseId = 'phaseId-1676299681'; + $jobId = 'jobId-1154752291'; + $request = (new RetryJobRequest()) + ->setRollout($formattedRollout) + ->setPhaseId($phaseId) + ->setJobId($jobId); + try { + $gapicClient->retryJob($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function terminateJobRunTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new TerminateJobRunResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->jobRunName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]', '[ROLLOUT]', '[JOB_RUN]'); + $request = (new TerminateJobRunRequest()) + ->setName($formattedName); + $response = $gapicClient->terminateJobRun($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/TerminateJobRun', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function terminateJobRunExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->jobRunName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]', '[ROLLOUT]', '[JOB_RUN]'); + $request = (new TerminateJobRunRequest()) + ->setName($formattedName); + try { + $gapicClient->terminateJobRun($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function updateDeliveryPipelineTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateDeliveryPipelineTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $uid = 'uid115792'; + $description = 'description-1724546052'; + $etag = 'etag3123477'; + $suspended = false; + $expectedResponse = new DeliveryPipeline(); + $expectedResponse->setName($name); + $expectedResponse->setUid($uid); + $expectedResponse->setDescription($description); + $expectedResponse->setEtag($etag); + $expectedResponse->setSuspended($suspended); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/updateDeliveryPipelineTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $updateMask = new FieldMask(); + $deliveryPipeline = new DeliveryPipeline(); + $request = (new UpdateDeliveryPipelineRequest()) + ->setUpdateMask($updateMask) + ->setDeliveryPipeline($deliveryPipeline); + $response = $gapicClient->updateDeliveryPipeline($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/UpdateDeliveryPipeline', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getUpdateMask(); + $this->assertProtobufEquals($updateMask, $actualValue); + $actualValue = $actualApiRequestObject->getDeliveryPipeline(); + $this->assertProtobufEquals($deliveryPipeline, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateDeliveryPipelineTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateDeliveryPipelineExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateDeliveryPipelineTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $updateMask = new FieldMask(); + $deliveryPipeline = new DeliveryPipeline(); + $request = (new UpdateDeliveryPipelineRequest()) + ->setUpdateMask($updateMask) + ->setDeliveryPipeline($deliveryPipeline); + $response = $gapicClient->updateDeliveryPipeline($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateDeliveryPipelineTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateTargetTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateTargetTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $targetId = 'targetId-815576439'; + $uid = 'uid115792'; + $description = 'description-1724546052'; + $requireApproval = false; + $etag = 'etag3123477'; + $expectedResponse = new Target(); + $expectedResponse->setName($name); + $expectedResponse->setTargetId($targetId); + $expectedResponse->setUid($uid); + $expectedResponse->setDescription($description); + $expectedResponse->setRequireApproval($requireApproval); + $expectedResponse->setEtag($etag); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/updateTargetTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $updateMask = new FieldMask(); + $target = new Target(); + $request = (new UpdateTargetRequest()) + ->setUpdateMask($updateMask) + ->setTarget($target); + $response = $gapicClient->updateTarget($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/UpdateTarget', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getUpdateMask(); + $this->assertProtobufEquals($updateMask, $actualValue); + $actualValue = $actualApiRequestObject->getTarget(); + $this->assertProtobufEquals($target, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateTargetTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateTargetExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateTargetTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $updateMask = new FieldMask(); + $target = new Target(); + $request = (new UpdateTargetRequest()) + ->setUpdateMask($updateMask) + ->setTarget($target); + $response = $gapicClient->updateTarget($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateTargetTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function getLocationTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $locationId = 'locationId552319461'; + $displayName = 'displayName1615086568'; + $expectedResponse = new Location(); + $expectedResponse->setName($name2); + $expectedResponse->setLocationId($locationId); + $expectedResponse->setDisplayName($displayName); + $transport->addResponse($expectedResponse); + $request = new GetLocationRequest(); + $response = $gapicClient->getLocation($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.location.Locations/GetLocation', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getLocationExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + $request = new GetLocationRequest(); + try { + $gapicClient->getLocation($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listLocationsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $locationsElement = new Location(); + $locations = [ + $locationsElement, + ]; + $expectedResponse = new ListLocationsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setLocations($locations); + $transport->addResponse($expectedResponse); + $request = new ListLocationsRequest(); + $response = $gapicClient->listLocations($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getLocations()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.location.Locations/ListLocations', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listLocationsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + $request = new ListLocationsRequest(); + try { + $gapicClient->listLocations($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getIamPolicyTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $version = 351608024; + $etag = '21'; + $expectedResponse = new Policy(); + $expectedResponse->setVersion($version); + $expectedResponse->setEtag($etag); + $transport->addResponse($expectedResponse); + // Mock request + $resource = 'resource-341064690'; + $request = (new GetIamPolicyRequest()) + ->setResource($resource); + $response = $gapicClient->getIamPolicy($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.iam.v1.IAMPolicy/GetIamPolicy', $actualFuncCall); + $actualValue = $actualRequestObject->getResource(); + $this->assertProtobufEquals($resource, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getIamPolicyExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $resource = 'resource-341064690'; + $request = (new GetIamPolicyRequest()) + ->setResource($resource); + try { + $gapicClient->getIamPolicy($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function setIamPolicyTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $version = 351608024; + $etag = '21'; + $expectedResponse = new Policy(); + $expectedResponse->setVersion($version); + $expectedResponse->setEtag($etag); + $transport->addResponse($expectedResponse); + // Mock request + $resource = 'resource-341064690'; + $policy = new Policy(); + $request = (new SetIamPolicyRequest()) + ->setResource($resource) + ->setPolicy($policy); + $response = $gapicClient->setIamPolicy($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.iam.v1.IAMPolicy/SetIamPolicy', $actualFuncCall); + $actualValue = $actualRequestObject->getResource(); + $this->assertProtobufEquals($resource, $actualValue); + $actualValue = $actualRequestObject->getPolicy(); + $this->assertProtobufEquals($policy, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function setIamPolicyExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $resource = 'resource-341064690'; + $policy = new Policy(); + $request = (new SetIamPolicyRequest()) + ->setResource($resource) + ->setPolicy($policy); + try { + $gapicClient->setIamPolicy($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function testIamPermissionsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new TestIamPermissionsResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $resource = 'resource-341064690'; + $permissions = []; + $request = (new TestIamPermissionsRequest()) + ->setResource($resource) + ->setPermissions($permissions); + $response = $gapicClient->testIamPermissions($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.iam.v1.IAMPolicy/TestIamPermissions', $actualFuncCall); + $actualValue = $actualRequestObject->getResource(); + $this->assertProtobufEquals($resource, $actualValue); + $actualValue = $actualRequestObject->getPermissions(); + $this->assertProtobufEquals($permissions, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function testIamPermissionsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $resource = 'resource-341064690'; + $permissions = []; + $request = (new TestIamPermissionsRequest()) + ->setResource($resource) + ->setPermissions($permissions); + try { + $gapicClient->testIamPermissions($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function abandonReleaseAsyncTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new AbandonReleaseResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->releaseName('[PROJECT]', '[LOCATION]', '[DELIVERY_PIPELINE]', '[RELEASE]'); + $request = (new AbandonReleaseRequest()) + ->setName($formattedName); + $response = $gapicClient->abandonReleaseAsync($request)->wait(); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.deploy.v1.CloudDeploy/AbandonRelease', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } +} diff --git a/ErrorReporting/samples/V1beta1/ErrorGroupServiceClient/get_group.php b/ErrorReporting/samples/V1beta1/ErrorGroupServiceClient/get_group.php index 87597c347c40..71cc0ecb3eef 100644 --- a/ErrorReporting/samples/V1beta1/ErrorGroupServiceClient/get_group.php +++ b/ErrorReporting/samples/V1beta1/ErrorGroupServiceClient/get_group.php @@ -24,8 +24,9 @@ // [START clouderrorreporting_v1beta1_generated_ErrorGroupService_GetGroup_sync] use Google\ApiCore\ApiException; +use Google\Cloud\ErrorReporting\V1beta1\Client\ErrorGroupServiceClient; use Google\Cloud\ErrorReporting\V1beta1\ErrorGroup; -use Google\Cloud\ErrorReporting\V1beta1\ErrorGroupServiceClient; +use Google\Cloud\ErrorReporting\V1beta1\GetGroupRequest; /** * Get the specified group. @@ -43,10 +44,14 @@ function get_group_sample(string $formattedGroupName): void // Create a client. $errorGroupServiceClient = new ErrorGroupServiceClient(); + // Prepare the request message. + $request = (new GetGroupRequest()) + ->setGroupName($formattedGroupName); + // Call the API and handle any network failures. try { /** @var ErrorGroup $response */ - $response = $errorGroupServiceClient->getGroup($formattedGroupName); + $response = $errorGroupServiceClient->getGroup($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/ErrorReporting/samples/V1beta1/ErrorGroupServiceClient/update_group.php b/ErrorReporting/samples/V1beta1/ErrorGroupServiceClient/update_group.php index 7f8b324e0574..6ad45223fb9d 100644 --- a/ErrorReporting/samples/V1beta1/ErrorGroupServiceClient/update_group.php +++ b/ErrorReporting/samples/V1beta1/ErrorGroupServiceClient/update_group.php @@ -24,8 +24,9 @@ // [START clouderrorreporting_v1beta1_generated_ErrorGroupService_UpdateGroup_sync] use Google\ApiCore\ApiException; +use Google\Cloud\ErrorReporting\V1beta1\Client\ErrorGroupServiceClient; use Google\Cloud\ErrorReporting\V1beta1\ErrorGroup; -use Google\Cloud\ErrorReporting\V1beta1\ErrorGroupServiceClient; +use Google\Cloud\ErrorReporting\V1beta1\UpdateGroupRequest; /** * Replace the data for the specified group. @@ -42,13 +43,15 @@ function update_group_sample(): void // Create a client. $errorGroupServiceClient = new ErrorGroupServiceClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $group = new ErrorGroup(); + $request = (new UpdateGroupRequest()) + ->setGroup($group); // Call the API and handle any network failures. try { /** @var ErrorGroup $response */ - $response = $errorGroupServiceClient->updateGroup($group); + $response = $errorGroupServiceClient->updateGroup($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/ErrorReporting/samples/V1beta1/ErrorStatsServiceClient/delete_events.php b/ErrorReporting/samples/V1beta1/ErrorStatsServiceClient/delete_events.php index d78400961645..8afdcbf6b225 100644 --- a/ErrorReporting/samples/V1beta1/ErrorStatsServiceClient/delete_events.php +++ b/ErrorReporting/samples/V1beta1/ErrorStatsServiceClient/delete_events.php @@ -24,8 +24,9 @@ // [START clouderrorreporting_v1beta1_generated_ErrorStatsService_DeleteEvents_sync] use Google\ApiCore\ApiException; +use Google\Cloud\ErrorReporting\V1beta1\Client\ErrorStatsServiceClient; +use Google\Cloud\ErrorReporting\V1beta1\DeleteEventsRequest; use Google\Cloud\ErrorReporting\V1beta1\DeleteEventsResponse; -use Google\Cloud\ErrorReporting\V1beta1\ErrorStatsServiceClient; /** * Deletes all error events of a given project. @@ -43,10 +44,14 @@ function delete_events_sample(string $formattedProjectName): void // Create a client. $errorStatsServiceClient = new ErrorStatsServiceClient(); + // Prepare the request message. + $request = (new DeleteEventsRequest()) + ->setProjectName($formattedProjectName); + // Call the API and handle any network failures. try { /** @var DeleteEventsResponse $response */ - $response = $errorStatsServiceClient->deleteEvents($formattedProjectName); + $response = $errorStatsServiceClient->deleteEvents($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/ErrorReporting/samples/V1beta1/ErrorStatsServiceClient/list_events.php b/ErrorReporting/samples/V1beta1/ErrorStatsServiceClient/list_events.php index 3a3e86e685a1..c3c4aea1d82b 100644 --- a/ErrorReporting/samples/V1beta1/ErrorStatsServiceClient/list_events.php +++ b/ErrorReporting/samples/V1beta1/ErrorStatsServiceClient/list_events.php @@ -25,8 +25,9 @@ // [START clouderrorreporting_v1beta1_generated_ErrorStatsService_ListEvents_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; +use Google\Cloud\ErrorReporting\V1beta1\Client\ErrorStatsServiceClient; use Google\Cloud\ErrorReporting\V1beta1\ErrorEvent; -use Google\Cloud\ErrorReporting\V1beta1\ErrorStatsServiceClient; +use Google\Cloud\ErrorReporting\V1beta1\ListEventsRequest; /** * Lists the specified events. @@ -45,10 +46,15 @@ function list_events_sample(string $formattedProjectName, string $groupId): void // Create a client. $errorStatsServiceClient = new ErrorStatsServiceClient(); + // Prepare the request message. + $request = (new ListEventsRequest()) + ->setProjectName($formattedProjectName) + ->setGroupId($groupId); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $errorStatsServiceClient->listEvents($formattedProjectName, $groupId); + $response = $errorStatsServiceClient->listEvents($request); /** @var ErrorEvent $element */ foreach ($response as $element) { diff --git a/ErrorReporting/samples/V1beta1/ErrorStatsServiceClient/list_group_stats.php b/ErrorReporting/samples/V1beta1/ErrorStatsServiceClient/list_group_stats.php index 594207ada5c3..7fce90df496e 100644 --- a/ErrorReporting/samples/V1beta1/ErrorStatsServiceClient/list_group_stats.php +++ b/ErrorReporting/samples/V1beta1/ErrorStatsServiceClient/list_group_stats.php @@ -25,8 +25,9 @@ // [START clouderrorreporting_v1beta1_generated_ErrorStatsService_ListGroupStats_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; +use Google\Cloud\ErrorReporting\V1beta1\Client\ErrorStatsServiceClient; use Google\Cloud\ErrorReporting\V1beta1\ErrorGroupStats; -use Google\Cloud\ErrorReporting\V1beta1\ErrorStatsServiceClient; +use Google\Cloud\ErrorReporting\V1beta1\ListGroupStatsRequest; /** * Lists the specified groups. @@ -44,10 +45,14 @@ function list_group_stats_sample(string $formattedProjectName): void // Create a client. $errorStatsServiceClient = new ErrorStatsServiceClient(); + // Prepare the request message. + $request = (new ListGroupStatsRequest()) + ->setProjectName($formattedProjectName); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $errorStatsServiceClient->listGroupStats($formattedProjectName); + $response = $errorStatsServiceClient->listGroupStats($request); /** @var ErrorGroupStats $element */ foreach ($response as $element) { diff --git a/ErrorReporting/samples/V1beta1/ReportErrorsServiceClient/report_error_event.php b/ErrorReporting/samples/V1beta1/ReportErrorsServiceClient/report_error_event.php index 181561dbd254..6dff658d3f28 100644 --- a/ErrorReporting/samples/V1beta1/ReportErrorsServiceClient/report_error_event.php +++ b/ErrorReporting/samples/V1beta1/ReportErrorsServiceClient/report_error_event.php @@ -24,8 +24,9 @@ // [START clouderrorreporting_v1beta1_generated_ReportErrorsService_ReportErrorEvent_sync] use Google\ApiCore\ApiException; +use Google\Cloud\ErrorReporting\V1beta1\Client\ReportErrorsServiceClient; +use Google\Cloud\ErrorReporting\V1beta1\ReportErrorEventRequest; use Google\Cloud\ErrorReporting\V1beta1\ReportErrorEventResponse; -use Google\Cloud\ErrorReporting\V1beta1\ReportErrorsServiceClient; use Google\Cloud\ErrorReporting\V1beta1\ReportedErrorEvent; use Google\Cloud\ErrorReporting\V1beta1\ServiceContext; @@ -82,16 +83,19 @@ function report_error_event_sample(string $formattedProjectName, string $eventMe // Create a client. $reportErrorsServiceClient = new ReportErrorsServiceClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $eventServiceContext = new ServiceContext(); $event = (new ReportedErrorEvent()) ->setServiceContext($eventServiceContext) ->setMessage($eventMessage); + $request = (new ReportErrorEventRequest()) + ->setProjectName($formattedProjectName) + ->setEvent($event); // Call the API and handle any network failures. try { /** @var ReportErrorEventResponse $response */ - $response = $reportErrorsServiceClient->reportErrorEvent($formattedProjectName, $event); + $response = $reportErrorsServiceClient->reportErrorEvent($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/ErrorReporting/src/V1beta1/Client/BaseClient/ErrorGroupServiceBaseClient.php b/ErrorReporting/src/V1beta1/Client/BaseClient/ErrorGroupServiceBaseClient.php new file mode 100644 index 000000000000..eecc468f9a64 --- /dev/null +++ b/ErrorReporting/src/V1beta1/Client/BaseClient/ErrorGroupServiceBaseClient.php @@ -0,0 +1,273 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/error_group_service_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/error_group_service_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/error_group_service_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/error_group_service_rest_client_config.php', + ], + ], + ]; + } + + /** + * Formats a string containing the fully-qualified path to represent a error_group + * resource. + * + * @param string $project + * @param string $group + * + * @return string The formatted error_group resource. + * + * @experimental + */ + public static function errorGroupName(string $project, string $group): string + { + return self::getPathTemplate('errorGroup')->render([ + 'project' => $project, + 'group' => $group, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - errorGroup: projects/{project}/groups/{group} + * + * The optional $template argument can be supplied to specify a particular pattern, + * and must match one of the templates listed above. If no $template argument is + * provided, or if the $template argument does not match one of the templates + * listed, then parseName will check each of the supported templates, and return + * the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + * + * @experimental + */ + public static function parseName(string $formattedName, string $template = null): array + { + return self::parseFormattedName($formattedName, $template); + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'clouderrorreporting.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + * + * @experimental + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Get the specified group. + * + * The async variant is {@see self::getGroupAsync()} . + * + * @param GetGroupRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return ErrorGroup + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function getGroup(GetGroupRequest $request, array $callOptions = []): ErrorGroup + { + return $this->startApiCall('GetGroup', $request, $callOptions)->wait(); + } + + /** + * Replace the data for the specified group. + * Fails if the group does not exist. + * + * The async variant is {@see self::updateGroupAsync()} . + * + * @param UpdateGroupRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return ErrorGroup + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function updateGroup(UpdateGroupRequest $request, array $callOptions = []): ErrorGroup + { + return $this->startApiCall('UpdateGroup', $request, $callOptions)->wait(); + } +} diff --git a/ErrorReporting/src/V1beta1/Client/BaseClient/ErrorStatsServiceBaseClient.php b/ErrorReporting/src/V1beta1/Client/BaseClient/ErrorStatsServiceBaseClient.php new file mode 100644 index 000000000000..ae0b329b01a7 --- /dev/null +++ b/ErrorReporting/src/V1beta1/Client/BaseClient/ErrorStatsServiceBaseClient.php @@ -0,0 +1,300 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/error_stats_service_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/error_stats_service_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/error_stats_service_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/error_stats_service_rest_client_config.php', + ], + ], + ]; + } + + /** + * Formats a string containing the fully-qualified path to represent a project + * resource. + * + * @param string $project + * + * @return string The formatted project resource. + * + * @experimental + */ + public static function projectName(string $project): string + { + return self::getPathTemplate('project')->render([ + 'project' => $project, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - project: projects/{project} + * + * The optional $template argument can be supplied to specify a particular pattern, + * and must match one of the templates listed above. If no $template argument is + * provided, or if the $template argument does not match one of the templates + * listed, then parseName will check each of the supported templates, and return + * the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + * + * @experimental + */ + public static function parseName(string $formattedName, string $template = null): array + { + return self::parseFormattedName($formattedName, $template); + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'clouderrorreporting.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + * + * @experimental + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Deletes all error events of a given project. + * + * The async variant is {@see self::deleteEventsAsync()} . + * + * @param DeleteEventsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return DeleteEventsResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function deleteEvents(DeleteEventsRequest $request, array $callOptions = []): DeleteEventsResponse + { + return $this->startApiCall('DeleteEvents', $request, $callOptions)->wait(); + } + + /** + * Lists the specified events. + * + * The async variant is {@see self::listEventsAsync()} . + * + * @param ListEventsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function listEvents(ListEventsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListEvents', $request, $callOptions); + } + + /** + * Lists the specified groups. + * + * The async variant is {@see self::listGroupStatsAsync()} . + * + * @param ListGroupStatsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function listGroupStats(ListGroupStatsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListGroupStats', $request, $callOptions); + } +} diff --git a/ErrorReporting/src/V1beta1/Client/BaseClient/ReportErrorsServiceBaseClient.php b/ErrorReporting/src/V1beta1/Client/BaseClient/ReportErrorsServiceBaseClient.php new file mode 100644 index 000000000000..30e07b883eed --- /dev/null +++ b/ErrorReporting/src/V1beta1/Client/BaseClient/ReportErrorsServiceBaseClient.php @@ -0,0 +1,255 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/report_errors_service_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/report_errors_service_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/report_errors_service_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/report_errors_service_rest_client_config.php', + ], + ], + ]; + } + + /** + * Formats a string containing the fully-qualified path to represent a project + * resource. + * + * @param string $project + * + * @return string The formatted project resource. + * + * @experimental + */ + public static function projectName(string $project): string + { + return self::getPathTemplate('project')->render([ + 'project' => $project, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - project: projects/{project} + * + * The optional $template argument can be supplied to specify a particular pattern, + * and must match one of the templates listed above. If no $template argument is + * provided, or if the $template argument does not match one of the templates + * listed, then parseName will check each of the supported templates, and return + * the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + * + * @experimental + */ + public static function parseName(string $formattedName, string $template = null): array + { + return self::parseFormattedName($formattedName, $template); + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'clouderrorreporting.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + * + * @experimental + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Report an individual error event and record the event to a log. + * + * This endpoint accepts **either** an OAuth token, + * **or** an [API key](https://support.google.com/cloud/answer/6158862) + * for authentication. To use an API key, append it to the URL as the value of + * a `key` parameter. For example: + * + * `POST + * https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456` + * + * **Note:** [Error Reporting](https://cloud.google.com/error-reporting) is a global service built + * on Cloud Logging and doesn't analyze logs stored + * in regional log buckets or logs routed to other Google Cloud projects. + * + * + * The async variant is {@see self::reportErrorEventAsync()} . + * + * @param ReportErrorEventRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return ReportErrorEventResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function reportErrorEvent(ReportErrorEventRequest $request, array $callOptions = []): ReportErrorEventResponse + { + return $this->startApiCall('ReportErrorEvent', $request, $callOptions)->wait(); + } +} diff --git a/ErrorReporting/src/V1beta1/Client/ErrorGroupServiceClient.php b/ErrorReporting/src/V1beta1/Client/ErrorGroupServiceClient.php new file mode 100644 index 000000000000..26ac1a62d22d --- /dev/null +++ b/ErrorReporting/src/V1beta1/Client/ErrorGroupServiceClient.php @@ -0,0 +1,42 @@ +setProjectName($projectName); + } + /** * Constructor. * diff --git a/ErrorReporting/src/V1beta1/GetGroupRequest.php b/ErrorReporting/src/V1beta1/GetGroupRequest.php index ff1cd7cd9f32..14109db9ce7f 100644 --- a/ErrorReporting/src/V1beta1/GetGroupRequest.php +++ b/ErrorReporting/src/V1beta1/GetGroupRequest.php @@ -26,6 +26,25 @@ class GetGroupRequest extends \Google\Protobuf\Internal\Message */ private $group_name = ''; + /** + * @param string $groupName Required. The group resource name. Written as + * `projects/{projectID}/groups/{group_name}`. Call + * [`groupStats.list`](https://cloud.google.com/error-reporting/reference/rest/v1beta1/projects.groupStats/list) + * to return a list of groups belonging to this project. + * + * Example: `projects/my-project-123/groups/my-group` + * Please see {@see ErrorGroupServiceClient::errorGroupName()} for help formatting this field. + * + * @return \Google\Cloud\ErrorReporting\V1beta1\GetGroupRequest + * + * @experimental + */ + public static function build(string $groupName): self + { + return (new self()) + ->setGroupName($groupName); + } + /** * Constructor. * diff --git a/ErrorReporting/src/V1beta1/ListEventsRequest.php b/ErrorReporting/src/V1beta1/ListEventsRequest.php index 8cfb0d4c9725..1c8398fdfac8 100644 --- a/ErrorReporting/src/V1beta1/ListEventsRequest.php +++ b/ErrorReporting/src/V1beta1/ListEventsRequest.php @@ -60,6 +60,27 @@ class ListEventsRequest extends \Google\Protobuf\Internal\Message */ private $page_token = ''; + /** + * @param string $projectName Required. The resource name of the Google Cloud Platform project. Written + * as `projects/{projectID}`, where `{projectID}` is the + * [Google Cloud Platform project + * ID](https://support.google.com/cloud/answer/6158840). + * + * Example: `projects/my-project-123`. Please see + * {@see ErrorStatsServiceClient::projectName()} for help formatting this field. + * @param string $groupId Required. The group for which events shall be returned. + * + * @return \Google\Cloud\ErrorReporting\V1beta1\ListEventsRequest + * + * @experimental + */ + public static function build(string $projectName, string $groupId): self + { + return (new self()) + ->setProjectName($projectName) + ->setGroupId($groupId); + } + /** * Constructor. * diff --git a/ErrorReporting/src/V1beta1/ListGroupStatsRequest.php b/ErrorReporting/src/V1beta1/ListGroupStatsRequest.php index 9e26c8c149a0..0a6b2f620052 100644 --- a/ErrorReporting/src/V1beta1/ListGroupStatsRequest.php +++ b/ErrorReporting/src/V1beta1/ListGroupStatsRequest.php @@ -96,6 +96,34 @@ class ListGroupStatsRequest extends \Google\Protobuf\Internal\Message */ private $page_token = ''; + /** + * @param string $projectName Required. The resource name of the Google Cloud Platform project. Written + * as `projects/{projectID}` or `projects/{projectNumber}`, where `{projectID}` + * and `{projectNumber}` can be found in the + * [Google Cloud Console](https://support.google.com/cloud/answer/6158840). + * + * Examples: `projects/my-project-123`, `projects/5551234`. Please see + * {@see ErrorStatsServiceClient::projectName()} for help formatting this field. + * @param \Google\Cloud\ErrorReporting\V1beta1\QueryTimeRange $timeRange Optional. List data for the given time range. + * If not set, a default time range is used. The field + * time_range_begin in the response will specify the beginning + * of this time range. + * Only ErrorGroupStats with a non-zero count in the given time + * range are returned, unless the request contains an explicit + * group_id list. If a group_id list is given, also + * ErrorGroupStats with zero occurrences are returned. + * + * @return \Google\Cloud\ErrorReporting\V1beta1\ListGroupStatsRequest + * + * @experimental + */ + public static function build(string $projectName, \Google\Cloud\ErrorReporting\V1beta1\QueryTimeRange $timeRange): self + { + return (new self()) + ->setProjectName($projectName) + ->setTimeRange($timeRange); + } + /** * Constructor. * diff --git a/ErrorReporting/src/V1beta1/ReportErrorEventRequest.php b/ErrorReporting/src/V1beta1/ReportErrorEventRequest.php index 8de6dc3a08f9..7946cf092f71 100644 --- a/ErrorReporting/src/V1beta1/ReportErrorEventRequest.php +++ b/ErrorReporting/src/V1beta1/ReportErrorEventRequest.php @@ -32,6 +32,27 @@ class ReportErrorEventRequest extends \Google\Protobuf\Internal\Message */ private $event = null; + /** + * @param string $projectName Required. The resource name of the Google Cloud Platform project. Written + * as `projects/{projectId}`, where `{projectId}` is the + * [Google Cloud Platform project + * ID](https://support.google.com/cloud/answer/6158840). + * + * Example: // `projects/my-project-123`. Please see + * {@see ReportErrorsServiceClient::projectName()} for help formatting this field. + * @param \Google\Cloud\ErrorReporting\V1beta1\ReportedErrorEvent $event Required. The error event to be reported. + * + * @return \Google\Cloud\ErrorReporting\V1beta1\ReportErrorEventRequest + * + * @experimental + */ + public static function build(string $projectName, \Google\Cloud\ErrorReporting\V1beta1\ReportedErrorEvent $event): self + { + return (new self()) + ->setProjectName($projectName) + ->setEvent($event); + } + /** * Constructor. * diff --git a/ErrorReporting/src/V1beta1/UpdateGroupRequest.php b/ErrorReporting/src/V1beta1/UpdateGroupRequest.php index 7863ea9d1138..0b6a32bbb71e 100644 --- a/ErrorReporting/src/V1beta1/UpdateGroupRequest.php +++ b/ErrorReporting/src/V1beta1/UpdateGroupRequest.php @@ -22,6 +22,19 @@ class UpdateGroupRequest extends \Google\Protobuf\Internal\Message */ private $group = null; + /** + * @param \Google\Cloud\ErrorReporting\V1beta1\ErrorGroup $group Required. The group which replaces the resource on the server. + * + * @return \Google\Cloud\ErrorReporting\V1beta1\UpdateGroupRequest + * + * @experimental + */ + public static function build(\Google\Cloud\ErrorReporting\V1beta1\ErrorGroup $group): self + { + return (new self()) + ->setGroup($group); + } + /** * Constructor. * diff --git a/ErrorReporting/src/V1beta1/resources/error_group_service_descriptor_config.php b/ErrorReporting/src/V1beta1/resources/error_group_service_descriptor_config.php index 2e9c68889066..97a6cb868f05 100644 --- a/ErrorReporting/src/V1beta1/resources/error_group_service_descriptor_config.php +++ b/ErrorReporting/src/V1beta1/resources/error_group_service_descriptor_config.php @@ -2,6 +2,35 @@ return [ 'interfaces' => [ - 'google.devtools.clouderrorreporting.v1beta1.ErrorGroupService' => [], + 'google.devtools.clouderrorreporting.v1beta1.ErrorGroupService' => [ + 'GetGroup' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\ErrorReporting\V1beta1\ErrorGroup', + 'headerParams' => [ + [ + 'keyName' => 'group_name', + 'fieldAccessors' => [ + 'getGroupName', + ], + ], + ], + ], + 'UpdateGroup' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\ErrorReporting\V1beta1\ErrorGroup', + 'headerParams' => [ + [ + 'keyName' => 'group.name', + 'fieldAccessors' => [ + 'getGroup', + 'getName', + ], + ], + ], + ], + 'templateMap' => [ + 'errorGroup' => 'projects/{project}/groups/{group}', + ], + ], ], ]; diff --git a/ErrorReporting/src/V1beta1/resources/error_stats_service_descriptor_config.php b/ErrorReporting/src/V1beta1/resources/error_stats_service_descriptor_config.php index 35148865a5eb..43712e675c86 100644 --- a/ErrorReporting/src/V1beta1/resources/error_stats_service_descriptor_config.php +++ b/ErrorReporting/src/V1beta1/resources/error_stats_service_descriptor_config.php @@ -3,6 +3,18 @@ return [ 'interfaces' => [ 'google.devtools.clouderrorreporting.v1beta1.ErrorStatsService' => [ + 'DeleteEvents' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\ErrorReporting\V1beta1\DeleteEventsResponse', + 'headerParams' => [ + [ + 'keyName' => 'project_name', + 'fieldAccessors' => [ + 'getProjectName', + ], + ], + ], + ], 'ListEvents' => [ 'pageStreaming' => [ 'requestPageTokenGetMethod' => 'getPageToken', @@ -12,6 +24,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getErrorEvents', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\ErrorReporting\V1beta1\ListEventsResponse', + 'headerParams' => [ + [ + 'keyName' => 'project_name', + 'fieldAccessors' => [ + 'getProjectName', + ], + ], + ], ], 'ListGroupStats' => [ 'pageStreaming' => [ @@ -22,6 +44,19 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getErrorGroupStats', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\ErrorReporting\V1beta1\ListGroupStatsResponse', + 'headerParams' => [ + [ + 'keyName' => 'project_name', + 'fieldAccessors' => [ + 'getProjectName', + ], + ], + ], + ], + 'templateMap' => [ + 'project' => 'projects/{project}', ], ], ], diff --git a/ErrorReporting/src/V1beta1/resources/report_errors_service_descriptor_config.php b/ErrorReporting/src/V1beta1/resources/report_errors_service_descriptor_config.php index 52aefb0c1051..d95e271868e2 100644 --- a/ErrorReporting/src/V1beta1/resources/report_errors_service_descriptor_config.php +++ b/ErrorReporting/src/V1beta1/resources/report_errors_service_descriptor_config.php @@ -2,6 +2,22 @@ return [ 'interfaces' => [ - 'google.devtools.clouderrorreporting.v1beta1.ReportErrorsService' => [], + 'google.devtools.clouderrorreporting.v1beta1.ReportErrorsService' => [ + 'ReportErrorEvent' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\ErrorReporting\V1beta1\ReportErrorEventResponse', + 'headerParams' => [ + [ + 'keyName' => 'project_name', + 'fieldAccessors' => [ + 'getProjectName', + ], + ], + ], + ], + 'templateMap' => [ + 'project' => 'projects/{project}', + ], + ], ], ]; diff --git a/ErrorReporting/tests/Unit/V1beta1/Client/ErrorGroupServiceClientTest.php b/ErrorReporting/tests/Unit/V1beta1/Client/ErrorGroupServiceClientTest.php new file mode 100644 index 000000000000..100a41dab981 --- /dev/null +++ b/ErrorReporting/tests/Unit/V1beta1/Client/ErrorGroupServiceClientTest.php @@ -0,0 +1,226 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return ErrorGroupServiceClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new ErrorGroupServiceClient($options); + } + + /** @test */ + public function getGroupTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name = 'name3373707'; + $groupId = 'groupId506361563'; + $expectedResponse = new ErrorGroup(); + $expectedResponse->setName($name); + $expectedResponse->setGroupId($groupId); + $transport->addResponse($expectedResponse); + // Mock request + $formattedGroupName = $gapicClient->errorGroupName('[PROJECT]', '[GROUP]'); + $request = (new GetGroupRequest()) + ->setGroupName($formattedGroupName); + $response = $gapicClient->getGroup($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.devtools.clouderrorreporting.v1beta1.ErrorGroupService/GetGroup', $actualFuncCall); + $actualValue = $actualRequestObject->getGroupName(); + $this->assertProtobufEquals($formattedGroupName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getGroupExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedGroupName = $gapicClient->errorGroupName('[PROJECT]', '[GROUP]'); + $request = (new GetGroupRequest()) + ->setGroupName($formattedGroupName); + try { + $gapicClient->getGroup($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function updateGroupTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name = 'name3373707'; + $groupId = 'groupId506361563'; + $expectedResponse = new ErrorGroup(); + $expectedResponse->setName($name); + $expectedResponse->setGroupId($groupId); + $transport->addResponse($expectedResponse); + // Mock request + $group = new ErrorGroup(); + $request = (new UpdateGroupRequest()) + ->setGroup($group); + $response = $gapicClient->updateGroup($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.devtools.clouderrorreporting.v1beta1.ErrorGroupService/UpdateGroup', $actualFuncCall); + $actualValue = $actualRequestObject->getGroup(); + $this->assertProtobufEquals($group, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function updateGroupExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $group = new ErrorGroup(); + $request = (new UpdateGroupRequest()) + ->setGroup($group); + try { + $gapicClient->updateGroup($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getGroupAsyncTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name = 'name3373707'; + $groupId = 'groupId506361563'; + $expectedResponse = new ErrorGroup(); + $expectedResponse->setName($name); + $expectedResponse->setGroupId($groupId); + $transport->addResponse($expectedResponse); + // Mock request + $formattedGroupName = $gapicClient->errorGroupName('[PROJECT]', '[GROUP]'); + $request = (new GetGroupRequest()) + ->setGroupName($formattedGroupName); + $response = $gapicClient->getGroupAsync($request)->wait(); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.devtools.clouderrorreporting.v1beta1.ErrorGroupService/GetGroup', $actualFuncCall); + $actualValue = $actualRequestObject->getGroupName(); + $this->assertProtobufEquals($formattedGroupName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } +} diff --git a/ErrorReporting/tests/Unit/V1beta1/Client/ErrorStatsServiceClientTest.php b/ErrorReporting/tests/Unit/V1beta1/Client/ErrorStatsServiceClientTest.php new file mode 100644 index 000000000000..d99c4491f0f9 --- /dev/null +++ b/ErrorReporting/tests/Unit/V1beta1/Client/ErrorStatsServiceClientTest.php @@ -0,0 +1,307 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return ErrorStatsServiceClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new ErrorStatsServiceClient($options); + } + + /** @test */ + public function deleteEventsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new DeleteEventsResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedProjectName = $gapicClient->projectName('[PROJECT]'); + $request = (new DeleteEventsRequest()) + ->setProjectName($formattedProjectName); + $response = $gapicClient->deleteEvents($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.devtools.clouderrorreporting.v1beta1.ErrorStatsService/DeleteEvents', $actualFuncCall); + $actualValue = $actualRequestObject->getProjectName(); + $this->assertProtobufEquals($formattedProjectName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function deleteEventsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedProjectName = $gapicClient->projectName('[PROJECT]'); + $request = (new DeleteEventsRequest()) + ->setProjectName($formattedProjectName); + try { + $gapicClient->deleteEvents($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listEventsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $errorEventsElement = new ErrorEvent(); + $errorEvents = [ + $errorEventsElement, + ]; + $expectedResponse = new ListEventsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setErrorEvents($errorEvents); + $transport->addResponse($expectedResponse); + // Mock request + $formattedProjectName = $gapicClient->projectName('[PROJECT]'); + $groupId = 'groupId506361563'; + $request = (new ListEventsRequest()) + ->setProjectName($formattedProjectName) + ->setGroupId($groupId); + $response = $gapicClient->listEvents($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getErrorEvents()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.devtools.clouderrorreporting.v1beta1.ErrorStatsService/ListEvents', $actualFuncCall); + $actualValue = $actualRequestObject->getProjectName(); + $this->assertProtobufEquals($formattedProjectName, $actualValue); + $actualValue = $actualRequestObject->getGroupId(); + $this->assertProtobufEquals($groupId, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listEventsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedProjectName = $gapicClient->projectName('[PROJECT]'); + $groupId = 'groupId506361563'; + $request = (new ListEventsRequest()) + ->setProjectName($formattedProjectName) + ->setGroupId($groupId); + try { + $gapicClient->listEvents($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listGroupStatsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $errorGroupStatsElement = new ErrorGroupStats(); + $errorGroupStats = [ + $errorGroupStatsElement, + ]; + $expectedResponse = new ListGroupStatsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setErrorGroupStats($errorGroupStats); + $transport->addResponse($expectedResponse); + // Mock request + $formattedProjectName = $gapicClient->projectName('[PROJECT]'); + $request = (new ListGroupStatsRequest()) + ->setProjectName($formattedProjectName); + $response = $gapicClient->listGroupStats($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getErrorGroupStats()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.devtools.clouderrorreporting.v1beta1.ErrorStatsService/ListGroupStats', $actualFuncCall); + $actualValue = $actualRequestObject->getProjectName(); + $this->assertProtobufEquals($formattedProjectName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listGroupStatsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedProjectName = $gapicClient->projectName('[PROJECT]'); + $request = (new ListGroupStatsRequest()) + ->setProjectName($formattedProjectName); + try { + $gapicClient->listGroupStats($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function deleteEventsAsyncTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new DeleteEventsResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedProjectName = $gapicClient->projectName('[PROJECT]'); + $request = (new DeleteEventsRequest()) + ->setProjectName($formattedProjectName); + $response = $gapicClient->deleteEventsAsync($request)->wait(); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.devtools.clouderrorreporting.v1beta1.ErrorStatsService/DeleteEvents', $actualFuncCall); + $actualValue = $actualRequestObject->getProjectName(); + $this->assertProtobufEquals($formattedProjectName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } +} diff --git a/ErrorReporting/tests/Unit/V1beta1/Client/ReportErrorsServiceClientTest.php b/ErrorReporting/tests/Unit/V1beta1/Client/ReportErrorsServiceClientTest.php new file mode 100644 index 000000000000..be5d01d1b07a --- /dev/null +++ b/ErrorReporting/tests/Unit/V1beta1/Client/ReportErrorsServiceClientTest.php @@ -0,0 +1,175 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return ReportErrorsServiceClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new ReportErrorsServiceClient($options); + } + + /** @test */ + public function reportErrorEventTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new ReportErrorEventResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedProjectName = $gapicClient->projectName('[PROJECT]'); + $event = new ReportedErrorEvent(); + $eventServiceContext = new ServiceContext(); + $event->setServiceContext($eventServiceContext); + $eventMessage = 'eventMessage1863181325'; + $event->setMessage($eventMessage); + $request = (new ReportErrorEventRequest()) + ->setProjectName($formattedProjectName) + ->setEvent($event); + $response = $gapicClient->reportErrorEvent($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.devtools.clouderrorreporting.v1beta1.ReportErrorsService/ReportErrorEvent', $actualFuncCall); + $actualValue = $actualRequestObject->getProjectName(); + $this->assertProtobufEquals($formattedProjectName, $actualValue); + $actualValue = $actualRequestObject->getEvent(); + $this->assertProtobufEquals($event, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function reportErrorEventExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedProjectName = $gapicClient->projectName('[PROJECT]'); + $event = new ReportedErrorEvent(); + $eventServiceContext = new ServiceContext(); + $event->setServiceContext($eventServiceContext); + $eventMessage = 'eventMessage1863181325'; + $event->setMessage($eventMessage); + $request = (new ReportErrorEventRequest()) + ->setProjectName($formattedProjectName) + ->setEvent($event); + try { + $gapicClient->reportErrorEvent($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function reportErrorEventAsyncTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new ReportErrorEventResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedProjectName = $gapicClient->projectName('[PROJECT]'); + $event = new ReportedErrorEvent(); + $eventServiceContext = new ServiceContext(); + $event->setServiceContext($eventServiceContext); + $eventMessage = 'eventMessage1863181325'; + $event->setMessage($eventMessage); + $request = (new ReportErrorEventRequest()) + ->setProjectName($formattedProjectName) + ->setEvent($event); + $response = $gapicClient->reportErrorEventAsync($request)->wait(); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.devtools.clouderrorreporting.v1beta1.ReportErrorsService/ReportErrorEvent', $actualFuncCall); + $actualValue = $actualRequestObject->getProjectName(); + $this->assertProtobufEquals($formattedProjectName, $actualValue); + $actualValue = $actualRequestObject->getEvent(); + $this->assertProtobufEquals($event, $actualValue); + $this->assertTrue($transport->isExhausted()); + } +} diff --git a/EssentialContacts/samples/V1/EssentialContactsServiceClient/compute_contacts.php b/EssentialContacts/samples/V1/EssentialContactsServiceClient/compute_contacts.php index 94e1f4d8b080..b53ceeba8c99 100644 --- a/EssentialContacts/samples/V1/EssentialContactsServiceClient/compute_contacts.php +++ b/EssentialContacts/samples/V1/EssentialContactsServiceClient/compute_contacts.php @@ -25,8 +25,9 @@ // [START essentialcontacts_v1_generated_EssentialContactsService_ComputeContacts_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; +use Google\Cloud\EssentialContacts\V1\Client\EssentialContactsServiceClient; +use Google\Cloud\EssentialContacts\V1\ComputeContactsRequest; use Google\Cloud\EssentialContacts\V1\Contact; -use Google\Cloud\EssentialContacts\V1\EssentialContactsServiceClient; /** * Lists all contacts for the resource that are subscribed to the @@ -43,10 +44,14 @@ function compute_contacts_sample(string $formattedParent): void // Create a client. $essentialContactsServiceClient = new EssentialContactsServiceClient(); + // Prepare the request message. + $request = (new ComputeContactsRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $essentialContactsServiceClient->computeContacts($formattedParent); + $response = $essentialContactsServiceClient->computeContacts($request); /** @var Contact $element */ foreach ($response as $element) { diff --git a/EssentialContacts/samples/V1/EssentialContactsServiceClient/create_contact.php b/EssentialContacts/samples/V1/EssentialContactsServiceClient/create_contact.php index 1fda9555ba2d..aa1db10b5db5 100644 --- a/EssentialContacts/samples/V1/EssentialContactsServiceClient/create_contact.php +++ b/EssentialContacts/samples/V1/EssentialContactsServiceClient/create_contact.php @@ -24,8 +24,9 @@ // [START essentialcontacts_v1_generated_EssentialContactsService_CreateContact_sync] use Google\ApiCore\ApiException; +use Google\Cloud\EssentialContacts\V1\Client\EssentialContactsServiceClient; use Google\Cloud\EssentialContacts\V1\Contact; -use Google\Cloud\EssentialContacts\V1\EssentialContactsServiceClient; +use Google\Cloud\EssentialContacts\V1\CreateContactRequest; /** * Adds a new contact for a resource. @@ -40,13 +41,16 @@ function create_contact_sample(string $formattedParent): void // Create a client. $essentialContactsServiceClient = new EssentialContactsServiceClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $contact = new Contact(); + $request = (new CreateContactRequest()) + ->setParent($formattedParent) + ->setContact($contact); // Call the API and handle any network failures. try { /** @var Contact $response */ - $response = $essentialContactsServiceClient->createContact($formattedParent, $contact); + $response = $essentialContactsServiceClient->createContact($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/EssentialContacts/samples/V1/EssentialContactsServiceClient/delete_contact.php b/EssentialContacts/samples/V1/EssentialContactsServiceClient/delete_contact.php index 3e77c38f3566..a0be98728963 100644 --- a/EssentialContacts/samples/V1/EssentialContactsServiceClient/delete_contact.php +++ b/EssentialContacts/samples/V1/EssentialContactsServiceClient/delete_contact.php @@ -24,7 +24,8 @@ // [START essentialcontacts_v1_generated_EssentialContactsService_DeleteContact_sync] use Google\ApiCore\ApiException; -use Google\Cloud\EssentialContacts\V1\EssentialContactsServiceClient; +use Google\Cloud\EssentialContacts\V1\Client\EssentialContactsServiceClient; +use Google\Cloud\EssentialContacts\V1\DeleteContactRequest; /** * Deletes a contact. @@ -40,9 +41,13 @@ function delete_contact_sample(string $formattedName): void // Create a client. $essentialContactsServiceClient = new EssentialContactsServiceClient(); + // Prepare the request message. + $request = (new DeleteContactRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { - $essentialContactsServiceClient->deleteContact($formattedName); + $essentialContactsServiceClient->deleteContact($request); printf('Call completed successfully.' . PHP_EOL); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/EssentialContacts/samples/V1/EssentialContactsServiceClient/get_contact.php b/EssentialContacts/samples/V1/EssentialContactsServiceClient/get_contact.php index 6933cecb946d..1d948a9f39bd 100644 --- a/EssentialContacts/samples/V1/EssentialContactsServiceClient/get_contact.php +++ b/EssentialContacts/samples/V1/EssentialContactsServiceClient/get_contact.php @@ -24,8 +24,9 @@ // [START essentialcontacts_v1_generated_EssentialContactsService_GetContact_sync] use Google\ApiCore\ApiException; +use Google\Cloud\EssentialContacts\V1\Client\EssentialContactsServiceClient; use Google\Cloud\EssentialContacts\V1\Contact; -use Google\Cloud\EssentialContacts\V1\EssentialContactsServiceClient; +use Google\Cloud\EssentialContacts\V1\GetContactRequest; /** * Gets a single contact. @@ -41,10 +42,14 @@ function get_contact_sample(string $formattedName): void // Create a client. $essentialContactsServiceClient = new EssentialContactsServiceClient(); + // Prepare the request message. + $request = (new GetContactRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var Contact $response */ - $response = $essentialContactsServiceClient->getContact($formattedName); + $response = $essentialContactsServiceClient->getContact($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/EssentialContacts/samples/V1/EssentialContactsServiceClient/list_contacts.php b/EssentialContacts/samples/V1/EssentialContactsServiceClient/list_contacts.php index fbea3d62adc3..0730a149c8c7 100644 --- a/EssentialContacts/samples/V1/EssentialContactsServiceClient/list_contacts.php +++ b/EssentialContacts/samples/V1/EssentialContactsServiceClient/list_contacts.php @@ -25,8 +25,9 @@ // [START essentialcontacts_v1_generated_EssentialContactsService_ListContacts_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; +use Google\Cloud\EssentialContacts\V1\Client\EssentialContactsServiceClient; use Google\Cloud\EssentialContacts\V1\Contact; -use Google\Cloud\EssentialContacts\V1\EssentialContactsServiceClient; +use Google\Cloud\EssentialContacts\V1\ListContactsRequest; /** * Lists the contacts that have been set on a resource. @@ -41,10 +42,14 @@ function list_contacts_sample(string $formattedParent): void // Create a client. $essentialContactsServiceClient = new EssentialContactsServiceClient(); + // Prepare the request message. + $request = (new ListContactsRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $essentialContactsServiceClient->listContacts($formattedParent); + $response = $essentialContactsServiceClient->listContacts($request); /** @var Contact $element */ foreach ($response as $element) { diff --git a/EssentialContacts/samples/V1/EssentialContactsServiceClient/send_test_message.php b/EssentialContacts/samples/V1/EssentialContactsServiceClient/send_test_message.php index 72631adca9ce..942aee8e6e74 100644 --- a/EssentialContacts/samples/V1/EssentialContactsServiceClient/send_test_message.php +++ b/EssentialContacts/samples/V1/EssentialContactsServiceClient/send_test_message.php @@ -24,8 +24,9 @@ // [START essentialcontacts_v1_generated_EssentialContactsService_SendTestMessage_sync] use Google\ApiCore\ApiException; -use Google\Cloud\EssentialContacts\V1\EssentialContactsServiceClient; +use Google\Cloud\EssentialContacts\V1\Client\EssentialContactsServiceClient; use Google\Cloud\EssentialContacts\V1\NotificationCategory; +use Google\Cloud\EssentialContacts\V1\SendTestMessageRequest; /** * Allows a contact admin to send a test message to contact to verify that it @@ -53,16 +54,16 @@ function send_test_message_sample( // Create a client. $essentialContactsServiceClient = new EssentialContactsServiceClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $formattedContacts = [$formattedContactsElement,]; + $request = (new SendTestMessageRequest()) + ->setContacts($formattedContacts) + ->setResource($formattedResource) + ->setNotificationCategory($notificationCategory); // Call the API and handle any network failures. try { - $essentialContactsServiceClient->sendTestMessage( - $formattedContacts, - $formattedResource, - $notificationCategory - ); + $essentialContactsServiceClient->sendTestMessage($request); printf('Call completed successfully.' . PHP_EOL); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/EssentialContacts/samples/V1/EssentialContactsServiceClient/update_contact.php b/EssentialContacts/samples/V1/EssentialContactsServiceClient/update_contact.php index 698db3e95535..3871379bf4d1 100644 --- a/EssentialContacts/samples/V1/EssentialContactsServiceClient/update_contact.php +++ b/EssentialContacts/samples/V1/EssentialContactsServiceClient/update_contact.php @@ -24,8 +24,9 @@ // [START essentialcontacts_v1_generated_EssentialContactsService_UpdateContact_sync] use Google\ApiCore\ApiException; +use Google\Cloud\EssentialContacts\V1\Client\EssentialContactsServiceClient; use Google\Cloud\EssentialContacts\V1\Contact; -use Google\Cloud\EssentialContacts\V1\EssentialContactsServiceClient; +use Google\Cloud\EssentialContacts\V1\UpdateContactRequest; /** * Updates a contact. @@ -42,13 +43,15 @@ function update_contact_sample(): void // Create a client. $essentialContactsServiceClient = new EssentialContactsServiceClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $contact = new Contact(); + $request = (new UpdateContactRequest()) + ->setContact($contact); // Call the API and handle any network failures. try { /** @var Contact $response */ - $response = $essentialContactsServiceClient->updateContact($contact); + $response = $essentialContactsServiceClient->updateContact($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/EssentialContacts/src/V1/Client/BaseClient/EssentialContactsServiceBaseClient.php b/EssentialContacts/src/V1/Client/BaseClient/EssentialContactsServiceBaseClient.php new file mode 100644 index 000000000000..32c6117c33b1 --- /dev/null +++ b/EssentialContacts/src/V1/Client/BaseClient/EssentialContactsServiceBaseClient.php @@ -0,0 +1,493 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/essential_contacts_service_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/essential_contacts_service_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/essential_contacts_service_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/essential_contacts_service_rest_client_config.php', + ], + ], + ]; + } + + /** + * Formats a string containing the fully-qualified path to represent a contact + * resource. + * + * @param string $project + * @param string $contact + * + * @return string The formatted contact resource. + */ + public static function contactName(string $project, string $contact): string + { + return self::getPathTemplate('contact')->render([ + 'project' => $project, + 'contact' => $contact, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a folder + * resource. + * + * @param string $folder + * + * @return string The formatted folder resource. + */ + public static function folderName(string $folder): string + { + return self::getPathTemplate('folder')->render([ + 'folder' => $folder, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * folder_contact resource. + * + * @param string $folder + * @param string $contact + * + * @return string The formatted folder_contact resource. + */ + public static function folderContactName(string $folder, string $contact): string + { + return self::getPathTemplate('folderContact')->render([ + 'folder' => $folder, + 'contact' => $contact, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a organization + * resource. + * + * @param string $organization + * + * @return string The formatted organization resource. + */ + public static function organizationName(string $organization): string + { + return self::getPathTemplate('organization')->render([ + 'organization' => $organization, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * organization_contact resource. + * + * @param string $organization + * @param string $contact + * + * @return string The formatted organization_contact resource. + */ + public static function organizationContactName(string $organization, string $contact): string + { + return self::getPathTemplate('organizationContact')->render([ + 'organization' => $organization, + 'contact' => $contact, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a project + * resource. + * + * @param string $project + * + * @return string The formatted project resource. + */ + public static function projectName(string $project): string + { + return self::getPathTemplate('project')->render([ + 'project' => $project, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * project_contact resource. + * + * @param string $project + * @param string $contact + * + * @return string The formatted project_contact resource. + */ + public static function projectContactName(string $project, string $contact): string + { + return self::getPathTemplate('projectContact')->render([ + 'project' => $project, + 'contact' => $contact, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - contact: projects/{project}/contacts/{contact} + * - folder: folders/{folder} + * - folderContact: folders/{folder}/contacts/{contact} + * - organization: organizations/{organization} + * - organizationContact: organizations/{organization}/contacts/{contact} + * - project: projects/{project} + * - projectContact: projects/{project}/contacts/{contact} + * + * The optional $template argument can be supplied to specify a particular pattern, + * and must match one of the templates listed above. If no $template argument is + * provided, or if the $template argument does not match one of the templates + * listed, then parseName will check each of the supported templates, and return + * the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + */ + public static function parseName(string $formattedName, string $template = null): array + { + return self::parseFormattedName($formattedName, $template); + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'essentialcontacts.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Lists all contacts for the resource that are subscribed to the + * specified notification categories, including contacts inherited from + * any parent resources. + * + * The async variant is {@see self::computeContactsAsync()} . + * + * @param ComputeContactsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function computeContacts(ComputeContactsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ComputeContacts', $request, $callOptions); + } + + /** + * Adds a new contact for a resource. + * + * The async variant is {@see self::createContactAsync()} . + * + * @param CreateContactRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Contact + * + * @throws ApiException Thrown if the API call fails. + */ + public function createContact(CreateContactRequest $request, array $callOptions = []): Contact + { + return $this->startApiCall('CreateContact', $request, $callOptions)->wait(); + } + + /** + * Deletes a contact. + * + * The async variant is {@see self::deleteContactAsync()} . + * + * @param DeleteContactRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteContact(DeleteContactRequest $request, array $callOptions = []): void + { + $this->startApiCall('DeleteContact', $request, $callOptions)->wait(); + } + + /** + * Gets a single contact. + * + * The async variant is {@see self::getContactAsync()} . + * + * @param GetContactRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Contact + * + * @throws ApiException Thrown if the API call fails. + */ + public function getContact(GetContactRequest $request, array $callOptions = []): Contact + { + return $this->startApiCall('GetContact', $request, $callOptions)->wait(); + } + + /** + * Lists the contacts that have been set on a resource. + * + * The async variant is {@see self::listContactsAsync()} . + * + * @param ListContactsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listContacts(ListContactsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListContacts', $request, $callOptions); + } + + /** + * Allows a contact admin to send a test message to contact to verify that it + * has been configured correctly. + * + * The async variant is {@see self::sendTestMessageAsync()} . + * + * @param SendTestMessageRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @throws ApiException Thrown if the API call fails. + */ + public function sendTestMessage(SendTestMessageRequest $request, array $callOptions = []): void + { + $this->startApiCall('SendTestMessage', $request, $callOptions)->wait(); + } + + /** + * Updates a contact. + * Note: A contact's email address cannot be changed. + * + * The async variant is {@see self::updateContactAsync()} . + * + * @param UpdateContactRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Contact + * + * @throws ApiException Thrown if the API call fails. + */ + public function updateContact(UpdateContactRequest $request, array $callOptions = []): Contact + { + return $this->startApiCall('UpdateContact', $request, $callOptions)->wait(); + } +} diff --git a/EssentialContacts/src/V1/Client/EssentialContactsServiceClient.php b/EssentialContacts/src/V1/Client/EssentialContactsServiceClient.php new file mode 100644 index 000000000000..e5f6c658786d --- /dev/null +++ b/EssentialContacts/src/V1/Client/EssentialContactsServiceClient.php @@ -0,0 +1,40 @@ +setParent($parent) + ->setContact($contact); + } + /** * Constructor. * diff --git a/EssentialContacts/src/V1/DeleteContactRequest.php b/EssentialContacts/src/V1/DeleteContactRequest.php index 91daf6fd96b8..a33fc9f8375c 100644 --- a/EssentialContacts/src/V1/DeleteContactRequest.php +++ b/EssentialContacts/src/V1/DeleteContactRequest.php @@ -25,6 +25,23 @@ class DeleteContactRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The name of the contact to delete. + * Format: organizations/{organization_id}/contacts/{contact_id}, + * folders/{folder_id}/contacts/{contact_id} or + * projects/{project_id}/contacts/{contact_id} + * Please see {@see EssentialContactsServiceClient::contactName()} for help formatting this field. + * + * @return \Google\Cloud\EssentialContacts\V1\DeleteContactRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/EssentialContacts/src/V1/GetContactRequest.php b/EssentialContacts/src/V1/GetContactRequest.php index 13a7aa5cbeb0..e95874e58c94 100644 --- a/EssentialContacts/src/V1/GetContactRequest.php +++ b/EssentialContacts/src/V1/GetContactRequest.php @@ -25,6 +25,23 @@ class GetContactRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The name of the contact to retrieve. + * Format: organizations/{organization_id}/contacts/{contact_id}, + * folders/{folder_id}/contacts/{contact_id} or + * projects/{project_id}/contacts/{contact_id} + * Please see {@see EssentialContactsServiceClient::contactName()} for help formatting this field. + * + * @return \Google\Cloud\EssentialContacts\V1\GetContactRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/EssentialContacts/src/V1/ListContactsRequest.php b/EssentialContacts/src/V1/ListContactsRequest.php index a41d925d0699..11bb0290cbbf 100644 --- a/EssentialContacts/src/V1/ListContactsRequest.php +++ b/EssentialContacts/src/V1/ListContactsRequest.php @@ -42,6 +42,22 @@ class ListContactsRequest extends \Google\Protobuf\Internal\Message */ private $page_token = ''; + /** + * @param string $parent Required. The parent resource name. + * Format: organizations/{organization_id}, folders/{folder_id} or + * projects/{project_id} + * Please see {@see EssentialContactsServiceClient::projectName()} for help formatting this field. + * + * @return \Google\Cloud\EssentialContacts\V1\ListContactsRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/EssentialContacts/src/V1/UpdateContactRequest.php b/EssentialContacts/src/V1/UpdateContactRequest.php index 25b8744482dd..d72808e8c35e 100644 --- a/EssentialContacts/src/V1/UpdateContactRequest.php +++ b/EssentialContacts/src/V1/UpdateContactRequest.php @@ -31,6 +31,24 @@ class UpdateContactRequest extends \Google\Protobuf\Internal\Message */ private $update_mask = null; + /** + * @param \Google\Cloud\EssentialContacts\V1\Contact $contact Required. The contact resource to replace the existing saved contact. Note: + * the email address of the contact cannot be modified. + * @param \Google\Protobuf\FieldMask $updateMask Optional. The update mask applied to the resource. For the `FieldMask` + * definition, see + * https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask + * + * @return \Google\Cloud\EssentialContacts\V1\UpdateContactRequest + * + * @experimental + */ + public static function build(\Google\Cloud\EssentialContacts\V1\Contact $contact, \Google\Protobuf\FieldMask $updateMask): self + { + return (new self()) + ->setContact($contact) + ->setUpdateMask($updateMask); + } + /** * Constructor. * diff --git a/EssentialContacts/src/V1/resources/essential_contacts_service_descriptor_config.php b/EssentialContacts/src/V1/resources/essential_contacts_service_descriptor_config.php index 0ea01e876bbf..fffc2713f526 100644 --- a/EssentialContacts/src/V1/resources/essential_contacts_service_descriptor_config.php +++ b/EssentialContacts/src/V1/resources/essential_contacts_service_descriptor_config.php @@ -12,6 +12,52 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getContacts', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\EssentialContacts\V1\ComputeContactsResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'CreateContact' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\EssentialContacts\V1\Contact', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'DeleteContact' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Protobuf\GPBEmpty', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetContact' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\EssentialContacts\V1\Contact', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'ListContacts' => [ 'pageStreaming' => [ @@ -22,6 +68,50 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getContacts', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\EssentialContacts\V1\ListContactsResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'SendTestMessage' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Protobuf\GPBEmpty', + 'headerParams' => [ + [ + 'keyName' => 'resource', + 'fieldAccessors' => [ + 'getResource', + ], + ], + ], + ], + 'UpdateContact' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\EssentialContacts\V1\Contact', + 'headerParams' => [ + [ + 'keyName' => 'contact.name', + 'fieldAccessors' => [ + 'getContact', + 'getName', + ], + ], + ], + ], + 'templateMap' => [ + 'contact' => 'projects/{project}/contacts/{contact}', + 'folder' => 'folders/{folder}', + 'folderContact' => 'folders/{folder}/contacts/{contact}', + 'organization' => 'organizations/{organization}', + 'organizationContact' => 'organizations/{organization}/contacts/{contact}', + 'project' => 'projects/{project}', + 'projectContact' => 'projects/{project}/contacts/{contact}', ], ], ], diff --git a/EssentialContacts/tests/Unit/V1/Client/EssentialContactsServiceClientTest.php b/EssentialContacts/tests/Unit/V1/Client/EssentialContactsServiceClientTest.php new file mode 100644 index 000000000000..caeb5d0e0301 --- /dev/null +++ b/EssentialContacts/tests/Unit/V1/Client/EssentialContactsServiceClientTest.php @@ -0,0 +1,601 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return EssentialContactsServiceClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new EssentialContactsServiceClient($options); + } + + /** @test */ + public function computeContactsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $contactsElement = new Contact(); + $contacts = [ + $contactsElement, + ]; + $expectedResponse = new ComputeContactsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setContacts($contacts); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $request = (new ComputeContactsRequest()) + ->setParent($formattedParent); + $response = $gapicClient->computeContacts($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getContacts()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.essentialcontacts.v1.EssentialContactsService/ComputeContacts', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function computeContactsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $request = (new ComputeContactsRequest()) + ->setParent($formattedParent); + try { + $gapicClient->computeContacts($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createContactTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name = 'name3373707'; + $email = 'email96619420'; + $languageTag = 'languageTag-2091510221'; + $expectedResponse = new Contact(); + $expectedResponse->setName($name); + $expectedResponse->setEmail($email); + $expectedResponse->setLanguageTag($languageTag); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $contact = new Contact(); + $request = (new CreateContactRequest()) + ->setParent($formattedParent) + ->setContact($contact); + $response = $gapicClient->createContact($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.essentialcontacts.v1.EssentialContactsService/CreateContact', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualRequestObject->getContact(); + $this->assertProtobufEquals($contact, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createContactExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $contact = new Contact(); + $request = (new CreateContactRequest()) + ->setParent($formattedParent) + ->setContact($contact); + try { + $gapicClient->createContact($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function deleteContactTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new GPBEmpty(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->contactName('[PROJECT]', '[CONTACT]'); + $request = (new DeleteContactRequest()) + ->setName($formattedName); + $gapicClient->deleteContact($request); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.essentialcontacts.v1.EssentialContactsService/DeleteContact', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function deleteContactExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->contactName('[PROJECT]', '[CONTACT]'); + $request = (new DeleteContactRequest()) + ->setName($formattedName); + try { + $gapicClient->deleteContact($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getContactTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $email = 'email96619420'; + $languageTag = 'languageTag-2091510221'; + $expectedResponse = new Contact(); + $expectedResponse->setName($name2); + $expectedResponse->setEmail($email); + $expectedResponse->setLanguageTag($languageTag); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->contactName('[PROJECT]', '[CONTACT]'); + $request = (new GetContactRequest()) + ->setName($formattedName); + $response = $gapicClient->getContact($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.essentialcontacts.v1.EssentialContactsService/GetContact', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getContactExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->contactName('[PROJECT]', '[CONTACT]'); + $request = (new GetContactRequest()) + ->setName($formattedName); + try { + $gapicClient->getContact($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listContactsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $contactsElement = new Contact(); + $contacts = [ + $contactsElement, + ]; + $expectedResponse = new ListContactsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setContacts($contacts); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $request = (new ListContactsRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listContacts($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getContacts()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.essentialcontacts.v1.EssentialContactsService/ListContacts', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listContactsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $request = (new ListContactsRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listContacts($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function sendTestMessageTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new GPBEmpty(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedContacts = [ + $gapicClient->contactName('[PROJECT]', '[CONTACT]'), + ]; + $formattedResource = $gapicClient->projectName('[PROJECT]'); + $notificationCategory = NotificationCategory::NOTIFICATION_CATEGORY_UNSPECIFIED; + $request = (new SendTestMessageRequest()) + ->setContacts($formattedContacts) + ->setResource($formattedResource) + ->setNotificationCategory($notificationCategory); + $gapicClient->sendTestMessage($request); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.essentialcontacts.v1.EssentialContactsService/SendTestMessage', $actualFuncCall); + $actualValue = $actualRequestObject->getContacts(); + $this->assertProtobufEquals($formattedContacts, $actualValue); + $actualValue = $actualRequestObject->getResource(); + $this->assertProtobufEquals($formattedResource, $actualValue); + $actualValue = $actualRequestObject->getNotificationCategory(); + $this->assertProtobufEquals($notificationCategory, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function sendTestMessageExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedContacts = [ + $gapicClient->contactName('[PROJECT]', '[CONTACT]'), + ]; + $formattedResource = $gapicClient->projectName('[PROJECT]'); + $notificationCategory = NotificationCategory::NOTIFICATION_CATEGORY_UNSPECIFIED; + $request = (new SendTestMessageRequest()) + ->setContacts($formattedContacts) + ->setResource($formattedResource) + ->setNotificationCategory($notificationCategory); + try { + $gapicClient->sendTestMessage($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function updateContactTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name = 'name3373707'; + $email = 'email96619420'; + $languageTag = 'languageTag-2091510221'; + $expectedResponse = new Contact(); + $expectedResponse->setName($name); + $expectedResponse->setEmail($email); + $expectedResponse->setLanguageTag($languageTag); + $transport->addResponse($expectedResponse); + // Mock request + $contact = new Contact(); + $request = (new UpdateContactRequest()) + ->setContact($contact); + $response = $gapicClient->updateContact($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.essentialcontacts.v1.EssentialContactsService/UpdateContact', $actualFuncCall); + $actualValue = $actualRequestObject->getContact(); + $this->assertProtobufEquals($contact, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function updateContactExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $contact = new Contact(); + $request = (new UpdateContactRequest()) + ->setContact($contact); + try { + $gapicClient->updateContact($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function computeContactsAsyncTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $contactsElement = new Contact(); + $contacts = [ + $contactsElement, + ]; + $expectedResponse = new ComputeContactsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setContacts($contacts); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $request = (new ComputeContactsRequest()) + ->setParent($formattedParent); + $response = $gapicClient->computeContactsAsync($request)->wait(); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getContacts()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.essentialcontacts.v1.EssentialContactsService/ComputeContacts', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } +} diff --git a/EventarcPublishing/samples/V1/PublisherClient/publish_channel_connection_events.php b/EventarcPublishing/samples/V1/PublisherClient/publish_channel_connection_events.php index 612664d42772..76a06c98cab6 100644 --- a/EventarcPublishing/samples/V1/PublisherClient/publish_channel_connection_events.php +++ b/EventarcPublishing/samples/V1/PublisherClient/publish_channel_connection_events.php @@ -24,8 +24,9 @@ // [START eventarcpublishing_v1_generated_Publisher_PublishChannelConnectionEvents_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Eventarc\Publishing\V1\Client\PublisherClient; +use Google\Cloud\Eventarc\Publishing\V1\PublishChannelConnectionEventsRequest; use Google\Cloud\Eventarc\Publishing\V1\PublishChannelConnectionEventsResponse; -use Google\Cloud\Eventarc\Publishing\V1\PublisherClient; /** * Publish events to a ChannelConnection in a partner's project. @@ -41,10 +42,13 @@ function publish_channel_connection_events_sample(): void // Create a client. $publisherClient = new PublisherClient(); + // Prepare the request message. + $request = new PublishChannelConnectionEventsRequest(); + // Call the API and handle any network failures. try { /** @var PublishChannelConnectionEventsResponse $response */ - $response = $publisherClient->publishChannelConnectionEvents(); + $response = $publisherClient->publishChannelConnectionEvents($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/EventarcPublishing/samples/V1/PublisherClient/publish_events.php b/EventarcPublishing/samples/V1/PublisherClient/publish_events.php index 44f05c020978..d4bcb2c10ad3 100644 --- a/EventarcPublishing/samples/V1/PublisherClient/publish_events.php +++ b/EventarcPublishing/samples/V1/PublisherClient/publish_events.php @@ -24,8 +24,9 @@ // [START eventarcpublishing_v1_generated_Publisher_PublishEvents_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Eventarc\Publishing\V1\Client\PublisherClient; +use Google\Cloud\Eventarc\Publishing\V1\PublishEventsRequest; use Google\Cloud\Eventarc\Publishing\V1\PublishEventsResponse; -use Google\Cloud\Eventarc\Publishing\V1\PublisherClient; /** * Publish events to a subscriber's channel. @@ -41,10 +42,13 @@ function publish_events_sample(): void // Create a client. $publisherClient = new PublisherClient(); + // Prepare the request message. + $request = new PublishEventsRequest(); + // Call the API and handle any network failures. try { /** @var PublishEventsResponse $response */ - $response = $publisherClient->publishEvents(); + $response = $publisherClient->publishEvents($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/EventarcPublishing/src/V1/Client/BaseClient/PublisherBaseClient.php b/EventarcPublishing/src/V1/Client/BaseClient/PublisherBaseClient.php new file mode 100644 index 000000000000..7a47d1e8bb3b --- /dev/null +++ b/EventarcPublishing/src/V1/Client/BaseClient/PublisherBaseClient.php @@ -0,0 +1,237 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/publisher_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/publisher_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/publisher_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/publisher_rest_client_config.php', + ], + ], + ]; + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'eventarcpublishing.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Publish events to a ChannelConnection in a partner's project. + * + * The async variant is {@see self::publishChannelConnectionEventsAsync()} . + * + * @param PublishChannelConnectionEventsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PublishChannelConnectionEventsResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function publishChannelConnectionEvents(PublishChannelConnectionEventsRequest $request, array $callOptions = []): PublishChannelConnectionEventsResponse + { + return $this->startApiCall('PublishChannelConnectionEvents', $request, $callOptions)->wait(); + } + + /** + * Publish events to a subscriber's channel. + * + * The async variant is {@see self::publishEventsAsync()} . + * + * @param PublishEventsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PublishEventsResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function publishEvents(PublishEventsRequest $request, array $callOptions = []): PublishEventsResponse + { + return $this->startApiCall('PublishEvents', $request, $callOptions)->wait(); + } +} diff --git a/EventarcPublishing/src/V1/Client/PublisherClient.php b/EventarcPublishing/src/V1/Client/PublisherClient.php new file mode 100644 index 000000000000..353777a80665 --- /dev/null +++ b/EventarcPublishing/src/V1/Client/PublisherClient.php @@ -0,0 +1,40 @@ + [ - 'google.cloud.eventarc.publishing.v1.Publisher' => [], + 'google.cloud.eventarc.publishing.v1.Publisher' => [ + 'PublishChannelConnectionEvents' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Eventarc\Publishing\V1\PublishChannelConnectionEventsResponse', + 'headerParams' => [ + [ + 'keyName' => 'channel_connection', + 'fieldAccessors' => [ + 'getChannelConnection', + ], + ], + ], + ], + 'PublishEvents' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Eventarc\Publishing\V1\PublishEventsResponse', + 'headerParams' => [ + [ + 'keyName' => 'channel', + 'fieldAccessors' => [ + 'getChannel', + ], + ], + ], + ], + ], ], ]; diff --git a/EventarcPublishing/tests/Unit/V1/Client/PublisherClientTest.php b/EventarcPublishing/tests/Unit/V1/Client/PublisherClientTest.php new file mode 100644 index 000000000000..39e04dec518f --- /dev/null +++ b/EventarcPublishing/tests/Unit/V1/Client/PublisherClientTest.php @@ -0,0 +1,194 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return PublisherClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new PublisherClient($options); + } + + /** @test */ + public function publishChannelConnectionEventsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new PublishChannelConnectionEventsResponse(); + $transport->addResponse($expectedResponse); + $request = new PublishChannelConnectionEventsRequest(); + $response = $gapicClient->publishChannelConnectionEvents($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.eventarc.publishing.v1.Publisher/PublishChannelConnectionEvents', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function publishChannelConnectionEventsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + $request = new PublishChannelConnectionEventsRequest(); + try { + $gapicClient->publishChannelConnectionEvents($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function publishEventsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new PublishEventsResponse(); + $transport->addResponse($expectedResponse); + $request = new PublishEventsRequest(); + $response = $gapicClient->publishEvents($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.eventarc.publishing.v1.Publisher/PublishEvents', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function publishEventsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + $request = new PublishEventsRequest(); + try { + $gapicClient->publishEvents($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function publishChannelConnectionEventsAsyncTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new PublishChannelConnectionEventsResponse(); + $transport->addResponse($expectedResponse); + $request = new PublishChannelConnectionEventsRequest(); + $response = $gapicClient->publishChannelConnectionEventsAsync($request)->wait(); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.eventarc.publishing.v1.Publisher/PublishChannelConnectionEvents', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } +} diff --git a/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/create_deployment.php b/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/create_deployment.php index 6c0730a0544a..08cf0c732e6c 100644 --- a/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/create_deployment.php +++ b/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/create_deployment.php @@ -24,8 +24,9 @@ // [START gsuiteaddons_v1_generated_GSuiteAddOns_CreateDeployment_sync] use Google\ApiCore\ApiException; +use Google\Cloud\GSuiteAddOns\V1\Client\GSuiteAddOnsClient; +use Google\Cloud\GSuiteAddOns\V1\CreateDeploymentRequest; use Google\Cloud\GSuiteAddOns\V1\Deployment; -use Google\Cloud\GSuiteAddOns\V1\GSuiteAddOnsClient; /** * Creates a deployment with the specified name and configuration. @@ -42,13 +43,17 @@ function create_deployment_sample(string $formattedParent, string $deploymentId) // Create a client. $gSuiteAddOnsClient = new GSuiteAddOnsClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $deployment = new Deployment(); + $request = (new CreateDeploymentRequest()) + ->setParent($formattedParent) + ->setDeploymentId($deploymentId) + ->setDeployment($deployment); // Call the API and handle any network failures. try { /** @var Deployment $response */ - $response = $gSuiteAddOnsClient->createDeployment($formattedParent, $deploymentId, $deployment); + $response = $gSuiteAddOnsClient->createDeployment($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/delete_deployment.php b/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/delete_deployment.php index 490ab01b931c..9f1c99cf8671 100644 --- a/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/delete_deployment.php +++ b/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/delete_deployment.php @@ -24,7 +24,8 @@ // [START gsuiteaddons_v1_generated_GSuiteAddOns_DeleteDeployment_sync] use Google\ApiCore\ApiException; -use Google\Cloud\GSuiteAddOns\V1\GSuiteAddOnsClient; +use Google\Cloud\GSuiteAddOns\V1\Client\GSuiteAddOnsClient; +use Google\Cloud\GSuiteAddOns\V1\DeleteDeploymentRequest; /** * Deletes the deployment with the given name. @@ -39,9 +40,13 @@ function delete_deployment_sample(string $formattedName): void // Create a client. $gSuiteAddOnsClient = new GSuiteAddOnsClient(); + // Prepare the request message. + $request = (new DeleteDeploymentRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { - $gSuiteAddOnsClient->deleteDeployment($formattedName); + $gSuiteAddOnsClient->deleteDeployment($request); printf('Call completed successfully.' . PHP_EOL); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/get_authorization.php b/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/get_authorization.php index 803252061caa..26cfde652228 100644 --- a/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/get_authorization.php +++ b/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/get_authorization.php @@ -25,7 +25,8 @@ // [START gsuiteaddons_v1_generated_GSuiteAddOns_GetAuthorization_sync] use Google\ApiCore\ApiException; use Google\Cloud\GSuiteAddOns\V1\Authorization; -use Google\Cloud\GSuiteAddOns\V1\GSuiteAddOnsClient; +use Google\Cloud\GSuiteAddOns\V1\Client\GSuiteAddOnsClient; +use Google\Cloud\GSuiteAddOns\V1\GetAuthorizationRequest; /** * Gets the authorization information for deployments in a given project. @@ -41,10 +42,14 @@ function get_authorization_sample(string $formattedName): void // Create a client. $gSuiteAddOnsClient = new GSuiteAddOnsClient(); + // Prepare the request message. + $request = (new GetAuthorizationRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var Authorization $response */ - $response = $gSuiteAddOnsClient->getAuthorization($formattedName); + $response = $gSuiteAddOnsClient->getAuthorization($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/get_deployment.php b/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/get_deployment.php index bca64e1afadf..c7f0e9e017f2 100644 --- a/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/get_deployment.php +++ b/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/get_deployment.php @@ -24,8 +24,9 @@ // [START gsuiteaddons_v1_generated_GSuiteAddOns_GetDeployment_sync] use Google\ApiCore\ApiException; +use Google\Cloud\GSuiteAddOns\V1\Client\GSuiteAddOnsClient; use Google\Cloud\GSuiteAddOns\V1\Deployment; -use Google\Cloud\GSuiteAddOns\V1\GSuiteAddOnsClient; +use Google\Cloud\GSuiteAddOns\V1\GetDeploymentRequest; /** * Gets the deployment with the specified name. @@ -40,10 +41,14 @@ function get_deployment_sample(string $formattedName): void // Create a client. $gSuiteAddOnsClient = new GSuiteAddOnsClient(); + // Prepare the request message. + $request = (new GetDeploymentRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var Deployment $response */ - $response = $gSuiteAddOnsClient->getDeployment($formattedName); + $response = $gSuiteAddOnsClient->getDeployment($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/get_install_status.php b/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/get_install_status.php index 106a618bbb85..f3929fa59d59 100644 --- a/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/get_install_status.php +++ b/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/get_install_status.php @@ -24,7 +24,8 @@ // [START gsuiteaddons_v1_generated_GSuiteAddOns_GetInstallStatus_sync] use Google\ApiCore\ApiException; -use Google\Cloud\GSuiteAddOns\V1\GSuiteAddOnsClient; +use Google\Cloud\GSuiteAddOns\V1\Client\GSuiteAddOnsClient; +use Google\Cloud\GSuiteAddOns\V1\GetInstallStatusRequest; use Google\Cloud\GSuiteAddOns\V1\InstallStatus; /** @@ -40,10 +41,14 @@ function get_install_status_sample(string $formattedName): void // Create a client. $gSuiteAddOnsClient = new GSuiteAddOnsClient(); + // Prepare the request message. + $request = (new GetInstallStatusRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var InstallStatus $response */ - $response = $gSuiteAddOnsClient->getInstallStatus($formattedName); + $response = $gSuiteAddOnsClient->getInstallStatus($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/install_deployment.php b/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/install_deployment.php index d66aca6db88a..57e8eb95bae6 100644 --- a/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/install_deployment.php +++ b/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/install_deployment.php @@ -24,7 +24,8 @@ // [START gsuiteaddons_v1_generated_GSuiteAddOns_InstallDeployment_sync] use Google\ApiCore\ApiException; -use Google\Cloud\GSuiteAddOns\V1\GSuiteAddOnsClient; +use Google\Cloud\GSuiteAddOns\V1\Client\GSuiteAddOnsClient; +use Google\Cloud\GSuiteAddOns\V1\InstallDeploymentRequest; /** * Installs a deployment in developer mode. @@ -41,9 +42,13 @@ function install_deployment_sample(string $formattedName): void // Create a client. $gSuiteAddOnsClient = new GSuiteAddOnsClient(); + // Prepare the request message. + $request = (new InstallDeploymentRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { - $gSuiteAddOnsClient->installDeployment($formattedName); + $gSuiteAddOnsClient->installDeployment($request); printf('Call completed successfully.' . PHP_EOL); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/list_deployments.php b/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/list_deployments.php index 13ae4d60fe12..050bec9bcd27 100644 --- a/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/list_deployments.php +++ b/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/list_deployments.php @@ -25,8 +25,9 @@ // [START gsuiteaddons_v1_generated_GSuiteAddOns_ListDeployments_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; +use Google\Cloud\GSuiteAddOns\V1\Client\GSuiteAddOnsClient; use Google\Cloud\GSuiteAddOns\V1\Deployment; -use Google\Cloud\GSuiteAddOns\V1\GSuiteAddOnsClient; +use Google\Cloud\GSuiteAddOns\V1\ListDeploymentsRequest; /** * Lists all deployments in a particular project. @@ -41,10 +42,14 @@ function list_deployments_sample(string $formattedParent): void // Create a client. $gSuiteAddOnsClient = new GSuiteAddOnsClient(); + // Prepare the request message. + $request = (new ListDeploymentsRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $gSuiteAddOnsClient->listDeployments($formattedParent); + $response = $gSuiteAddOnsClient->listDeployments($request); /** @var Deployment $element */ foreach ($response as $element) { diff --git a/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/replace_deployment.php b/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/replace_deployment.php index 471725821944..2f84ae454ea2 100644 --- a/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/replace_deployment.php +++ b/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/replace_deployment.php @@ -24,8 +24,9 @@ // [START gsuiteaddons_v1_generated_GSuiteAddOns_ReplaceDeployment_sync] use Google\ApiCore\ApiException; +use Google\Cloud\GSuiteAddOns\V1\Client\GSuiteAddOnsClient; use Google\Cloud\GSuiteAddOns\V1\Deployment; -use Google\Cloud\GSuiteAddOns\V1\GSuiteAddOnsClient; +use Google\Cloud\GSuiteAddOns\V1\ReplaceDeploymentRequest; /** * Creates or replaces a deployment with the specified name. @@ -41,13 +42,15 @@ function replace_deployment_sample(): void // Create a client. $gSuiteAddOnsClient = new GSuiteAddOnsClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $deployment = new Deployment(); + $request = (new ReplaceDeploymentRequest()) + ->setDeployment($deployment); // Call the API and handle any network failures. try { /** @var Deployment $response */ - $response = $gSuiteAddOnsClient->replaceDeployment($deployment); + $response = $gSuiteAddOnsClient->replaceDeployment($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/uninstall_deployment.php b/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/uninstall_deployment.php index 8a3c09f1702a..32355161ffa3 100644 --- a/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/uninstall_deployment.php +++ b/GSuiteAddOns/samples/V1/GSuiteAddOnsClient/uninstall_deployment.php @@ -24,7 +24,8 @@ // [START gsuiteaddons_v1_generated_GSuiteAddOns_UninstallDeployment_sync] use Google\ApiCore\ApiException; -use Google\Cloud\GSuiteAddOns\V1\GSuiteAddOnsClient; +use Google\Cloud\GSuiteAddOns\V1\Client\GSuiteAddOnsClient; +use Google\Cloud\GSuiteAddOns\V1\UninstallDeploymentRequest; /** * Uninstalls a developer mode deployment. @@ -41,9 +42,13 @@ function uninstall_deployment_sample(string $formattedName): void // Create a client. $gSuiteAddOnsClient = new GSuiteAddOnsClient(); + // Prepare the request message. + $request = (new UninstallDeploymentRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { - $gSuiteAddOnsClient->uninstallDeployment($formattedName); + $gSuiteAddOnsClient->uninstallDeployment($request); printf('Call completed successfully.' . PHP_EOL); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GSuiteAddOns/src/V1/Client/BaseClient/GSuiteAddOnsBaseClient.php b/GSuiteAddOns/src/V1/Client/BaseClient/GSuiteAddOnsBaseClient.php new file mode 100644 index 000000000000..a43fefe39cd2 --- /dev/null +++ b/GSuiteAddOns/src/V1/Client/BaseClient/GSuiteAddOnsBaseClient.php @@ -0,0 +1,520 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/g_suite_add_ons_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/g_suite_add_ons_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/g_suite_add_ons_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/g_suite_add_ons_rest_client_config.php', + ], + ], + ]; + } + + /** + * Formats a string containing the fully-qualified path to represent a + * authorization resource. + * + * @param string $project + * + * @return string The formatted authorization resource. + */ + public static function authorizationName(string $project): string + { + return self::getPathTemplate('authorization')->render([ + 'project' => $project, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a deployment + * resource. + * + * @param string $project + * @param string $deployment + * + * @return string The formatted deployment resource. + */ + public static function deploymentName(string $project, string $deployment): string + { + return self::getPathTemplate('deployment')->render([ + 'project' => $project, + 'deployment' => $deployment, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * install_status resource. + * + * @param string $project + * @param string $deployment + * + * @return string The formatted install_status resource. + */ + public static function installStatusName(string $project, string $deployment): string + { + return self::getPathTemplate('installStatus')->render([ + 'project' => $project, + 'deployment' => $deployment, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a project + * resource. + * + * @param string $project + * + * @return string The formatted project resource. + */ + public static function projectName(string $project): string + { + return self::getPathTemplate('project')->render([ + 'project' => $project, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - authorization: projects/{project}/authorization + * - deployment: projects/{project}/deployments/{deployment} + * - installStatus: projects/{project}/deployments/{deployment}/installStatus + * - project: projects/{project} + * + * The optional $template argument can be supplied to specify a particular pattern, + * and must match one of the templates listed above. If no $template argument is + * provided, or if the $template argument does not match one of the templates + * listed, then parseName will check each of the supported templates, and return + * the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + */ + public static function parseName(string $formattedName, string $template = null): array + { + return self::parseFormattedName($formattedName, $template); + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'gsuiteaddons.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Creates a deployment with the specified name and configuration. + * + * The async variant is {@see self::createDeploymentAsync()} . + * + * @param CreateDeploymentRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Deployment + * + * @throws ApiException Thrown if the API call fails. + */ + public function createDeployment(CreateDeploymentRequest $request, array $callOptions = []): Deployment + { + return $this->startApiCall('CreateDeployment', $request, $callOptions)->wait(); + } + + /** + * Deletes the deployment with the given name. + * + * The async variant is {@see self::deleteDeploymentAsync()} . + * + * @param DeleteDeploymentRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteDeployment(DeleteDeploymentRequest $request, array $callOptions = []): void + { + $this->startApiCall('DeleteDeployment', $request, $callOptions)->wait(); + } + + /** + * Gets the authorization information for deployments in a given project. + * + * The async variant is {@see self::getAuthorizationAsync()} . + * + * @param GetAuthorizationRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Authorization + * + * @throws ApiException Thrown if the API call fails. + */ + public function getAuthorization(GetAuthorizationRequest $request, array $callOptions = []): Authorization + { + return $this->startApiCall('GetAuthorization', $request, $callOptions)->wait(); + } + + /** + * Gets the deployment with the specified name. + * + * The async variant is {@see self::getDeploymentAsync()} . + * + * @param GetDeploymentRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Deployment + * + * @throws ApiException Thrown if the API call fails. + */ + public function getDeployment(GetDeploymentRequest $request, array $callOptions = []): Deployment + { + return $this->startApiCall('GetDeployment', $request, $callOptions)->wait(); + } + + /** + * Fetches the install status of a developer mode deployment. + * + * The async variant is {@see self::getInstallStatusAsync()} . + * + * @param GetInstallStatusRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return InstallStatus + * + * @throws ApiException Thrown if the API call fails. + */ + public function getInstallStatus(GetInstallStatusRequest $request, array $callOptions = []): InstallStatus + { + return $this->startApiCall('GetInstallStatus', $request, $callOptions)->wait(); + } + + /** + * Installs a deployment in developer mode. + * See: + * https://developers.google.com/gsuite/add-ons/how-tos/testing-gsuite-addons. + * + * The async variant is {@see self::installDeploymentAsync()} . + * + * @param InstallDeploymentRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @throws ApiException Thrown if the API call fails. + */ + public function installDeployment(InstallDeploymentRequest $request, array $callOptions = []): void + { + $this->startApiCall('InstallDeployment', $request, $callOptions)->wait(); + } + + /** + * Lists all deployments in a particular project. + * + * The async variant is {@see self::listDeploymentsAsync()} . + * + * @param ListDeploymentsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listDeployments(ListDeploymentsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListDeployments', $request, $callOptions); + } + + /** + * Creates or replaces a deployment with the specified name. + * + * The async variant is {@see self::replaceDeploymentAsync()} . + * + * @param ReplaceDeploymentRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Deployment + * + * @throws ApiException Thrown if the API call fails. + */ + public function replaceDeployment(ReplaceDeploymentRequest $request, array $callOptions = []): Deployment + { + return $this->startApiCall('ReplaceDeployment', $request, $callOptions)->wait(); + } + + /** + * Uninstalls a developer mode deployment. + * See: + * https://developers.google.com/gsuite/add-ons/how-tos/testing-gsuite-addons. + * + * The async variant is {@see self::uninstallDeploymentAsync()} . + * + * @param UninstallDeploymentRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @throws ApiException Thrown if the API call fails. + */ + public function uninstallDeployment(UninstallDeploymentRequest $request, array $callOptions = []): void + { + $this->startApiCall('UninstallDeployment', $request, $callOptions)->wait(); + } +} diff --git a/GSuiteAddOns/src/V1/Client/GSuiteAddOnsClient.php b/GSuiteAddOns/src/V1/Client/GSuiteAddOnsClient.php new file mode 100644 index 000000000000..95e8054f51ca --- /dev/null +++ b/GSuiteAddOns/src/V1/Client/GSuiteAddOnsClient.php @@ -0,0 +1,40 @@ +/deployments/`. + * + * @return \Google\Cloud\GSuiteAddOns\V1\CreateDeploymentRequest + * + * @experimental + */ + public static function build(string $parent, \Google\Cloud\GSuiteAddOns\V1\Deployment $deployment, string $deploymentId): self + { + return (new self()) + ->setParent($parent) + ->setDeployment($deployment) + ->setDeploymentId($deploymentId); + } + /** * Constructor. * diff --git a/GSuiteAddOns/src/V1/DeleteDeploymentRequest.php b/GSuiteAddOns/src/V1/DeleteDeploymentRequest.php index 7762f494140d..08c497ba7ff6 100644 --- a/GSuiteAddOns/src/V1/DeleteDeploymentRequest.php +++ b/GSuiteAddOns/src/V1/DeleteDeploymentRequest.php @@ -30,6 +30,22 @@ class DeleteDeploymentRequest extends \Google\Protobuf\Internal\Message */ private $etag = ''; + /** + * @param string $name Required. The full resource name of the deployment to delete. + * + * Example: `projects/my_project/deployments/my_deployment`. Please see + * {@see GSuiteAddOnsClient::deploymentName()} for help formatting this field. + * + * @return \Google\Cloud\GSuiteAddOns\V1\DeleteDeploymentRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GSuiteAddOns/src/V1/GetAuthorizationRequest.php b/GSuiteAddOns/src/V1/GetAuthorizationRequest.php index 99455b4cdfd2..5467a5d8fa75 100644 --- a/GSuiteAddOns/src/V1/GetAuthorizationRequest.php +++ b/GSuiteAddOns/src/V1/GetAuthorizationRequest.php @@ -24,6 +24,23 @@ class GetAuthorizationRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. Name of the project for which to get the Google Workspace Add-ons + * authorization information. + * + * Example: `projects/my_project/authorization`. Please see + * {@see GSuiteAddOnsClient::authorizationName()} for help formatting this field. + * + * @return \Google\Cloud\GSuiteAddOns\V1\GetAuthorizationRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GSuiteAddOns/src/V1/GetDeploymentRequest.php b/GSuiteAddOns/src/V1/GetDeploymentRequest.php index 95675dbe6e77..2ade5154f4c2 100644 --- a/GSuiteAddOns/src/V1/GetDeploymentRequest.php +++ b/GSuiteAddOns/src/V1/GetDeploymentRequest.php @@ -23,6 +23,22 @@ class GetDeploymentRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The full resource name of the deployment to get. + * + * Example: `projects/my_project/deployments/my_deployment`. Please see + * {@see GSuiteAddOnsClient::deploymentName()} for help formatting this field. + * + * @return \Google\Cloud\GSuiteAddOns\V1\GetDeploymentRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GSuiteAddOns/src/V1/GetInstallStatusRequest.php b/GSuiteAddOns/src/V1/GetInstallStatusRequest.php index ee70c586157a..06d33ac3225b 100644 --- a/GSuiteAddOns/src/V1/GetInstallStatusRequest.php +++ b/GSuiteAddOns/src/V1/GetInstallStatusRequest.php @@ -23,6 +23,22 @@ class GetInstallStatusRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The full resource name of the deployment. + * + * Example: `projects/my_project/deployments/my_deployment/installStatus`. Please see + * {@see GSuiteAddOnsClient::installStatusName()} for help formatting this field. + * + * @return \Google\Cloud\GSuiteAddOns\V1\GetInstallStatusRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GSuiteAddOns/src/V1/InstallDeploymentRequest.php b/GSuiteAddOns/src/V1/InstallDeploymentRequest.php index 07f6db04049b..0208f547a132 100644 --- a/GSuiteAddOns/src/V1/InstallDeploymentRequest.php +++ b/GSuiteAddOns/src/V1/InstallDeploymentRequest.php @@ -23,6 +23,22 @@ class InstallDeploymentRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The full resource name of the deployment to install. + * + * Example: `projects/my_project/deployments/my_deployment`. Please see + * {@see GSuiteAddOnsClient::deploymentName()} for help formatting this field. + * + * @return \Google\Cloud\GSuiteAddOns\V1\InstallDeploymentRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GSuiteAddOns/src/V1/ListDeploymentsRequest.php b/GSuiteAddOns/src/V1/ListDeploymentsRequest.php index 2e037256c3ac..302288c2a285 100644 --- a/GSuiteAddOns/src/V1/ListDeploymentsRequest.php +++ b/GSuiteAddOns/src/V1/ListDeploymentsRequest.php @@ -41,6 +41,22 @@ class ListDeploymentsRequest extends \Google\Protobuf\Internal\Message */ private $page_token = ''; + /** + * @param string $parent Required. Name of the project in which to create the deployment. + * + * Example: `projects/my_project`. Please see + * {@see GSuiteAddOnsClient::projectName()} for help formatting this field. + * + * @return \Google\Cloud\GSuiteAddOns\V1\ListDeploymentsRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/GSuiteAddOns/src/V1/ReplaceDeploymentRequest.php b/GSuiteAddOns/src/V1/ReplaceDeploymentRequest.php index d53581db1443..d8ce5cb5f0b6 100644 --- a/GSuiteAddOns/src/V1/ReplaceDeploymentRequest.php +++ b/GSuiteAddOns/src/V1/ReplaceDeploymentRequest.php @@ -22,6 +22,19 @@ class ReplaceDeploymentRequest extends \Google\Protobuf\Internal\Message */ private $deployment = null; + /** + * @param \Google\Cloud\GSuiteAddOns\V1\Deployment $deployment Required. The deployment to create or replace. + * + * @return \Google\Cloud\GSuiteAddOns\V1\ReplaceDeploymentRequest + * + * @experimental + */ + public static function build(\Google\Cloud\GSuiteAddOns\V1\Deployment $deployment): self + { + return (new self()) + ->setDeployment($deployment); + } + /** * Constructor. * diff --git a/GSuiteAddOns/src/V1/UninstallDeploymentRequest.php b/GSuiteAddOns/src/V1/UninstallDeploymentRequest.php index d361515f61c7..776c7a1618f8 100644 --- a/GSuiteAddOns/src/V1/UninstallDeploymentRequest.php +++ b/GSuiteAddOns/src/V1/UninstallDeploymentRequest.php @@ -23,6 +23,22 @@ class UninstallDeploymentRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The full resource name of the deployment to install. + * + * Example: `projects/my_project/deployments/my_deployment`. Please see + * {@see GSuiteAddOnsClient::deploymentName()} for help formatting this field. + * + * @return \Google\Cloud\GSuiteAddOns\V1\UninstallDeploymentRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GSuiteAddOns/src/V1/resources/g_suite_add_ons_descriptor_config.php b/GSuiteAddOns/src/V1/resources/g_suite_add_ons_descriptor_config.php index 1060fd869fce..324f1a563071 100644 --- a/GSuiteAddOns/src/V1/resources/g_suite_add_ons_descriptor_config.php +++ b/GSuiteAddOns/src/V1/resources/g_suite_add_ons_descriptor_config.php @@ -3,6 +3,78 @@ return [ 'interfaces' => [ 'google.cloud.gsuiteaddons.v1.GSuiteAddOns' => [ + 'CreateDeployment' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GSuiteAddOns\V1\Deployment', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'DeleteDeployment' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Protobuf\GPBEmpty', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetAuthorization' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GSuiteAddOns\V1\Authorization', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetDeployment' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GSuiteAddOns\V1\Deployment', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetInstallStatus' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GSuiteAddOns\V1\InstallStatus', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'InstallDeployment' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Protobuf\GPBEmpty', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], 'ListDeployments' => [ 'pageStreaming' => [ 'requestPageTokenGetMethod' => 'getPageToken', @@ -12,6 +84,47 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getDeployments', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\GSuiteAddOns\V1\ListDeploymentsResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'ReplaceDeployment' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GSuiteAddOns\V1\Deployment', + 'headerParams' => [ + [ + 'keyName' => 'deployment.name', + 'fieldAccessors' => [ + 'getDeployment', + 'getName', + ], + ], + ], + ], + 'UninstallDeployment' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Protobuf\GPBEmpty', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'templateMap' => [ + 'authorization' => 'projects/{project}/authorization', + 'deployment' => 'projects/{project}/deployments/{deployment}', + 'installStatus' => 'projects/{project}/deployments/{deployment}/installStatus', + 'project' => 'projects/{project}', ], ], ], diff --git a/GSuiteAddOns/tests/Unit/V1/Client/GSuiteAddOnsClientTest.php b/GSuiteAddOns/tests/Unit/V1/Client/GSuiteAddOnsClientTest.php new file mode 100644 index 000000000000..bee744fc1009 --- /dev/null +++ b/GSuiteAddOns/tests/Unit/V1/Client/GSuiteAddOnsClientTest.php @@ -0,0 +1,710 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return GSuiteAddOnsClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new GSuiteAddOnsClient($options); + } + + /** @test */ + public function createDeploymentTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name = 'name3373707'; + $etag = 'etag3123477'; + $expectedResponse = new Deployment(); + $expectedResponse->setName($name); + $expectedResponse->setEtag($etag); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $deploymentId = 'deploymentId51250389'; + $deployment = new Deployment(); + $request = (new CreateDeploymentRequest()) + ->setParent($formattedParent) + ->setDeploymentId($deploymentId) + ->setDeployment($deployment); + $response = $gapicClient->createDeployment($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gsuiteaddons.v1.GSuiteAddOns/CreateDeployment', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualRequestObject->getDeploymentId(); + $this->assertProtobufEquals($deploymentId, $actualValue); + $actualValue = $actualRequestObject->getDeployment(); + $this->assertProtobufEquals($deployment, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createDeploymentExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $deploymentId = 'deploymentId51250389'; + $deployment = new Deployment(); + $request = (new CreateDeploymentRequest()) + ->setParent($formattedParent) + ->setDeploymentId($deploymentId) + ->setDeployment($deployment); + try { + $gapicClient->createDeployment($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function deleteDeploymentTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new GPBEmpty(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->deploymentName('[PROJECT]', '[DEPLOYMENT]'); + $request = (new DeleteDeploymentRequest()) + ->setName($formattedName); + $gapicClient->deleteDeployment($request); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gsuiteaddons.v1.GSuiteAddOns/DeleteDeployment', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function deleteDeploymentExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->deploymentName('[PROJECT]', '[DEPLOYMENT]'); + $request = (new DeleteDeploymentRequest()) + ->setName($formattedName); + try { + $gapicClient->deleteDeployment($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getAuthorizationTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $serviceAccountEmail = 'serviceAccountEmail-1300473088'; + $oauthClientId = 'oauthClientId-1137123737'; + $expectedResponse = new Authorization(); + $expectedResponse->setName($name2); + $expectedResponse->setServiceAccountEmail($serviceAccountEmail); + $expectedResponse->setOauthClientId($oauthClientId); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->authorizationName('[PROJECT]'); + $request = (new GetAuthorizationRequest()) + ->setName($formattedName); + $response = $gapicClient->getAuthorization($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gsuiteaddons.v1.GSuiteAddOns/GetAuthorization', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getAuthorizationExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->authorizationName('[PROJECT]'); + $request = (new GetAuthorizationRequest()) + ->setName($formattedName); + try { + $gapicClient->getAuthorization($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getDeploymentTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $etag = 'etag3123477'; + $expectedResponse = new Deployment(); + $expectedResponse->setName($name2); + $expectedResponse->setEtag($etag); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->deploymentName('[PROJECT]', '[DEPLOYMENT]'); + $request = (new GetDeploymentRequest()) + ->setName($formattedName); + $response = $gapicClient->getDeployment($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gsuiteaddons.v1.GSuiteAddOns/GetDeployment', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getDeploymentExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->deploymentName('[PROJECT]', '[DEPLOYMENT]'); + $request = (new GetDeploymentRequest()) + ->setName($formattedName); + try { + $gapicClient->getDeployment($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getInstallStatusTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $expectedResponse = new InstallStatus(); + $expectedResponse->setName($name2); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->installStatusName('[PROJECT]', '[DEPLOYMENT]'); + $request = (new GetInstallStatusRequest()) + ->setName($formattedName); + $response = $gapicClient->getInstallStatus($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gsuiteaddons.v1.GSuiteAddOns/GetInstallStatus', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getInstallStatusExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->installStatusName('[PROJECT]', '[DEPLOYMENT]'); + $request = (new GetInstallStatusRequest()) + ->setName($formattedName); + try { + $gapicClient->getInstallStatus($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function installDeploymentTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new GPBEmpty(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->deploymentName('[PROJECT]', '[DEPLOYMENT]'); + $request = (new InstallDeploymentRequest()) + ->setName($formattedName); + $gapicClient->installDeployment($request); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gsuiteaddons.v1.GSuiteAddOns/InstallDeployment', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function installDeploymentExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->deploymentName('[PROJECT]', '[DEPLOYMENT]'); + $request = (new InstallDeploymentRequest()) + ->setName($formattedName); + try { + $gapicClient->installDeployment($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listDeploymentsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $deploymentsElement = new Deployment(); + $deployments = [ + $deploymentsElement, + ]; + $expectedResponse = new ListDeploymentsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setDeployments($deployments); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $request = (new ListDeploymentsRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listDeployments($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getDeployments()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gsuiteaddons.v1.GSuiteAddOns/ListDeployments', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listDeploymentsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $request = (new ListDeploymentsRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listDeployments($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function replaceDeploymentTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name = 'name3373707'; + $etag = 'etag3123477'; + $expectedResponse = new Deployment(); + $expectedResponse->setName($name); + $expectedResponse->setEtag($etag); + $transport->addResponse($expectedResponse); + // Mock request + $deployment = new Deployment(); + $request = (new ReplaceDeploymentRequest()) + ->setDeployment($deployment); + $response = $gapicClient->replaceDeployment($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gsuiteaddons.v1.GSuiteAddOns/ReplaceDeployment', $actualFuncCall); + $actualValue = $actualRequestObject->getDeployment(); + $this->assertProtobufEquals($deployment, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function replaceDeploymentExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $deployment = new Deployment(); + $request = (new ReplaceDeploymentRequest()) + ->setDeployment($deployment); + try { + $gapicClient->replaceDeployment($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function uninstallDeploymentTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new GPBEmpty(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->deploymentName('[PROJECT]', '[DEPLOYMENT]'); + $request = (new UninstallDeploymentRequest()) + ->setName($formattedName); + $gapicClient->uninstallDeployment($request); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gsuiteaddons.v1.GSuiteAddOns/UninstallDeployment', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function uninstallDeploymentExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->deploymentName('[PROJECT]', '[DEPLOYMENT]'); + $request = (new UninstallDeploymentRequest()) + ->setName($formattedName); + try { + $gapicClient->uninstallDeployment($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createDeploymentAsyncTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name = 'name3373707'; + $etag = 'etag3123477'; + $expectedResponse = new Deployment(); + $expectedResponse->setName($name); + $expectedResponse->setEtag($etag); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $deploymentId = 'deploymentId51250389'; + $deployment = new Deployment(); + $request = (new CreateDeploymentRequest()) + ->setParent($formattedParent) + ->setDeploymentId($deploymentId) + ->setDeployment($deployment); + $response = $gapicClient->createDeploymentAsync($request)->wait(); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gsuiteaddons.v1.GSuiteAddOns/CreateDeployment', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualRequestObject->getDeploymentId(); + $this->assertProtobufEquals($deploymentId, $actualValue); + $actualValue = $actualRequestObject->getDeployment(); + $this->assertProtobufEquals($deployment, $actualValue); + $this->assertTrue($transport->isExhausted()); + } +} diff --git a/GkeBackup/samples/V1/BackupForGKEClient/create_backup.php b/GkeBackup/samples/V1/BackupForGKEClient/create_backup.php index c44c8387f25d..51b608c58e40 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/create_backup.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/create_backup.php @@ -26,7 +26,8 @@ use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; use Google\Cloud\GkeBackup\V1\Backup; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\CreateBackupRequest; use Google\Rpc\Status; /** @@ -41,10 +42,14 @@ function create_backup_sample(string $formattedParent): void // Create a client. $backupForGKEClient = new BackupForGKEClient(); + // Prepare the request message. + $request = (new CreateBackupRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $backupForGKEClient->createBackup($formattedParent); + $response = $backupForGKEClient->createBackup($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeBackup/samples/V1/BackupForGKEClient/create_backup_plan.php b/GkeBackup/samples/V1/BackupForGKEClient/create_backup_plan.php index 40f2822dcae1..6829a327b675 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/create_backup_plan.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/create_backup_plan.php @@ -25,8 +25,9 @@ // [START gkebackup_v1_generated_BackupForGKE_CreateBackupPlan_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; use Google\Cloud\GkeBackup\V1\BackupPlan; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\CreateBackupPlanRequest; use Google\Rpc\Status; /** @@ -59,14 +60,18 @@ function create_backup_plan_sample( // Create a client. $backupForGKEClient = new BackupForGKEClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $backupPlan = (new BackupPlan()) ->setCluster($formattedBackupPlanCluster); + $request = (new CreateBackupPlanRequest()) + ->setParent($formattedParent) + ->setBackupPlan($backupPlan) + ->setBackupPlanId($backupPlanId); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $backupForGKEClient->createBackupPlan($formattedParent, $backupPlan, $backupPlanId); + $response = $backupForGKEClient->createBackupPlan($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeBackup/samples/V1/BackupForGKEClient/create_restore.php b/GkeBackup/samples/V1/BackupForGKEClient/create_restore.php index 113e5f66e4c3..e7189fb3b32b 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/create_restore.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/create_restore.php @@ -25,7 +25,8 @@ // [START gkebackup_v1_generated_BackupForGKE_CreateRestore_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\CreateRestoreRequest; use Google\Cloud\GkeBackup\V1\Restore; use Google\Rpc\Status; @@ -57,14 +58,18 @@ function create_restore_sample( // Create a client. $backupForGKEClient = new BackupForGKEClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $restore = (new Restore()) ->setBackup($formattedRestoreBackup); + $request = (new CreateRestoreRequest()) + ->setParent($formattedParent) + ->setRestore($restore) + ->setRestoreId($restoreId); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $backupForGKEClient->createRestore($formattedParent, $restore, $restoreId); + $response = $backupForGKEClient->createRestore($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeBackup/samples/V1/BackupForGKEClient/create_restore_plan.php b/GkeBackup/samples/V1/BackupForGKEClient/create_restore_plan.php index 6ee8fb332ae8..7c0a79a262a5 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/create_restore_plan.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/create_restore_plan.php @@ -25,7 +25,8 @@ // [START gkebackup_v1_generated_BackupForGKE_CreateRestorePlan_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\CreateRestorePlanRequest; use Google\Cloud\GkeBackup\V1\RestoreConfig; use Google\Cloud\GkeBackup\V1\RestorePlan; use Google\Rpc\Status; @@ -66,17 +67,21 @@ function create_restore_plan_sample( // Create a client. $backupForGKEClient = new BackupForGKEClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $restorePlanRestoreConfig = new RestoreConfig(); $restorePlan = (new RestorePlan()) ->setBackupPlan($formattedRestorePlanBackupPlan) ->setCluster($formattedRestorePlanCluster) ->setRestoreConfig($restorePlanRestoreConfig); + $request = (new CreateRestorePlanRequest()) + ->setParent($formattedParent) + ->setRestorePlan($restorePlan) + ->setRestorePlanId($restorePlanId); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $backupForGKEClient->createRestorePlan($formattedParent, $restorePlan, $restorePlanId); + $response = $backupForGKEClient->createRestorePlan($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeBackup/samples/V1/BackupForGKEClient/delete_backup.php b/GkeBackup/samples/V1/BackupForGKEClient/delete_backup.php index 080eb483d1ba..c19953a75e8f 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/delete_backup.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/delete_backup.php @@ -25,7 +25,8 @@ // [START gkebackup_v1_generated_BackupForGKE_DeleteBackup_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\DeleteBackupRequest; use Google\Rpc\Status; /** @@ -40,10 +41,14 @@ function delete_backup_sample(string $formattedName): void // Create a client. $backupForGKEClient = new BackupForGKEClient(); + // Prepare the request message. + $request = (new DeleteBackupRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $backupForGKEClient->deleteBackup($formattedName); + $response = $backupForGKEClient->deleteBackup($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeBackup/samples/V1/BackupForGKEClient/delete_backup_plan.php b/GkeBackup/samples/V1/BackupForGKEClient/delete_backup_plan.php index ffe77a5a96fe..d2966eff9f53 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/delete_backup_plan.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/delete_backup_plan.php @@ -25,7 +25,8 @@ // [START gkebackup_v1_generated_BackupForGKE_DeleteBackupPlan_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\DeleteBackupPlanRequest; use Google\Rpc\Status; /** @@ -40,10 +41,14 @@ function delete_backup_plan_sample(string $formattedName): void // Create a client. $backupForGKEClient = new BackupForGKEClient(); + // Prepare the request message. + $request = (new DeleteBackupPlanRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $backupForGKEClient->deleteBackupPlan($formattedName); + $response = $backupForGKEClient->deleteBackupPlan($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeBackup/samples/V1/BackupForGKEClient/delete_restore.php b/GkeBackup/samples/V1/BackupForGKEClient/delete_restore.php index 5a0033175fd9..a80ce1948004 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/delete_restore.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/delete_restore.php @@ -25,7 +25,8 @@ // [START gkebackup_v1_generated_BackupForGKE_DeleteRestore_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\DeleteRestoreRequest; use Google\Rpc\Status; /** @@ -40,10 +41,14 @@ function delete_restore_sample(string $formattedName): void // Create a client. $backupForGKEClient = new BackupForGKEClient(); + // Prepare the request message. + $request = (new DeleteRestoreRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $backupForGKEClient->deleteRestore($formattedName); + $response = $backupForGKEClient->deleteRestore($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeBackup/samples/V1/BackupForGKEClient/delete_restore_plan.php b/GkeBackup/samples/V1/BackupForGKEClient/delete_restore_plan.php index 6fe0dea6a192..e2602ebb5a34 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/delete_restore_plan.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/delete_restore_plan.php @@ -25,7 +25,8 @@ // [START gkebackup_v1_generated_BackupForGKE_DeleteRestorePlan_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\DeleteRestorePlanRequest; use Google\Rpc\Status; /** @@ -40,10 +41,14 @@ function delete_restore_plan_sample(string $formattedName): void // Create a client. $backupForGKEClient = new BackupForGKEClient(); + // Prepare the request message. + $request = (new DeleteRestorePlanRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $backupForGKEClient->deleteRestorePlan($formattedName); + $response = $backupForGKEClient->deleteRestorePlan($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeBackup/samples/V1/BackupForGKEClient/get_backup.php b/GkeBackup/samples/V1/BackupForGKEClient/get_backup.php index 5b261a394f4a..7fe4a3628e4a 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/get_backup.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/get_backup.php @@ -25,7 +25,8 @@ // [START gkebackup_v1_generated_BackupForGKE_GetBackup_sync] use Google\ApiCore\ApiException; use Google\Cloud\GkeBackup\V1\Backup; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\GetBackupRequest; /** * Retrieve the details of a single Backup. @@ -39,10 +40,14 @@ function get_backup_sample(string $formattedName): void // Create a client. $backupForGKEClient = new BackupForGKEClient(); + // Prepare the request message. + $request = (new GetBackupRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var Backup $response */ - $response = $backupForGKEClient->getBackup($formattedName); + $response = $backupForGKEClient->getBackup($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeBackup/samples/V1/BackupForGKEClient/get_backup_plan.php b/GkeBackup/samples/V1/BackupForGKEClient/get_backup_plan.php index da330bf3e0b0..d9b6f7a265a6 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/get_backup_plan.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/get_backup_plan.php @@ -24,8 +24,9 @@ // [START gkebackup_v1_generated_BackupForGKE_GetBackupPlan_sync] use Google\ApiCore\ApiException; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; use Google\Cloud\GkeBackup\V1\BackupPlan; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\GetBackupPlanRequest; /** * Retrieve the details of a single BackupPlan. @@ -39,10 +40,14 @@ function get_backup_plan_sample(string $formattedName): void // Create a client. $backupForGKEClient = new BackupForGKEClient(); + // Prepare the request message. + $request = (new GetBackupPlanRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var BackupPlan $response */ - $response = $backupForGKEClient->getBackupPlan($formattedName); + $response = $backupForGKEClient->getBackupPlan($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeBackup/samples/V1/BackupForGKEClient/get_restore.php b/GkeBackup/samples/V1/BackupForGKEClient/get_restore.php index 2fc2bd1242db..25cfe62f59bd 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/get_restore.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/get_restore.php @@ -24,7 +24,8 @@ // [START gkebackup_v1_generated_BackupForGKE_GetRestore_sync] use Google\ApiCore\ApiException; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\GetRestoreRequest; use Google\Cloud\GkeBackup\V1\Restore; /** @@ -39,10 +40,14 @@ function get_restore_sample(string $formattedName): void // Create a client. $backupForGKEClient = new BackupForGKEClient(); + // Prepare the request message. + $request = (new GetRestoreRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var Restore $response */ - $response = $backupForGKEClient->getRestore($formattedName); + $response = $backupForGKEClient->getRestore($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeBackup/samples/V1/BackupForGKEClient/get_restore_plan.php b/GkeBackup/samples/V1/BackupForGKEClient/get_restore_plan.php index 3a6b6f72a3de..b09c492f1a40 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/get_restore_plan.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/get_restore_plan.php @@ -24,7 +24,8 @@ // [START gkebackup_v1_generated_BackupForGKE_GetRestorePlan_sync] use Google\ApiCore\ApiException; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\GetRestorePlanRequest; use Google\Cloud\GkeBackup\V1\RestorePlan; /** @@ -39,10 +40,14 @@ function get_restore_plan_sample(string $formattedName): void // Create a client. $backupForGKEClient = new BackupForGKEClient(); + // Prepare the request message. + $request = (new GetRestorePlanRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var RestorePlan $response */ - $response = $backupForGKEClient->getRestorePlan($formattedName); + $response = $backupForGKEClient->getRestorePlan($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeBackup/samples/V1/BackupForGKEClient/get_volume_backup.php b/GkeBackup/samples/V1/BackupForGKEClient/get_volume_backup.php index cc1c50d6c170..6e59f5f1cea0 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/get_volume_backup.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/get_volume_backup.php @@ -24,7 +24,8 @@ // [START gkebackup_v1_generated_BackupForGKE_GetVolumeBackup_sync] use Google\ApiCore\ApiException; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\GetVolumeBackupRequest; use Google\Cloud\GkeBackup\V1\VolumeBackup; /** @@ -39,10 +40,14 @@ function get_volume_backup_sample(string $formattedName): void // Create a client. $backupForGKEClient = new BackupForGKEClient(); + // Prepare the request message. + $request = (new GetVolumeBackupRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var VolumeBackup $response */ - $response = $backupForGKEClient->getVolumeBackup($formattedName); + $response = $backupForGKEClient->getVolumeBackup($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeBackup/samples/V1/BackupForGKEClient/get_volume_restore.php b/GkeBackup/samples/V1/BackupForGKEClient/get_volume_restore.php index 88e9cb83879f..ff2416c0d3c2 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/get_volume_restore.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/get_volume_restore.php @@ -24,7 +24,8 @@ // [START gkebackup_v1_generated_BackupForGKE_GetVolumeRestore_sync] use Google\ApiCore\ApiException; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\GetVolumeRestoreRequest; use Google\Cloud\GkeBackup\V1\VolumeRestore; /** @@ -39,10 +40,14 @@ function get_volume_restore_sample(string $formattedName): void // Create a client. $backupForGKEClient = new BackupForGKEClient(); + // Prepare the request message. + $request = (new GetVolumeRestoreRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var VolumeRestore $response */ - $response = $backupForGKEClient->getVolumeRestore($formattedName); + $response = $backupForGKEClient->getVolumeRestore($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeBackup/samples/V1/BackupForGKEClient/list_backup_plans.php b/GkeBackup/samples/V1/BackupForGKEClient/list_backup_plans.php index 18533528a924..5e28e56e7f9d 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/list_backup_plans.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/list_backup_plans.php @@ -25,8 +25,9 @@ // [START gkebackup_v1_generated_BackupForGKE_ListBackupPlans_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; use Google\Cloud\GkeBackup\V1\BackupPlan; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\ListBackupPlansRequest; /** * Lists BackupPlans in a given location. @@ -40,10 +41,14 @@ function list_backup_plans_sample(string $formattedParent): void // Create a client. $backupForGKEClient = new BackupForGKEClient(); + // Prepare the request message. + $request = (new ListBackupPlansRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $backupForGKEClient->listBackupPlans($formattedParent); + $response = $backupForGKEClient->listBackupPlans($request); /** @var BackupPlan $element */ foreach ($response as $element) { diff --git a/GkeBackup/samples/V1/BackupForGKEClient/list_backups.php b/GkeBackup/samples/V1/BackupForGKEClient/list_backups.php index 563b1c1acbb6..31d376576816 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/list_backups.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/list_backups.php @@ -26,7 +26,8 @@ use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; use Google\Cloud\GkeBackup\V1\Backup; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\ListBackupsRequest; /** * Lists the Backups for a given BackupPlan. @@ -40,10 +41,14 @@ function list_backups_sample(string $formattedParent): void // Create a client. $backupForGKEClient = new BackupForGKEClient(); + // Prepare the request message. + $request = (new ListBackupsRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $backupForGKEClient->listBackups($formattedParent); + $response = $backupForGKEClient->listBackups($request); /** @var Backup $element */ foreach ($response as $element) { diff --git a/GkeBackup/samples/V1/BackupForGKEClient/list_restore_plans.php b/GkeBackup/samples/V1/BackupForGKEClient/list_restore_plans.php index de371106cfd5..507936b0ebfc 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/list_restore_plans.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/list_restore_plans.php @@ -25,7 +25,8 @@ // [START gkebackup_v1_generated_BackupForGKE_ListRestorePlans_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\ListRestorePlansRequest; use Google\Cloud\GkeBackup\V1\RestorePlan; /** @@ -40,10 +41,14 @@ function list_restore_plans_sample(string $formattedParent): void // Create a client. $backupForGKEClient = new BackupForGKEClient(); + // Prepare the request message. + $request = (new ListRestorePlansRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $backupForGKEClient->listRestorePlans($formattedParent); + $response = $backupForGKEClient->listRestorePlans($request); /** @var RestorePlan $element */ foreach ($response as $element) { diff --git a/GkeBackup/samples/V1/BackupForGKEClient/list_restores.php b/GkeBackup/samples/V1/BackupForGKEClient/list_restores.php index 3e18e8d6ad71..f968c02ba2b4 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/list_restores.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/list_restores.php @@ -25,7 +25,8 @@ // [START gkebackup_v1_generated_BackupForGKE_ListRestores_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\ListRestoresRequest; use Google\Cloud\GkeBackup\V1\Restore; /** @@ -40,10 +41,14 @@ function list_restores_sample(string $formattedParent): void // Create a client. $backupForGKEClient = new BackupForGKEClient(); + // Prepare the request message. + $request = (new ListRestoresRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $backupForGKEClient->listRestores($formattedParent); + $response = $backupForGKEClient->listRestores($request); /** @var Restore $element */ foreach ($response as $element) { diff --git a/GkeBackup/samples/V1/BackupForGKEClient/list_volume_backups.php b/GkeBackup/samples/V1/BackupForGKEClient/list_volume_backups.php index 585af6f507f7..76d828135a9c 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/list_volume_backups.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/list_volume_backups.php @@ -25,7 +25,8 @@ // [START gkebackup_v1_generated_BackupForGKE_ListVolumeBackups_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\ListVolumeBackupsRequest; use Google\Cloud\GkeBackup\V1\VolumeBackup; /** @@ -40,10 +41,14 @@ function list_volume_backups_sample(string $formattedParent): void // Create a client. $backupForGKEClient = new BackupForGKEClient(); + // Prepare the request message. + $request = (new ListVolumeBackupsRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $backupForGKEClient->listVolumeBackups($formattedParent); + $response = $backupForGKEClient->listVolumeBackups($request); /** @var VolumeBackup $element */ foreach ($response as $element) { diff --git a/GkeBackup/samples/V1/BackupForGKEClient/list_volume_restores.php b/GkeBackup/samples/V1/BackupForGKEClient/list_volume_restores.php index b82c5cdebc66..7fafc7834136 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/list_volume_restores.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/list_volume_restores.php @@ -25,7 +25,8 @@ // [START gkebackup_v1_generated_BackupForGKE_ListVolumeRestores_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\ListVolumeRestoresRequest; use Google\Cloud\GkeBackup\V1\VolumeRestore; /** @@ -40,10 +41,14 @@ function list_volume_restores_sample(string $formattedParent): void // Create a client. $backupForGKEClient = new BackupForGKEClient(); + // Prepare the request message. + $request = (new ListVolumeRestoresRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $backupForGKEClient->listVolumeRestores($formattedParent); + $response = $backupForGKEClient->listVolumeRestores($request); /** @var VolumeRestore $element */ foreach ($response as $element) { diff --git a/GkeBackup/samples/V1/BackupForGKEClient/update_backup.php b/GkeBackup/samples/V1/BackupForGKEClient/update_backup.php index b4d989890ca3..2c6d814142d0 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/update_backup.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/update_backup.php @@ -26,7 +26,8 @@ use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; use Google\Cloud\GkeBackup\V1\Backup; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\UpdateBackupRequest; use Google\Rpc\Status; /** @@ -43,13 +44,15 @@ function update_backup_sample(): void // Create a client. $backupForGKEClient = new BackupForGKEClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $backup = new Backup(); + $request = (new UpdateBackupRequest()) + ->setBackup($backup); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $backupForGKEClient->updateBackup($backup); + $response = $backupForGKEClient->updateBackup($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeBackup/samples/V1/BackupForGKEClient/update_backup_plan.php b/GkeBackup/samples/V1/BackupForGKEClient/update_backup_plan.php index 8e167682aa8e..c1d5e299b0a6 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/update_backup_plan.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/update_backup_plan.php @@ -25,8 +25,9 @@ // [START gkebackup_v1_generated_BackupForGKE_UpdateBackupPlan_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; use Google\Cloud\GkeBackup\V1\BackupPlan; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\UpdateBackupPlanRequest; use Google\Rpc\Status; /** @@ -45,14 +46,16 @@ function update_backup_plan_sample(string $formattedBackupPlanCluster): void // Create a client. $backupForGKEClient = new BackupForGKEClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $backupPlan = (new BackupPlan()) ->setCluster($formattedBackupPlanCluster); + $request = (new UpdateBackupPlanRequest()) + ->setBackupPlan($backupPlan); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $backupForGKEClient->updateBackupPlan($backupPlan); + $response = $backupForGKEClient->updateBackupPlan($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeBackup/samples/V1/BackupForGKEClient/update_restore.php b/GkeBackup/samples/V1/BackupForGKEClient/update_restore.php index 3dcdccdd2030..3aec4cc4b1db 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/update_restore.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/update_restore.php @@ -25,8 +25,9 @@ // [START gkebackup_v1_generated_BackupForGKE_UpdateRestore_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; use Google\Cloud\GkeBackup\V1\Restore; +use Google\Cloud\GkeBackup\V1\UpdateRestoreRequest; use Google\Rpc\Status; /** @@ -43,14 +44,16 @@ function update_restore_sample(string $formattedRestoreBackup): void // Create a client. $backupForGKEClient = new BackupForGKEClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $restore = (new Restore()) ->setBackup($formattedRestoreBackup); + $request = (new UpdateRestoreRequest()) + ->setRestore($restore); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $backupForGKEClient->updateRestore($restore); + $response = $backupForGKEClient->updateRestore($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeBackup/samples/V1/BackupForGKEClient/update_restore_plan.php b/GkeBackup/samples/V1/BackupForGKEClient/update_restore_plan.php index e7c8c640d8de..6ebdb49201a5 100644 --- a/GkeBackup/samples/V1/BackupForGKEClient/update_restore_plan.php +++ b/GkeBackup/samples/V1/BackupForGKEClient/update_restore_plan.php @@ -25,9 +25,10 @@ // [START gkebackup_v1_generated_BackupForGKE_UpdateRestorePlan_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\GkeBackup\V1\BackupForGKEClient; +use Google\Cloud\GkeBackup\V1\Client\BackupForGKEClient; use Google\Cloud\GkeBackup\V1\RestoreConfig; use Google\Cloud\GkeBackup\V1\RestorePlan; +use Google\Cloud\GkeBackup\V1\UpdateRestorePlanRequest; use Google\Rpc\Status; /** @@ -53,17 +54,19 @@ function update_restore_plan_sample( // Create a client. $backupForGKEClient = new BackupForGKEClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $restorePlanRestoreConfig = new RestoreConfig(); $restorePlan = (new RestorePlan()) ->setBackupPlan($formattedRestorePlanBackupPlan) ->setCluster($formattedRestorePlanCluster) ->setRestoreConfig($restorePlanRestoreConfig); + $request = (new UpdateRestorePlanRequest()) + ->setRestorePlan($restorePlan); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $backupForGKEClient->updateRestorePlan($restorePlan); + $response = $backupForGKEClient->updateRestorePlan($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeBackup/src/V1/Client/BackupForGKEClient.php b/GkeBackup/src/V1/Client/BackupForGKEClient.php new file mode 100644 index 000000000000..468725210438 --- /dev/null +++ b/GkeBackup/src/V1/Client/BackupForGKEClient.php @@ -0,0 +1,40 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/backup_for_gke_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/backup_for_gke_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/backup_for_gke_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/backup_for_gke_rest_client_config.php', + ], + ], + ]; + } + + /** + * Return an OperationsClient object with the same endpoint as $this. + * + * @return OperationsClient + */ + public function getOperationsClient() + { + return $this->operationsClient; + } + + /** + * Resume an existing long running operation that was previously started by a long + * running API method. If $methodName is not provided, or does not match a long + * running API method, then the operation can still be resumed, but the + * OperationResponse object will not deserialize the final response. + * + * @param string $operationName The name of the long running operation + * @param string $methodName The name of the method used to start the operation + * + * @return OperationResponse + */ + public function resumeOperation($operationName, $methodName = null) + { + $options = isset($this->descriptors[$methodName]['longRunning']) ? $this->descriptors[$methodName]['longRunning'] : []; + $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); + $operation->reload(); + return $operation; + } + + /** + * Formats a string containing the fully-qualified path to represent a backup + * resource. + * + * @param string $project + * @param string $location + * @param string $backupPlan + * @param string $backup + * + * @return string The formatted backup resource. + */ + public static function backupName(string $project, string $location, string $backupPlan, string $backup): string + { + return self::getPathTemplate('backup')->render([ + 'project' => $project, + 'location' => $location, + 'backup_plan' => $backupPlan, + 'backup' => $backup, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a backup_plan + * resource. + * + * @param string $project + * @param string $location + * @param string $backupPlan + * + * @return string The formatted backup_plan resource. + */ + public static function backupPlanName(string $project, string $location, string $backupPlan): string + { + return self::getPathTemplate('backupPlan')->render([ + 'project' => $project, + 'location' => $location, + 'backup_plan' => $backupPlan, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a cluster + * resource. + * + * @param string $project + * @param string $location + * @param string $cluster + * + * @return string The formatted cluster resource. + */ + public static function clusterName(string $project, string $location, string $cluster): string + { + return self::getPathTemplate('cluster')->render([ + 'project' => $project, + 'location' => $location, + 'cluster' => $cluster, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a crypto_key + * resource. + * + * @param string $project + * @param string $location + * @param string $keyRing + * @param string $cryptoKey + * + * @return string The formatted crypto_key resource. + */ + public static function cryptoKeyName(string $project, string $location, string $keyRing, string $cryptoKey): string + { + return self::getPathTemplate('cryptoKey')->render([ + 'project' => $project, + 'location' => $location, + 'key_ring' => $keyRing, + 'crypto_key' => $cryptoKey, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a location + * resource. + * + * @param string $project + * @param string $location + * + * @return string The formatted location resource. + */ + public static function locationName(string $project, string $location): string + { + return self::getPathTemplate('location')->render([ + 'project' => $project, + 'location' => $location, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a restore + * resource. + * + * @param string $project + * @param string $location + * @param string $restorePlan + * @param string $restore + * + * @return string The formatted restore resource. + */ + public static function restoreName(string $project, string $location, string $restorePlan, string $restore): string + { + return self::getPathTemplate('restore')->render([ + 'project' => $project, + 'location' => $location, + 'restore_plan' => $restorePlan, + 'restore' => $restore, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a restore_plan + * resource. + * + * @param string $project + * @param string $location + * @param string $restorePlan + * + * @return string The formatted restore_plan resource. + */ + public static function restorePlanName(string $project, string $location, string $restorePlan): string + { + return self::getPathTemplate('restorePlan')->render([ + 'project' => $project, + 'location' => $location, + 'restore_plan' => $restorePlan, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * volume_backup resource. + * + * @param string $project + * @param string $location + * @param string $backupPlan + * @param string $backup + * @param string $volumeBackup + * + * @return string The formatted volume_backup resource. + */ + public static function volumeBackupName(string $project, string $location, string $backupPlan, string $backup, string $volumeBackup): string + { + return self::getPathTemplate('volumeBackup')->render([ + 'project' => $project, + 'location' => $location, + 'backup_plan' => $backupPlan, + 'backup' => $backup, + 'volume_backup' => $volumeBackup, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * volume_restore resource. + * + * @param string $project + * @param string $location + * @param string $restorePlan + * @param string $restore + * @param string $volumeRestore + * + * @return string The formatted volume_restore resource. + */ + public static function volumeRestoreName(string $project, string $location, string $restorePlan, string $restore, string $volumeRestore): string + { + return self::getPathTemplate('volumeRestore')->render([ + 'project' => $project, + 'location' => $location, + 'restore_plan' => $restorePlan, + 'restore' => $restore, + 'volume_restore' => $volumeRestore, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - backup: projects/{project}/locations/{location}/backupPlans/{backup_plan}/backups/{backup} + * - backupPlan: projects/{project}/locations/{location}/backupPlans/{backup_plan} + * - cluster: projects/{project}/locations/{location}/clusters/{cluster} + * - cryptoKey: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key} + * - location: projects/{project}/locations/{location} + * - restore: projects/{project}/locations/{location}/restorePlans/{restore_plan}/restores/{restore} + * - restorePlan: projects/{project}/locations/{location}/restorePlans/{restore_plan} + * - volumeBackup: projects/{project}/locations/{location}/backupPlans/{backup_plan}/backups/{backup}/volumeBackups/{volume_backup} + * - volumeRestore: projects/{project}/locations/{location}/restorePlans/{restore_plan}/restores/{restore}/volumeRestores/{volume_restore} + * + * The optional $template argument can be supplied to specify a particular pattern, + * and must match one of the templates listed above. If no $template argument is + * provided, or if the $template argument does not match one of the templates + * listed, then parseName will check each of the supported templates, and return + * the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + */ + public static function parseName(string $formattedName, string $template = null): array + { + return self::parseFormattedName($formattedName, $template); + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'gkebackup.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + $this->operationsClient = $this->createOperationsClient($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Creates a Backup for the given BackupPlan. + * + * The async variant is {@see self::createBackupAsync()} . + * + * @param CreateBackupRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createBackup(CreateBackupRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreateBackup', $request, $callOptions)->wait(); + } + + /** + * Creates a new BackupPlan in a given location. + * + * The async variant is {@see self::createBackupPlanAsync()} . + * + * @param CreateBackupPlanRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createBackupPlan(CreateBackupPlanRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreateBackupPlan', $request, $callOptions)->wait(); + } + + /** + * Creates a new Restore for the given RestorePlan. + * + * The async variant is {@see self::createRestoreAsync()} . + * + * @param CreateRestoreRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createRestore(CreateRestoreRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreateRestore', $request, $callOptions)->wait(); + } + + /** + * Creates a new RestorePlan in a given location. + * + * The async variant is {@see self::createRestorePlanAsync()} . + * + * @param CreateRestorePlanRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createRestorePlan(CreateRestorePlanRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreateRestorePlan', $request, $callOptions)->wait(); + } + + /** + * Deletes an existing Backup. + * + * The async variant is {@see self::deleteBackupAsync()} . + * + * @param DeleteBackupRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteBackup(DeleteBackupRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('DeleteBackup', $request, $callOptions)->wait(); + } + + /** + * Deletes an existing BackupPlan. + * + * The async variant is {@see self::deleteBackupPlanAsync()} . + * + * @param DeleteBackupPlanRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteBackupPlan(DeleteBackupPlanRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('DeleteBackupPlan', $request, $callOptions)->wait(); + } + + /** + * Deletes an existing Restore. + * + * The async variant is {@see self::deleteRestoreAsync()} . + * + * @param DeleteRestoreRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteRestore(DeleteRestoreRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('DeleteRestore', $request, $callOptions)->wait(); + } + + /** + * Deletes an existing RestorePlan. + * + * The async variant is {@see self::deleteRestorePlanAsync()} . + * + * @param DeleteRestorePlanRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteRestorePlan(DeleteRestorePlanRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('DeleteRestorePlan', $request, $callOptions)->wait(); + } + + /** + * Retrieve the details of a single Backup. + * + * The async variant is {@see self::getBackupAsync()} . + * + * @param GetBackupRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Backup + * + * @throws ApiException Thrown if the API call fails. + */ + public function getBackup(GetBackupRequest $request, array $callOptions = []): Backup + { + return $this->startApiCall('GetBackup', $request, $callOptions)->wait(); + } + + /** + * Retrieve the details of a single BackupPlan. + * + * The async variant is {@see self::getBackupPlanAsync()} . + * + * @param GetBackupPlanRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return BackupPlan + * + * @throws ApiException Thrown if the API call fails. + */ + public function getBackupPlan(GetBackupPlanRequest $request, array $callOptions = []): BackupPlan + { + return $this->startApiCall('GetBackupPlan', $request, $callOptions)->wait(); + } + + /** + * Retrieves the details of a single Restore. + * + * The async variant is {@see self::getRestoreAsync()} . + * + * @param GetRestoreRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Restore + * + * @throws ApiException Thrown if the API call fails. + */ + public function getRestore(GetRestoreRequest $request, array $callOptions = []): Restore + { + return $this->startApiCall('GetRestore', $request, $callOptions)->wait(); + } + + /** + * Retrieve the details of a single RestorePlan. + * + * The async variant is {@see self::getRestorePlanAsync()} . + * + * @param GetRestorePlanRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return RestorePlan + * + * @throws ApiException Thrown if the API call fails. + */ + public function getRestorePlan(GetRestorePlanRequest $request, array $callOptions = []): RestorePlan + { + return $this->startApiCall('GetRestorePlan', $request, $callOptions)->wait(); + } + + /** + * Retrieve the details of a single VolumeBackup. + * + * The async variant is {@see self::getVolumeBackupAsync()} . + * + * @param GetVolumeBackupRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return VolumeBackup + * + * @throws ApiException Thrown if the API call fails. + */ + public function getVolumeBackup(GetVolumeBackupRequest $request, array $callOptions = []): VolumeBackup + { + return $this->startApiCall('GetVolumeBackup', $request, $callOptions)->wait(); + } + + /** + * Retrieve the details of a single VolumeRestore. + * + * The async variant is {@see self::getVolumeRestoreAsync()} . + * + * @param GetVolumeRestoreRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return VolumeRestore + * + * @throws ApiException Thrown if the API call fails. + */ + public function getVolumeRestore(GetVolumeRestoreRequest $request, array $callOptions = []): VolumeRestore + { + return $this->startApiCall('GetVolumeRestore', $request, $callOptions)->wait(); + } + + /** + * Lists BackupPlans in a given location. + * + * The async variant is {@see self::listBackupPlansAsync()} . + * + * @param ListBackupPlansRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listBackupPlans(ListBackupPlansRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListBackupPlans', $request, $callOptions); + } + + /** + * Lists the Backups for a given BackupPlan. + * + * The async variant is {@see self::listBackupsAsync()} . + * + * @param ListBackupsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listBackups(ListBackupsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListBackups', $request, $callOptions); + } + + /** + * Lists RestorePlans in a given location. + * + * The async variant is {@see self::listRestorePlansAsync()} . + * + * @param ListRestorePlansRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listRestorePlans(ListRestorePlansRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListRestorePlans', $request, $callOptions); + } + + /** + * Lists the Restores for a given RestorePlan. + * + * The async variant is {@see self::listRestoresAsync()} . + * + * @param ListRestoresRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listRestores(ListRestoresRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListRestores', $request, $callOptions); + } + + /** + * Lists the VolumeBackups for a given Backup. + * + * The async variant is {@see self::listVolumeBackupsAsync()} . + * + * @param ListVolumeBackupsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listVolumeBackups(ListVolumeBackupsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListVolumeBackups', $request, $callOptions); + } + + /** + * Lists the VolumeRestores for a given Restore. + * + * The async variant is {@see self::listVolumeRestoresAsync()} . + * + * @param ListVolumeRestoresRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listVolumeRestores(ListVolumeRestoresRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListVolumeRestores', $request, $callOptions); + } + + /** + * Update a Backup. + * + * The async variant is {@see self::updateBackupAsync()} . + * + * @param UpdateBackupRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function updateBackup(UpdateBackupRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('UpdateBackup', $request, $callOptions)->wait(); + } + + /** + * Update a BackupPlan. + * + * The async variant is {@see self::updateBackupPlanAsync()} . + * + * @param UpdateBackupPlanRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function updateBackupPlan(UpdateBackupPlanRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('UpdateBackupPlan', $request, $callOptions)->wait(); + } + + /** + * Update a Restore. + * + * The async variant is {@see self::updateRestoreAsync()} . + * + * @param UpdateRestoreRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function updateRestore(UpdateRestoreRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('UpdateRestore', $request, $callOptions)->wait(); + } + + /** + * Update a RestorePlan. + * + * The async variant is {@see self::updateRestorePlanAsync()} . + * + * @param UpdateRestorePlanRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function updateRestorePlan(UpdateRestorePlanRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('UpdateRestorePlan', $request, $callOptions)->wait(); + } +} diff --git a/GkeBackup/src/V1/CreateBackupPlanRequest.php b/GkeBackup/src/V1/CreateBackupPlanRequest.php index 0f282360b2aa..d23933ba2cc2 100644 --- a/GkeBackup/src/V1/CreateBackupPlanRequest.php +++ b/GkeBackup/src/V1/CreateBackupPlanRequest.php @@ -41,6 +41,32 @@ class CreateBackupPlanRequest extends \Google\Protobuf\Internal\Message */ private $backup_plan_id = ''; + /** + * @param string $parent Required. The location within which to create the BackupPlan. + * Format: projects/*/locations/* + * Please see {@see BackupForGKEClient::locationName()} for help formatting this field. + * @param \Google\Cloud\GkeBackup\V1\BackupPlan $backupPlan Required. The BackupPlan resource object to create. + * @param string $backupPlanId Required. The client-provided short name for the BackupPlan resource. + * This name must: + * + * - be between 1 and 63 characters long (inclusive) + * - consist of only lower-case ASCII letters, numbers, and dashes + * - start with a lower-case letter + * - end with a lower-case letter or number + * - be unique within the set of BackupPlans in this location + * + * @return \Google\Cloud\GkeBackup\V1\CreateBackupPlanRequest + * + * @experimental + */ + public static function build(string $parent, \Google\Cloud\GkeBackup\V1\BackupPlan $backupPlan, string $backupPlanId): self + { + return (new self()) + ->setParent($parent) + ->setBackupPlan($backupPlan) + ->setBackupPlanId($backupPlanId); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/CreateBackupRequest.php b/GkeBackup/src/V1/CreateBackupRequest.php index 1f1d1dcaff43..e2ef7f9cb609 100644 --- a/GkeBackup/src/V1/CreateBackupRequest.php +++ b/GkeBackup/src/V1/CreateBackupRequest.php @@ -41,6 +41,32 @@ class CreateBackupRequest extends \Google\Protobuf\Internal\Message */ private $backup_id = ''; + /** + * @param string $parent Required. The BackupPlan within which to create the Backup. + * Format: projects/*/locations/*/backupPlans/* + * Please see {@see BackupForGKEClient::backupPlanName()} for help formatting this field. + * @param \Google\Cloud\GkeBackup\V1\Backup $backup The Backup resource to create. + * @param string $backupId The client-provided short name for the Backup resource. + * This name must: + * + * - be between 1 and 63 characters long (inclusive) + * - consist of only lower-case ASCII letters, numbers, and dashes + * - start with a lower-case letter + * - end with a lower-case letter or number + * - be unique within the set of Backups in this BackupPlan + * + * @return \Google\Cloud\GkeBackup\V1\CreateBackupRequest + * + * @experimental + */ + public static function build(string $parent, \Google\Cloud\GkeBackup\V1\Backup $backup, string $backupId): self + { + return (new self()) + ->setParent($parent) + ->setBackup($backup) + ->setBackupId($backupId); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/CreateRestorePlanRequest.php b/GkeBackup/src/V1/CreateRestorePlanRequest.php index c25eec5ffa18..e28a91bbd045 100644 --- a/GkeBackup/src/V1/CreateRestorePlanRequest.php +++ b/GkeBackup/src/V1/CreateRestorePlanRequest.php @@ -41,6 +41,32 @@ class CreateRestorePlanRequest extends \Google\Protobuf\Internal\Message */ private $restore_plan_id = ''; + /** + * @param string $parent Required. The location within which to create the RestorePlan. + * Format: projects/*/locations/* + * Please see {@see BackupForGKEClient::locationName()} for help formatting this field. + * @param \Google\Cloud\GkeBackup\V1\RestorePlan $restorePlan Required. The RestorePlan resource object to create. + * @param string $restorePlanId Required. The client-provided short name for the RestorePlan resource. + * This name must: + * + * - be between 1 and 63 characters long (inclusive) + * - consist of only lower-case ASCII letters, numbers, and dashes + * - start with a lower-case letter + * - end with a lower-case letter or number + * - be unique within the set of RestorePlans in this location + * + * @return \Google\Cloud\GkeBackup\V1\CreateRestorePlanRequest + * + * @experimental + */ + public static function build(string $parent, \Google\Cloud\GkeBackup\V1\RestorePlan $restorePlan, string $restorePlanId): self + { + return (new self()) + ->setParent($parent) + ->setRestorePlan($restorePlan) + ->setRestorePlanId($restorePlanId); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/CreateRestoreRequest.php b/GkeBackup/src/V1/CreateRestoreRequest.php index 5eab75a32de1..ba91472e0aee 100644 --- a/GkeBackup/src/V1/CreateRestoreRequest.php +++ b/GkeBackup/src/V1/CreateRestoreRequest.php @@ -41,6 +41,32 @@ class CreateRestoreRequest extends \Google\Protobuf\Internal\Message */ private $restore_id = ''; + /** + * @param string $parent Required. The RestorePlan within which to create the Restore. + * Format: projects/*/locations/*/restorePlans/* + * Please see {@see BackupForGKEClient::restorePlanName()} for help formatting this field. + * @param \Google\Cloud\GkeBackup\V1\Restore $restore Required. The restore resource to create. + * @param string $restoreId Required. The client-provided short name for the Restore resource. + * This name must: + * + * - be between 1 and 63 characters long (inclusive) + * - consist of only lower-case ASCII letters, numbers, and dashes + * - start with a lower-case letter + * - end with a lower-case letter or number + * - be unique within the set of Restores in this RestorePlan. + * + * @return \Google\Cloud\GkeBackup\V1\CreateRestoreRequest + * + * @experimental + */ + public static function build(string $parent, \Google\Cloud\GkeBackup\V1\Restore $restore, string $restoreId): self + { + return (new self()) + ->setParent($parent) + ->setRestore($restore) + ->setRestoreId($restoreId); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/DeleteBackupPlanRequest.php b/GkeBackup/src/V1/DeleteBackupPlanRequest.php index faf23b6ae8ce..12a98af0bee1 100644 --- a/GkeBackup/src/V1/DeleteBackupPlanRequest.php +++ b/GkeBackup/src/V1/DeleteBackupPlanRequest.php @@ -31,6 +31,21 @@ class DeleteBackupPlanRequest extends \Google\Protobuf\Internal\Message */ private $etag = ''; + /** + * @param string $name Required. Fully qualified BackupPlan name. + * Format: projects/*/locations/*/backupPlans/* + * Please see {@see BackupForGKEClient::backupPlanName()} for help formatting this field. + * + * @return \Google\Cloud\GkeBackup\V1\DeleteBackupPlanRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/DeleteBackupRequest.php b/GkeBackup/src/V1/DeleteBackupRequest.php index 2229ddf564ff..dc519df51e00 100644 --- a/GkeBackup/src/V1/DeleteBackupRequest.php +++ b/GkeBackup/src/V1/DeleteBackupRequest.php @@ -39,6 +39,21 @@ class DeleteBackupRequest extends \Google\Protobuf\Internal\Message */ private $force = false; + /** + * @param string $name Required. Name of the Backup resource. + * Format: projects/*/locations/*/backupPlans/*/backups/* + * Please see {@see BackupForGKEClient::backupName()} for help formatting this field. + * + * @return \Google\Cloud\GkeBackup\V1\DeleteBackupRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/DeleteRestorePlanRequest.php b/GkeBackup/src/V1/DeleteRestorePlanRequest.php index 671beb55a9bf..d55bee2dc7c4 100644 --- a/GkeBackup/src/V1/DeleteRestorePlanRequest.php +++ b/GkeBackup/src/V1/DeleteRestorePlanRequest.php @@ -39,6 +39,21 @@ class DeleteRestorePlanRequest extends \Google\Protobuf\Internal\Message */ private $force = false; + /** + * @param string $name Required. Fully qualified RestorePlan name. + * Format: projects/*/locations/*/restorePlans/* + * Please see {@see BackupForGKEClient::restorePlanName()} for help formatting this field. + * + * @return \Google\Cloud\GkeBackup\V1\DeleteRestorePlanRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/DeleteRestoreRequest.php b/GkeBackup/src/V1/DeleteRestoreRequest.php index 47de45a5c44a..d7411f233104 100644 --- a/GkeBackup/src/V1/DeleteRestoreRequest.php +++ b/GkeBackup/src/V1/DeleteRestoreRequest.php @@ -39,6 +39,21 @@ class DeleteRestoreRequest extends \Google\Protobuf\Internal\Message */ private $force = false; + /** + * @param string $name Required. Full name of the Restore + * Format: projects/*/locations/*/restorePlans/*/restores/* + * Please see {@see BackupForGKEClient::restoreName()} for help formatting this field. + * + * @return \Google\Cloud\GkeBackup\V1\DeleteRestoreRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/GetBackupPlanRequest.php b/GkeBackup/src/V1/GetBackupPlanRequest.php index b224dd16e47c..d2492c0a9dc5 100644 --- a/GkeBackup/src/V1/GetBackupPlanRequest.php +++ b/GkeBackup/src/V1/GetBackupPlanRequest.php @@ -23,6 +23,21 @@ class GetBackupPlanRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. Fully qualified BackupPlan name. + * Format: projects/*/locations/*/backupPlans/* + * Please see {@see BackupForGKEClient::backupPlanName()} for help formatting this field. + * + * @return \Google\Cloud\GkeBackup\V1\GetBackupPlanRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/GetBackupRequest.php b/GkeBackup/src/V1/GetBackupRequest.php index 247b6075ff48..0560d55535f5 100644 --- a/GkeBackup/src/V1/GetBackupRequest.php +++ b/GkeBackup/src/V1/GetBackupRequest.php @@ -23,6 +23,21 @@ class GetBackupRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. Full name of the Backup resource. + * Format: projects/*/locations/*/backupPlans/*/backups/* + * Please see {@see BackupForGKEClient::backupName()} for help formatting this field. + * + * @return \Google\Cloud\GkeBackup\V1\GetBackupRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/GetRestorePlanRequest.php b/GkeBackup/src/V1/GetRestorePlanRequest.php index 79771e687390..b96be4554317 100644 --- a/GkeBackup/src/V1/GetRestorePlanRequest.php +++ b/GkeBackup/src/V1/GetRestorePlanRequest.php @@ -23,6 +23,21 @@ class GetRestorePlanRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. Fully qualified RestorePlan name. + * Format: projects/*/locations/*/restorePlans/* + * Please see {@see BackupForGKEClient::restorePlanName()} for help formatting this field. + * + * @return \Google\Cloud\GkeBackup\V1\GetRestorePlanRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/GetRestoreRequest.php b/GkeBackup/src/V1/GetRestoreRequest.php index 7340f1c35148..aa974eae1a86 100644 --- a/GkeBackup/src/V1/GetRestoreRequest.php +++ b/GkeBackup/src/V1/GetRestoreRequest.php @@ -23,6 +23,21 @@ class GetRestoreRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. Name of the restore resource. + * Format: projects/*/locations/*/restorePlans/*/restores/* + * Please see {@see BackupForGKEClient::restoreName()} for help formatting this field. + * + * @return \Google\Cloud\GkeBackup\V1\GetRestoreRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/GetVolumeBackupRequest.php b/GkeBackup/src/V1/GetVolumeBackupRequest.php index c0e617d02a91..a67445fb5152 100644 --- a/GkeBackup/src/V1/GetVolumeBackupRequest.php +++ b/GkeBackup/src/V1/GetVolumeBackupRequest.php @@ -23,6 +23,21 @@ class GetVolumeBackupRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. Full name of the VolumeBackup resource. + * Format: projects/*/locations/*/backupPlans/*/backups/*/volumeBackups/* + * Please see {@see BackupForGKEClient::volumeBackupName()} for help formatting this field. + * + * @return \Google\Cloud\GkeBackup\V1\GetVolumeBackupRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/GetVolumeRestoreRequest.php b/GkeBackup/src/V1/GetVolumeRestoreRequest.php index b8d2ef1595a8..2e2c09a7cef2 100644 --- a/GkeBackup/src/V1/GetVolumeRestoreRequest.php +++ b/GkeBackup/src/V1/GetVolumeRestoreRequest.php @@ -23,6 +23,21 @@ class GetVolumeRestoreRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. Full name of the VolumeRestore resource. + * Format: projects/*/locations/*/restorePlans/*/restores/*/volumeRestores/* + * Please see {@see BackupForGKEClient::volumeRestoreName()} for help formatting this field. + * + * @return \Google\Cloud\GkeBackup\V1\GetVolumeRestoreRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/ListBackupPlansRequest.php b/GkeBackup/src/V1/ListBackupPlansRequest.php index d88a2d0e0026..99b1c206eff2 100644 --- a/GkeBackup/src/V1/ListBackupPlansRequest.php +++ b/GkeBackup/src/V1/ListBackupPlansRequest.php @@ -57,6 +57,21 @@ class ListBackupPlansRequest extends \Google\Protobuf\Internal\Message */ private $order_by = ''; + /** + * @param string $parent Required. The location that contains the BackupPlans to list. + * Format: projects/*/locations/* + * Please see {@see BackupForGKEClient::locationName()} for help formatting this field. + * + * @return \Google\Cloud\GkeBackup\V1\ListBackupPlansRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/ListBackupsRequest.php b/GkeBackup/src/V1/ListBackupsRequest.php index b6a929be0353..0df442fd3159 100644 --- a/GkeBackup/src/V1/ListBackupsRequest.php +++ b/GkeBackup/src/V1/ListBackupsRequest.php @@ -57,6 +57,21 @@ class ListBackupsRequest extends \Google\Protobuf\Internal\Message */ private $order_by = ''; + /** + * @param string $parent Required. The BackupPlan that contains the Backups to list. + * Format: projects/*/locations/*/backupPlans/* + * Please see {@see BackupForGKEClient::backupPlanName()} for help formatting this field. + * + * @return \Google\Cloud\GkeBackup\V1\ListBackupsRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/ListRestorePlansRequest.php b/GkeBackup/src/V1/ListRestorePlansRequest.php index 190702a874f0..cbaebb820fea 100644 --- a/GkeBackup/src/V1/ListRestorePlansRequest.php +++ b/GkeBackup/src/V1/ListRestorePlansRequest.php @@ -57,6 +57,21 @@ class ListRestorePlansRequest extends \Google\Protobuf\Internal\Message */ private $order_by = ''; + /** + * @param string $parent Required. The location that contains the RestorePlans to list. + * Format: projects/*/locations/* + * Please see {@see BackupForGKEClient::locationName()} for help formatting this field. + * + * @return \Google\Cloud\GkeBackup\V1\ListRestorePlansRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/ListRestoresRequest.php b/GkeBackup/src/V1/ListRestoresRequest.php index eac97dd3fefe..fc66aaa737fd 100644 --- a/GkeBackup/src/V1/ListRestoresRequest.php +++ b/GkeBackup/src/V1/ListRestoresRequest.php @@ -57,6 +57,21 @@ class ListRestoresRequest extends \Google\Protobuf\Internal\Message */ private $order_by = ''; + /** + * @param string $parent Required. The RestorePlan that contains the Restores to list. + * Format: projects/*/locations/*/restorePlans/* + * Please see {@see BackupForGKEClient::restorePlanName()} for help formatting this field. + * + * @return \Google\Cloud\GkeBackup\V1\ListRestoresRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/ListVolumeBackupsRequest.php b/GkeBackup/src/V1/ListVolumeBackupsRequest.php index 73d6bb55a163..5a35fb7bd728 100644 --- a/GkeBackup/src/V1/ListVolumeBackupsRequest.php +++ b/GkeBackup/src/V1/ListVolumeBackupsRequest.php @@ -57,6 +57,21 @@ class ListVolumeBackupsRequest extends \Google\Protobuf\Internal\Message */ private $order_by = ''; + /** + * @param string $parent Required. The Backup that contains the VolumeBackups to list. + * Format: projects/*/locations/*/backupPlans/*/backups/* + * Please see {@see BackupForGKEClient::backupName()} for help formatting this field. + * + * @return \Google\Cloud\GkeBackup\V1\ListVolumeBackupsRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/ListVolumeRestoresRequest.php b/GkeBackup/src/V1/ListVolumeRestoresRequest.php index ff8369418628..e8b5e324c4c4 100644 --- a/GkeBackup/src/V1/ListVolumeRestoresRequest.php +++ b/GkeBackup/src/V1/ListVolumeRestoresRequest.php @@ -57,6 +57,21 @@ class ListVolumeRestoresRequest extends \Google\Protobuf\Internal\Message */ private $order_by = ''; + /** + * @param string $parent Required. The Restore that contains the VolumeRestores to list. + * Format: projects/*/locations/*/restorePlans/*/restores/* + * Please see {@see BackupForGKEClient::restoreName()} for help formatting this field. + * + * @return \Google\Cloud\GkeBackup\V1\ListVolumeRestoresRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/UpdateBackupPlanRequest.php b/GkeBackup/src/V1/UpdateBackupPlanRequest.php index 31c12bc223fe..4c57365c874a 100644 --- a/GkeBackup/src/V1/UpdateBackupPlanRequest.php +++ b/GkeBackup/src/V1/UpdateBackupPlanRequest.php @@ -37,6 +37,30 @@ class UpdateBackupPlanRequest extends \Google\Protobuf\Internal\Message */ private $update_mask = null; + /** + * @param \Google\Cloud\GkeBackup\V1\BackupPlan $backupPlan Required. A new version of the BackupPlan resource that contains updated fields. + * This may be sparsely populated if an `update_mask` is provided. + * @param \Google\Protobuf\FieldMask $updateMask This is used to specify the fields to be overwritten in the + * BackupPlan targeted for update. The values for each of these + * updated fields will be taken from the `backup_plan` provided + * with this request. Field names are relative to the root of the resource + * (e.g., `description`, `backup_config.include_volume_data`, etc.) + * If no `update_mask` is provided, all fields in `backup_plan` will be + * written to the target BackupPlan resource. + * Note that OUTPUT_ONLY and IMMUTABLE fields in `backup_plan` are ignored + * and are not used to update the target BackupPlan. + * + * @return \Google\Cloud\GkeBackup\V1\UpdateBackupPlanRequest + * + * @experimental + */ + public static function build(\Google\Cloud\GkeBackup\V1\BackupPlan $backupPlan, \Google\Protobuf\FieldMask $updateMask): self + { + return (new self()) + ->setBackupPlan($backupPlan) + ->setUpdateMask($updateMask); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/UpdateBackupRequest.php b/GkeBackup/src/V1/UpdateBackupRequest.php index f27c619b2d24..a7e28441100a 100644 --- a/GkeBackup/src/V1/UpdateBackupRequest.php +++ b/GkeBackup/src/V1/UpdateBackupRequest.php @@ -36,6 +36,29 @@ class UpdateBackupRequest extends \Google\Protobuf\Internal\Message */ private $update_mask = null; + /** + * @param \Google\Cloud\GkeBackup\V1\Backup $backup Required. A new version of the Backup resource that contains updated fields. + * This may be sparsely populated if an `update_mask` is provided. + * @param \Google\Protobuf\FieldMask $updateMask This is used to specify the fields to be overwritten in the + * Backup targeted for update. The values for each of these + * updated fields will be taken from the `backup_plan` provided + * with this request. Field names are relative to the root of the resource. + * If no `update_mask` is provided, all fields in `backup` will be + * written to the target Backup resource. + * Note that OUTPUT_ONLY and IMMUTABLE fields in `backup` are ignored + * and are not used to update the target Backup. + * + * @return \Google\Cloud\GkeBackup\V1\UpdateBackupRequest + * + * @experimental + */ + public static function build(\Google\Cloud\GkeBackup\V1\Backup $backup, \Google\Protobuf\FieldMask $updateMask): self + { + return (new self()) + ->setBackup($backup) + ->setUpdateMask($updateMask); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/UpdateRestorePlanRequest.php b/GkeBackup/src/V1/UpdateRestorePlanRequest.php index 65e938fd8709..2693973cb8e3 100644 --- a/GkeBackup/src/V1/UpdateRestorePlanRequest.php +++ b/GkeBackup/src/V1/UpdateRestorePlanRequest.php @@ -36,6 +36,29 @@ class UpdateRestorePlanRequest extends \Google\Protobuf\Internal\Message */ private $update_mask = null; + /** + * @param \Google\Cloud\GkeBackup\V1\RestorePlan $restorePlan Required. A new version of the RestorePlan resource that contains updated fields. + * This may be sparsely populated if an `update_mask` is provided. + * @param \Google\Protobuf\FieldMask $updateMask This is used to specify the fields to be overwritten in the + * RestorePlan targeted for update. The values for each of these + * updated fields will be taken from the `restore_plan` provided + * with this request. Field names are relative to the root of the resource. + * If no `update_mask` is provided, all fields in `restore_plan` will be + * written to the target RestorePlan resource. + * Note that OUTPUT_ONLY and IMMUTABLE fields in `restore_plan` are ignored + * and are not used to update the target RestorePlan. + * + * @return \Google\Cloud\GkeBackup\V1\UpdateRestorePlanRequest + * + * @experimental + */ + public static function build(\Google\Cloud\GkeBackup\V1\RestorePlan $restorePlan, \Google\Protobuf\FieldMask $updateMask): self + { + return (new self()) + ->setRestorePlan($restorePlan) + ->setUpdateMask($updateMask); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/UpdateRestoreRequest.php b/GkeBackup/src/V1/UpdateRestoreRequest.php index 10cce4129498..9a5f64510d38 100644 --- a/GkeBackup/src/V1/UpdateRestoreRequest.php +++ b/GkeBackup/src/V1/UpdateRestoreRequest.php @@ -36,6 +36,29 @@ class UpdateRestoreRequest extends \Google\Protobuf\Internal\Message */ private $update_mask = null; + /** + * @param \Google\Cloud\GkeBackup\V1\Restore $restore Required. A new version of the Restore resource that contains updated fields. + * This may be sparsely populated if an `update_mask` is provided. + * @param \Google\Protobuf\FieldMask $updateMask This is used to specify the fields to be overwritten in the + * Restore targeted for update. The values for each of these + * updated fields will be taken from the `restore` provided + * with this request. Field names are relative to the root of the resource. + * If no `update_mask` is provided, all fields in `restore` will be + * written to the target Restore resource. + * Note that OUTPUT_ONLY and IMMUTABLE fields in `restore` are ignored + * and are not used to update the target Restore. + * + * @return \Google\Cloud\GkeBackup\V1\UpdateRestoreRequest + * + * @experimental + */ + public static function build(\Google\Cloud\GkeBackup\V1\Restore $restore, \Google\Protobuf\FieldMask $updateMask): self + { + return (new self()) + ->setRestore($restore) + ->setUpdateMask($updateMask); + } + /** * Constructor. * diff --git a/GkeBackup/src/V1/resources/backup_for_gke_descriptor_config.php b/GkeBackup/src/V1/resources/backup_for_gke_descriptor_config.php index 69f8f5298390..25eb5e1a1e17 100644 --- a/GkeBackup/src/V1/resources/backup_for_gke_descriptor_config.php +++ b/GkeBackup/src/V1/resources/backup_for_gke_descriptor_config.php @@ -12,6 +12,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'CreateBackupPlan' => [ 'longRunning' => [ @@ -22,6 +31,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'CreateRestore' => [ 'longRunning' => [ @@ -32,6 +50,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'CreateRestorePlan' => [ 'longRunning' => [ @@ -42,6 +69,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'DeleteBackup' => [ 'longRunning' => [ @@ -52,6 +88,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'DeleteBackupPlan' => [ 'longRunning' => [ @@ -62,6 +107,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'DeleteRestore' => [ 'longRunning' => [ @@ -72,6 +126,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'DeleteRestorePlan' => [ 'longRunning' => [ @@ -82,6 +145,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'UpdateBackup' => [ 'longRunning' => [ @@ -92,6 +164,16 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'backup.name', + 'fieldAccessors' => [ + 'getBackup', + 'getName', + ], + ], + ], ], 'UpdateBackupPlan' => [ 'longRunning' => [ @@ -102,6 +184,16 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'backup_plan.name', + 'fieldAccessors' => [ + 'getBackupPlan', + 'getName', + ], + ], + ], ], 'UpdateRestore' => [ 'longRunning' => [ @@ -112,6 +204,16 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'restore.name', + 'fieldAccessors' => [ + 'getRestore', + 'getName', + ], + ], + ], ], 'UpdateRestorePlan' => [ 'longRunning' => [ @@ -122,6 +224,88 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'restore_plan.name', + 'fieldAccessors' => [ + 'getRestorePlan', + 'getName', + ], + ], + ], + ], + 'GetBackup' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GkeBackup\V1\Backup', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetBackupPlan' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GkeBackup\V1\BackupPlan', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetRestore' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GkeBackup\V1\Restore', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetRestorePlan' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GkeBackup\V1\RestorePlan', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetVolumeBackup' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GkeBackup\V1\VolumeBackup', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetVolumeRestore' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GkeBackup\V1\VolumeRestore', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'ListBackupPlans' => [ 'pageStreaming' => [ @@ -132,6 +316,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getBackupPlans', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\GkeBackup\V1\ListBackupPlansResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'ListBackups' => [ 'pageStreaming' => [ @@ -142,6 +336,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getBackups', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\GkeBackup\V1\ListBackupsResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'ListRestorePlans' => [ 'pageStreaming' => [ @@ -152,6 +356,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getRestorePlans', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\GkeBackup\V1\ListRestorePlansResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'ListRestores' => [ 'pageStreaming' => [ @@ -162,6 +376,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getRestores', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\GkeBackup\V1\ListRestoresResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'ListVolumeBackups' => [ 'pageStreaming' => [ @@ -172,6 +396,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getVolumeBackups', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\GkeBackup\V1\ListVolumeBackupsResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'ListVolumeRestores' => [ 'pageStreaming' => [ @@ -182,6 +416,27 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getVolumeRestores', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\GkeBackup\V1\ListVolumeRestoresResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'templateMap' => [ + 'backup' => 'projects/{project}/locations/{location}/backupPlans/{backup_plan}/backups/{backup}', + 'backupPlan' => 'projects/{project}/locations/{location}/backupPlans/{backup_plan}', + 'cluster' => 'projects/{project}/locations/{location}/clusters/{cluster}', + 'cryptoKey' => 'projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}', + 'location' => 'projects/{project}/locations/{location}', + 'restore' => 'projects/{project}/locations/{location}/restorePlans/{restore_plan}/restores/{restore}', + 'restorePlan' => 'projects/{project}/locations/{location}/restorePlans/{restore_plan}', + 'volumeBackup' => 'projects/{project}/locations/{location}/backupPlans/{backup_plan}/backups/{backup}/volumeBackups/{volume_backup}', + 'volumeRestore' => 'projects/{project}/locations/{location}/restorePlans/{restore_plan}/restores/{restore}/volumeRestores/{volume_restore}', ], ], ], diff --git a/GkeBackup/tests/Unit/V1/Client/BackupForGKEClientTest.php b/GkeBackup/tests/Unit/V1/Client/BackupForGKEClientTest.php new file mode 100644 index 000000000000..238ee9c66858 --- /dev/null +++ b/GkeBackup/tests/Unit/V1/Client/BackupForGKEClientTest.php @@ -0,0 +1,2796 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return BackupForGKEClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new BackupForGKEClient($options); + } + + /** @test */ + public function createBackupTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createBackupTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $uid = 'uid115792'; + $manual = true; + $deleteLockDays = 1638724265; + $retainDays = 1380805807; + $allNamespaces = true; + $containsVolumeData = false; + $containsSecrets = false; + $stateReason = 'stateReason282113458'; + $resourceCount = 287552926; + $volumeCount = 1362665558; + $sizeBytes = 1796325715; + $etag = 'etag3123477'; + $description = 'description-1724546052'; + $podCount = 977657493; + $configBackupSizeBytes = 606785139; + $expectedResponse = new Backup(); + $expectedResponse->setName($name); + $expectedResponse->setUid($uid); + $expectedResponse->setManual($manual); + $expectedResponse->setDeleteLockDays($deleteLockDays); + $expectedResponse->setRetainDays($retainDays); + $expectedResponse->setAllNamespaces($allNamespaces); + $expectedResponse->setContainsVolumeData($containsVolumeData); + $expectedResponse->setContainsSecrets($containsSecrets); + $expectedResponse->setStateReason($stateReason); + $expectedResponse->setResourceCount($resourceCount); + $expectedResponse->setVolumeCount($volumeCount); + $expectedResponse->setSizeBytes($sizeBytes); + $expectedResponse->setEtag($etag); + $expectedResponse->setDescription($description); + $expectedResponse->setPodCount($podCount); + $expectedResponse->setConfigBackupSizeBytes($configBackupSizeBytes); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createBackupTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->backupPlanName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]'); + $request = (new CreateBackupRequest()) + ->setParent($formattedParent); + $response = $gapicClient->createBackup($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/CreateBackup', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createBackupTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createBackupExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createBackupTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->backupPlanName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]'); + $request = (new CreateBackupRequest()) + ->setParent($formattedParent); + $response = $gapicClient->createBackup($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createBackupTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createBackupPlanTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createBackupPlanTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $uid = 'uid115792'; + $description = 'description-1724546052'; + $cluster = 'cluster872092154'; + $etag = 'etag3123477'; + $deactivated = true; + $protectedPodCount = 1494678716; + $expectedResponse = new BackupPlan(); + $expectedResponse->setName($name); + $expectedResponse->setUid($uid); + $expectedResponse->setDescription($description); + $expectedResponse->setCluster($cluster); + $expectedResponse->setEtag($etag); + $expectedResponse->setDeactivated($deactivated); + $expectedResponse->setProtectedPodCount($protectedPodCount); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createBackupPlanTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $backupPlan = new BackupPlan(); + $backupPlanCluster = $gapicClient->clusterName('[PROJECT]', '[LOCATION]', '[CLUSTER]'); + $backupPlan->setCluster($backupPlanCluster); + $backupPlanId = 'backupPlanId-25762700'; + $request = (new CreateBackupPlanRequest()) + ->setParent($formattedParent) + ->setBackupPlan($backupPlan) + ->setBackupPlanId($backupPlanId); + $response = $gapicClient->createBackupPlan($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/CreateBackupPlan', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getBackupPlan(); + $this->assertProtobufEquals($backupPlan, $actualValue); + $actualValue = $actualApiRequestObject->getBackupPlanId(); + $this->assertProtobufEquals($backupPlanId, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createBackupPlanTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createBackupPlanExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createBackupPlanTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $backupPlan = new BackupPlan(); + $backupPlanCluster = $gapicClient->clusterName('[PROJECT]', '[LOCATION]', '[CLUSTER]'); + $backupPlan->setCluster($backupPlanCluster); + $backupPlanId = 'backupPlanId-25762700'; + $request = (new CreateBackupPlanRequest()) + ->setParent($formattedParent) + ->setBackupPlan($backupPlan) + ->setBackupPlanId($backupPlanId); + $response = $gapicClient->createBackupPlan($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createBackupPlanTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createRestoreTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createRestoreTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $uid = 'uid115792'; + $description = 'description-1724546052'; + $backup = 'backup-1396673086'; + $cluster = 'cluster872092154'; + $stateReason = 'stateReason282113458'; + $resourcesRestoredCount = 882879616; + $resourcesExcludedCount = 338652236; + $resourcesFailedCount = 217904743; + $volumesRestoredCount = 1005533068; + $etag = 'etag3123477'; + $expectedResponse = new Restore(); + $expectedResponse->setName($name); + $expectedResponse->setUid($uid); + $expectedResponse->setDescription($description); + $expectedResponse->setBackup($backup); + $expectedResponse->setCluster($cluster); + $expectedResponse->setStateReason($stateReason); + $expectedResponse->setResourcesRestoredCount($resourcesRestoredCount); + $expectedResponse->setResourcesExcludedCount($resourcesExcludedCount); + $expectedResponse->setResourcesFailedCount($resourcesFailedCount); + $expectedResponse->setVolumesRestoredCount($volumesRestoredCount); + $expectedResponse->setEtag($etag); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createRestoreTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->restorePlanName('[PROJECT]', '[LOCATION]', '[RESTORE_PLAN]'); + $restore = new Restore(); + $restoreBackup = $gapicClient->backupName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]', '[BACKUP]'); + $restore->setBackup($restoreBackup); + $restoreId = 'restoreId-1374819220'; + $request = (new CreateRestoreRequest()) + ->setParent($formattedParent) + ->setRestore($restore) + ->setRestoreId($restoreId); + $response = $gapicClient->createRestore($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/CreateRestore', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getRestore(); + $this->assertProtobufEquals($restore, $actualValue); + $actualValue = $actualApiRequestObject->getRestoreId(); + $this->assertProtobufEquals($restoreId, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createRestoreTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createRestoreExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createRestoreTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->restorePlanName('[PROJECT]', '[LOCATION]', '[RESTORE_PLAN]'); + $restore = new Restore(); + $restoreBackup = $gapicClient->backupName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]', '[BACKUP]'); + $restore->setBackup($restoreBackup); + $restoreId = 'restoreId-1374819220'; + $request = (new CreateRestoreRequest()) + ->setParent($formattedParent) + ->setRestore($restore) + ->setRestoreId($restoreId); + $response = $gapicClient->createRestore($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createRestoreTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createRestorePlanTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createRestorePlanTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $uid = 'uid115792'; + $description = 'description-1724546052'; + $backupPlan = 'backupPlan1119623046'; + $cluster = 'cluster872092154'; + $etag = 'etag3123477'; + $expectedResponse = new RestorePlan(); + $expectedResponse->setName($name); + $expectedResponse->setUid($uid); + $expectedResponse->setDescription($description); + $expectedResponse->setBackupPlan($backupPlan); + $expectedResponse->setCluster($cluster); + $expectedResponse->setEtag($etag); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createRestorePlanTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $restorePlan = new RestorePlan(); + $restorePlanBackupPlan = $gapicClient->backupPlanName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]'); + $restorePlan->setBackupPlan($restorePlanBackupPlan); + $restorePlanCluster = $gapicClient->clusterName('[PROJECT]', '[LOCATION]', '[CLUSTER]'); + $restorePlan->setCluster($restorePlanCluster); + $restorePlanRestoreConfig = new RestoreConfig(); + $restorePlan->setRestoreConfig($restorePlanRestoreConfig); + $restorePlanId = 'restorePlanId126727488'; + $request = (new CreateRestorePlanRequest()) + ->setParent($formattedParent) + ->setRestorePlan($restorePlan) + ->setRestorePlanId($restorePlanId); + $response = $gapicClient->createRestorePlan($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/CreateRestorePlan', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getRestorePlan(); + $this->assertProtobufEquals($restorePlan, $actualValue); + $actualValue = $actualApiRequestObject->getRestorePlanId(); + $this->assertProtobufEquals($restorePlanId, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createRestorePlanTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createRestorePlanExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createRestorePlanTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $restorePlan = new RestorePlan(); + $restorePlanBackupPlan = $gapicClient->backupPlanName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]'); + $restorePlan->setBackupPlan($restorePlanBackupPlan); + $restorePlanCluster = $gapicClient->clusterName('[PROJECT]', '[LOCATION]', '[CLUSTER]'); + $restorePlan->setCluster($restorePlanCluster); + $restorePlanRestoreConfig = new RestoreConfig(); + $restorePlan->setRestoreConfig($restorePlanRestoreConfig); + $restorePlanId = 'restorePlanId126727488'; + $request = (new CreateRestorePlanRequest()) + ->setParent($formattedParent) + ->setRestorePlan($restorePlan) + ->setRestorePlanId($restorePlanId); + $response = $gapicClient->createRestorePlan($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createRestorePlanTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteBackupTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteBackupTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new GPBEmpty(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/deleteBackupTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedName = $gapicClient->backupName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]', '[BACKUP]'); + $request = (new DeleteBackupRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteBackup($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/DeleteBackup', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteBackupTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteBackupExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteBackupTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->backupName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]', '[BACKUP]'); + $request = (new DeleteBackupRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteBackup($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteBackupTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteBackupPlanTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteBackupPlanTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new GPBEmpty(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/deleteBackupPlanTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedName = $gapicClient->backupPlanName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]'); + $request = (new DeleteBackupPlanRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteBackupPlan($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/DeleteBackupPlan', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteBackupPlanTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteBackupPlanExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteBackupPlanTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->backupPlanName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]'); + $request = (new DeleteBackupPlanRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteBackupPlan($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteBackupPlanTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteRestoreTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteRestoreTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new GPBEmpty(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/deleteRestoreTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedName = $gapicClient->restoreName('[PROJECT]', '[LOCATION]', '[RESTORE_PLAN]', '[RESTORE]'); + $request = (new DeleteRestoreRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteRestore($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/DeleteRestore', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteRestoreTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteRestoreExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteRestoreTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->restoreName('[PROJECT]', '[LOCATION]', '[RESTORE_PLAN]', '[RESTORE]'); + $request = (new DeleteRestoreRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteRestore($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteRestoreTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteRestorePlanTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteRestorePlanTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new GPBEmpty(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/deleteRestorePlanTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedName = $gapicClient->restorePlanName('[PROJECT]', '[LOCATION]', '[RESTORE_PLAN]'); + $request = (new DeleteRestorePlanRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteRestorePlan($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/DeleteRestorePlan', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteRestorePlanTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteRestorePlanExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteRestorePlanTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->restorePlanName('[PROJECT]', '[LOCATION]', '[RESTORE_PLAN]'); + $request = (new DeleteRestorePlanRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteRestorePlan($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteRestorePlanTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function getBackupTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $uid = 'uid115792'; + $manual = true; + $deleteLockDays = 1638724265; + $retainDays = 1380805807; + $allNamespaces = true; + $containsVolumeData = false; + $containsSecrets = false; + $stateReason = 'stateReason282113458'; + $resourceCount = 287552926; + $volumeCount = 1362665558; + $sizeBytes = 1796325715; + $etag = 'etag3123477'; + $description = 'description-1724546052'; + $podCount = 977657493; + $configBackupSizeBytes = 606785139; + $expectedResponse = new Backup(); + $expectedResponse->setName($name2); + $expectedResponse->setUid($uid); + $expectedResponse->setManual($manual); + $expectedResponse->setDeleteLockDays($deleteLockDays); + $expectedResponse->setRetainDays($retainDays); + $expectedResponse->setAllNamespaces($allNamespaces); + $expectedResponse->setContainsVolumeData($containsVolumeData); + $expectedResponse->setContainsSecrets($containsSecrets); + $expectedResponse->setStateReason($stateReason); + $expectedResponse->setResourceCount($resourceCount); + $expectedResponse->setVolumeCount($volumeCount); + $expectedResponse->setSizeBytes($sizeBytes); + $expectedResponse->setEtag($etag); + $expectedResponse->setDescription($description); + $expectedResponse->setPodCount($podCount); + $expectedResponse->setConfigBackupSizeBytes($configBackupSizeBytes); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->backupName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]', '[BACKUP]'); + $request = (new GetBackupRequest()) + ->setName($formattedName); + $response = $gapicClient->getBackup($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/GetBackup', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getBackupExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->backupName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]', '[BACKUP]'); + $request = (new GetBackupRequest()) + ->setName($formattedName); + try { + $gapicClient->getBackup($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getBackupPlanTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $uid = 'uid115792'; + $description = 'description-1724546052'; + $cluster = 'cluster872092154'; + $etag = 'etag3123477'; + $deactivated = true; + $protectedPodCount = 1494678716; + $expectedResponse = new BackupPlan(); + $expectedResponse->setName($name2); + $expectedResponse->setUid($uid); + $expectedResponse->setDescription($description); + $expectedResponse->setCluster($cluster); + $expectedResponse->setEtag($etag); + $expectedResponse->setDeactivated($deactivated); + $expectedResponse->setProtectedPodCount($protectedPodCount); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->backupPlanName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]'); + $request = (new GetBackupPlanRequest()) + ->setName($formattedName); + $response = $gapicClient->getBackupPlan($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/GetBackupPlan', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getBackupPlanExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->backupPlanName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]'); + $request = (new GetBackupPlanRequest()) + ->setName($formattedName); + try { + $gapicClient->getBackupPlan($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getRestoreTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $uid = 'uid115792'; + $description = 'description-1724546052'; + $backup = 'backup-1396673086'; + $cluster = 'cluster872092154'; + $stateReason = 'stateReason282113458'; + $resourcesRestoredCount = 882879616; + $resourcesExcludedCount = 338652236; + $resourcesFailedCount = 217904743; + $volumesRestoredCount = 1005533068; + $etag = 'etag3123477'; + $expectedResponse = new Restore(); + $expectedResponse->setName($name2); + $expectedResponse->setUid($uid); + $expectedResponse->setDescription($description); + $expectedResponse->setBackup($backup); + $expectedResponse->setCluster($cluster); + $expectedResponse->setStateReason($stateReason); + $expectedResponse->setResourcesRestoredCount($resourcesRestoredCount); + $expectedResponse->setResourcesExcludedCount($resourcesExcludedCount); + $expectedResponse->setResourcesFailedCount($resourcesFailedCount); + $expectedResponse->setVolumesRestoredCount($volumesRestoredCount); + $expectedResponse->setEtag($etag); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->restoreName('[PROJECT]', '[LOCATION]', '[RESTORE_PLAN]', '[RESTORE]'); + $request = (new GetRestoreRequest()) + ->setName($formattedName); + $response = $gapicClient->getRestore($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/GetRestore', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getRestoreExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->restoreName('[PROJECT]', '[LOCATION]', '[RESTORE_PLAN]', '[RESTORE]'); + $request = (new GetRestoreRequest()) + ->setName($formattedName); + try { + $gapicClient->getRestore($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getRestorePlanTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $uid = 'uid115792'; + $description = 'description-1724546052'; + $backupPlan = 'backupPlan1119623046'; + $cluster = 'cluster872092154'; + $etag = 'etag3123477'; + $expectedResponse = new RestorePlan(); + $expectedResponse->setName($name2); + $expectedResponse->setUid($uid); + $expectedResponse->setDescription($description); + $expectedResponse->setBackupPlan($backupPlan); + $expectedResponse->setCluster($cluster); + $expectedResponse->setEtag($etag); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->restorePlanName('[PROJECT]', '[LOCATION]', '[RESTORE_PLAN]'); + $request = (new GetRestorePlanRequest()) + ->setName($formattedName); + $response = $gapicClient->getRestorePlan($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/GetRestorePlan', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getRestorePlanExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->restorePlanName('[PROJECT]', '[LOCATION]', '[RESTORE_PLAN]'); + $request = (new GetRestorePlanRequest()) + ->setName($formattedName); + try { + $gapicClient->getRestorePlan($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getVolumeBackupTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $uid = 'uid115792'; + $volumeBackupHandle = 'volumeBackupHandle-2105959712'; + $storageBytes = 2035244455; + $diskSizeBytes = 275393905; + $stateMessage = 'stateMessage29641305'; + $etag = 'etag3123477'; + $expectedResponse = new VolumeBackup(); + $expectedResponse->setName($name2); + $expectedResponse->setUid($uid); + $expectedResponse->setVolumeBackupHandle($volumeBackupHandle); + $expectedResponse->setStorageBytes($storageBytes); + $expectedResponse->setDiskSizeBytes($diskSizeBytes); + $expectedResponse->setStateMessage($stateMessage); + $expectedResponse->setEtag($etag); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->volumeBackupName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]', '[BACKUP]', '[VOLUME_BACKUP]'); + $request = (new GetVolumeBackupRequest()) + ->setName($formattedName); + $response = $gapicClient->getVolumeBackup($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/GetVolumeBackup', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getVolumeBackupExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->volumeBackupName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]', '[BACKUP]', '[VOLUME_BACKUP]'); + $request = (new GetVolumeBackupRequest()) + ->setName($formattedName); + try { + $gapicClient->getVolumeBackup($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getVolumeRestoreTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $uid = 'uid115792'; + $volumeBackup = 'volumeBackup664943239'; + $volumeHandle = 'volumeHandle837038829'; + $stateMessage = 'stateMessage29641305'; + $etag = 'etag3123477'; + $expectedResponse = new VolumeRestore(); + $expectedResponse->setName($name2); + $expectedResponse->setUid($uid); + $expectedResponse->setVolumeBackup($volumeBackup); + $expectedResponse->setVolumeHandle($volumeHandle); + $expectedResponse->setStateMessage($stateMessage); + $expectedResponse->setEtag($etag); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->volumeRestoreName('[PROJECT]', '[LOCATION]', '[RESTORE_PLAN]', '[RESTORE]', '[VOLUME_RESTORE]'); + $request = (new GetVolumeRestoreRequest()) + ->setName($formattedName); + $response = $gapicClient->getVolumeRestore($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/GetVolumeRestore', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getVolumeRestoreExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->volumeRestoreName('[PROJECT]', '[LOCATION]', '[RESTORE_PLAN]', '[RESTORE]', '[VOLUME_RESTORE]'); + $request = (new GetVolumeRestoreRequest()) + ->setName($formattedName); + try { + $gapicClient->getVolumeRestore($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listBackupPlansTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $backupPlansElement = new BackupPlan(); + $backupPlans = [ + $backupPlansElement, + ]; + $expectedResponse = new ListBackupPlansResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setBackupPlans($backupPlans); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListBackupPlansRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listBackupPlans($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getBackupPlans()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/ListBackupPlans', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listBackupPlansExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListBackupPlansRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listBackupPlans($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listBackupsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $backupsElement = new Backup(); + $backups = [ + $backupsElement, + ]; + $expectedResponse = new ListBackupsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setBackups($backups); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->backupPlanName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]'); + $request = (new ListBackupsRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listBackups($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getBackups()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/ListBackups', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listBackupsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->backupPlanName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]'); + $request = (new ListBackupsRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listBackups($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listRestorePlansTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $restorePlansElement = new RestorePlan(); + $restorePlans = [ + $restorePlansElement, + ]; + $expectedResponse = new ListRestorePlansResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setRestorePlans($restorePlans); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListRestorePlansRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listRestorePlans($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getRestorePlans()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/ListRestorePlans', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listRestorePlansExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListRestorePlansRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listRestorePlans($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listRestoresTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $restoresElement = new Restore(); + $restores = [ + $restoresElement, + ]; + $expectedResponse = new ListRestoresResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setRestores($restores); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->restorePlanName('[PROJECT]', '[LOCATION]', '[RESTORE_PLAN]'); + $request = (new ListRestoresRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listRestores($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getRestores()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/ListRestores', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listRestoresExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->restorePlanName('[PROJECT]', '[LOCATION]', '[RESTORE_PLAN]'); + $request = (new ListRestoresRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listRestores($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listVolumeBackupsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $volumeBackupsElement = new VolumeBackup(); + $volumeBackups = [ + $volumeBackupsElement, + ]; + $expectedResponse = new ListVolumeBackupsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setVolumeBackups($volumeBackups); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->backupName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]', '[BACKUP]'); + $request = (new ListVolumeBackupsRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listVolumeBackups($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getVolumeBackups()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/ListVolumeBackups', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listVolumeBackupsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->backupName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]', '[BACKUP]'); + $request = (new ListVolumeBackupsRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listVolumeBackups($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listVolumeRestoresTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $volumeRestoresElement = new VolumeRestore(); + $volumeRestores = [ + $volumeRestoresElement, + ]; + $expectedResponse = new ListVolumeRestoresResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setVolumeRestores($volumeRestores); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->restoreName('[PROJECT]', '[LOCATION]', '[RESTORE_PLAN]', '[RESTORE]'); + $request = (new ListVolumeRestoresRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listVolumeRestores($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getVolumeRestores()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/ListVolumeRestores', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listVolumeRestoresExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->restoreName('[PROJECT]', '[LOCATION]', '[RESTORE_PLAN]', '[RESTORE]'); + $request = (new ListVolumeRestoresRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listVolumeRestores($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function updateBackupTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateBackupTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $uid = 'uid115792'; + $manual = true; + $deleteLockDays = 1638724265; + $retainDays = 1380805807; + $allNamespaces = true; + $containsVolumeData = false; + $containsSecrets = false; + $stateReason = 'stateReason282113458'; + $resourceCount = 287552926; + $volumeCount = 1362665558; + $sizeBytes = 1796325715; + $etag = 'etag3123477'; + $description = 'description-1724546052'; + $podCount = 977657493; + $configBackupSizeBytes = 606785139; + $expectedResponse = new Backup(); + $expectedResponse->setName($name); + $expectedResponse->setUid($uid); + $expectedResponse->setManual($manual); + $expectedResponse->setDeleteLockDays($deleteLockDays); + $expectedResponse->setRetainDays($retainDays); + $expectedResponse->setAllNamespaces($allNamespaces); + $expectedResponse->setContainsVolumeData($containsVolumeData); + $expectedResponse->setContainsSecrets($containsSecrets); + $expectedResponse->setStateReason($stateReason); + $expectedResponse->setResourceCount($resourceCount); + $expectedResponse->setVolumeCount($volumeCount); + $expectedResponse->setSizeBytes($sizeBytes); + $expectedResponse->setEtag($etag); + $expectedResponse->setDescription($description); + $expectedResponse->setPodCount($podCount); + $expectedResponse->setConfigBackupSizeBytes($configBackupSizeBytes); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/updateBackupTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $backup = new Backup(); + $request = (new UpdateBackupRequest()) + ->setBackup($backup); + $response = $gapicClient->updateBackup($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/UpdateBackup', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getBackup(); + $this->assertProtobufEquals($backup, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateBackupTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateBackupExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateBackupTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $backup = new Backup(); + $request = (new UpdateBackupRequest()) + ->setBackup($backup); + $response = $gapicClient->updateBackup($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateBackupTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateBackupPlanTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateBackupPlanTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $uid = 'uid115792'; + $description = 'description-1724546052'; + $cluster = 'cluster872092154'; + $etag = 'etag3123477'; + $deactivated = true; + $protectedPodCount = 1494678716; + $expectedResponse = new BackupPlan(); + $expectedResponse->setName($name); + $expectedResponse->setUid($uid); + $expectedResponse->setDescription($description); + $expectedResponse->setCluster($cluster); + $expectedResponse->setEtag($etag); + $expectedResponse->setDeactivated($deactivated); + $expectedResponse->setProtectedPodCount($protectedPodCount); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/updateBackupPlanTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $backupPlan = new BackupPlan(); + $backupPlanCluster = $gapicClient->clusterName('[PROJECT]', '[LOCATION]', '[CLUSTER]'); + $backupPlan->setCluster($backupPlanCluster); + $request = (new UpdateBackupPlanRequest()) + ->setBackupPlan($backupPlan); + $response = $gapicClient->updateBackupPlan($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/UpdateBackupPlan', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getBackupPlan(); + $this->assertProtobufEquals($backupPlan, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateBackupPlanTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateBackupPlanExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateBackupPlanTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $backupPlan = new BackupPlan(); + $backupPlanCluster = $gapicClient->clusterName('[PROJECT]', '[LOCATION]', '[CLUSTER]'); + $backupPlan->setCluster($backupPlanCluster); + $request = (new UpdateBackupPlanRequest()) + ->setBackupPlan($backupPlan); + $response = $gapicClient->updateBackupPlan($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateBackupPlanTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateRestoreTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateRestoreTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $uid = 'uid115792'; + $description = 'description-1724546052'; + $backup = 'backup-1396673086'; + $cluster = 'cluster872092154'; + $stateReason = 'stateReason282113458'; + $resourcesRestoredCount = 882879616; + $resourcesExcludedCount = 338652236; + $resourcesFailedCount = 217904743; + $volumesRestoredCount = 1005533068; + $etag = 'etag3123477'; + $expectedResponse = new Restore(); + $expectedResponse->setName($name); + $expectedResponse->setUid($uid); + $expectedResponse->setDescription($description); + $expectedResponse->setBackup($backup); + $expectedResponse->setCluster($cluster); + $expectedResponse->setStateReason($stateReason); + $expectedResponse->setResourcesRestoredCount($resourcesRestoredCount); + $expectedResponse->setResourcesExcludedCount($resourcesExcludedCount); + $expectedResponse->setResourcesFailedCount($resourcesFailedCount); + $expectedResponse->setVolumesRestoredCount($volumesRestoredCount); + $expectedResponse->setEtag($etag); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/updateRestoreTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $restore = new Restore(); + $restoreBackup = $gapicClient->backupName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]', '[BACKUP]'); + $restore->setBackup($restoreBackup); + $request = (new UpdateRestoreRequest()) + ->setRestore($restore); + $response = $gapicClient->updateRestore($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/UpdateRestore', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getRestore(); + $this->assertProtobufEquals($restore, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateRestoreTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateRestoreExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateRestoreTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $restore = new Restore(); + $restoreBackup = $gapicClient->backupName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]', '[BACKUP]'); + $restore->setBackup($restoreBackup); + $request = (new UpdateRestoreRequest()) + ->setRestore($restore); + $response = $gapicClient->updateRestore($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateRestoreTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateRestorePlanTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateRestorePlanTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $uid = 'uid115792'; + $description = 'description-1724546052'; + $backupPlan = 'backupPlan1119623046'; + $cluster = 'cluster872092154'; + $etag = 'etag3123477'; + $expectedResponse = new RestorePlan(); + $expectedResponse->setName($name); + $expectedResponse->setUid($uid); + $expectedResponse->setDescription($description); + $expectedResponse->setBackupPlan($backupPlan); + $expectedResponse->setCluster($cluster); + $expectedResponse->setEtag($etag); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/updateRestorePlanTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $restorePlan = new RestorePlan(); + $restorePlanBackupPlan = $gapicClient->backupPlanName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]'); + $restorePlan->setBackupPlan($restorePlanBackupPlan); + $restorePlanCluster = $gapicClient->clusterName('[PROJECT]', '[LOCATION]', '[CLUSTER]'); + $restorePlan->setCluster($restorePlanCluster); + $restorePlanRestoreConfig = new RestoreConfig(); + $restorePlan->setRestoreConfig($restorePlanRestoreConfig); + $request = (new UpdateRestorePlanRequest()) + ->setRestorePlan($restorePlan); + $response = $gapicClient->updateRestorePlan($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/UpdateRestorePlan', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getRestorePlan(); + $this->assertProtobufEquals($restorePlan, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateRestorePlanTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateRestorePlanExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateRestorePlanTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $restorePlan = new RestorePlan(); + $restorePlanBackupPlan = $gapicClient->backupPlanName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]'); + $restorePlan->setBackupPlan($restorePlanBackupPlan); + $restorePlanCluster = $gapicClient->clusterName('[PROJECT]', '[LOCATION]', '[CLUSTER]'); + $restorePlan->setCluster($restorePlanCluster); + $restorePlanRestoreConfig = new RestoreConfig(); + $restorePlan->setRestoreConfig($restorePlanRestoreConfig); + $request = (new UpdateRestorePlanRequest()) + ->setRestorePlan($restorePlan); + $response = $gapicClient->updateRestorePlan($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateRestorePlanTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createBackupAsyncTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createBackupTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $uid = 'uid115792'; + $manual = true; + $deleteLockDays = 1638724265; + $retainDays = 1380805807; + $allNamespaces = true; + $containsVolumeData = false; + $containsSecrets = false; + $stateReason = 'stateReason282113458'; + $resourceCount = 287552926; + $volumeCount = 1362665558; + $sizeBytes = 1796325715; + $etag = 'etag3123477'; + $description = 'description-1724546052'; + $podCount = 977657493; + $configBackupSizeBytes = 606785139; + $expectedResponse = new Backup(); + $expectedResponse->setName($name); + $expectedResponse->setUid($uid); + $expectedResponse->setManual($manual); + $expectedResponse->setDeleteLockDays($deleteLockDays); + $expectedResponse->setRetainDays($retainDays); + $expectedResponse->setAllNamespaces($allNamespaces); + $expectedResponse->setContainsVolumeData($containsVolumeData); + $expectedResponse->setContainsSecrets($containsSecrets); + $expectedResponse->setStateReason($stateReason); + $expectedResponse->setResourceCount($resourceCount); + $expectedResponse->setVolumeCount($volumeCount); + $expectedResponse->setSizeBytes($sizeBytes); + $expectedResponse->setEtag($etag); + $expectedResponse->setDescription($description); + $expectedResponse->setPodCount($podCount); + $expectedResponse->setConfigBackupSizeBytes($configBackupSizeBytes); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createBackupTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->backupPlanName('[PROJECT]', '[LOCATION]', '[BACKUP_PLAN]'); + $request = (new CreateBackupRequest()) + ->setParent($formattedParent); + $response = $gapicClient->createBackupAsync($request)->wait(); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkebackup.v1.BackupForGKE/CreateBackup', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createBackupTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } +} diff --git a/GkeConnectGateway/samples/V1beta1/GatewayServiceClient/delete_resource.php b/GkeConnectGateway/samples/V1beta1/GatewayServiceClient/delete_resource.php index 60f6107bd37f..4cbd1d6b4742 100644 --- a/GkeConnectGateway/samples/V1beta1/GatewayServiceClient/delete_resource.php +++ b/GkeConnectGateway/samples/V1beta1/GatewayServiceClient/delete_resource.php @@ -25,7 +25,7 @@ // [START connectgateway_v1beta1_generated_GatewayService_DeleteResource_sync] use Google\ApiCore\ApiException; use Google\Api\HttpBody; -use Google\Cloud\GkeConnect\Gateway\V1beta1\GatewayServiceClient; +use Google\Cloud\GkeConnect\Gateway\V1beta1\Client\GatewayServiceClient; /** * DeleteResource performs an HTTP DELETE on the Kubernetes API Server. @@ -41,10 +41,13 @@ function delete_resource_sample(): void // Create a client. $gatewayServiceClient = new GatewayServiceClient(); + // Prepare the request message. + $request = new HttpBody(); + // Call the API and handle any network failures. try { /** @var HttpBody $response */ - $response = $gatewayServiceClient->deleteResource(); + $response = $gatewayServiceClient->deleteResource($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeConnectGateway/samples/V1beta1/GatewayServiceClient/get_resource.php b/GkeConnectGateway/samples/V1beta1/GatewayServiceClient/get_resource.php index 7d3e073f29f9..37a91d8e8256 100644 --- a/GkeConnectGateway/samples/V1beta1/GatewayServiceClient/get_resource.php +++ b/GkeConnectGateway/samples/V1beta1/GatewayServiceClient/get_resource.php @@ -25,7 +25,7 @@ // [START connectgateway_v1beta1_generated_GatewayService_GetResource_sync] use Google\ApiCore\ApiException; use Google\Api\HttpBody; -use Google\Cloud\GkeConnect\Gateway\V1beta1\GatewayServiceClient; +use Google\Cloud\GkeConnect\Gateway\V1beta1\Client\GatewayServiceClient; /** * GetResource performs an HTTP GET request on the Kubernetes API Server. @@ -41,10 +41,13 @@ function get_resource_sample(): void // Create a client. $gatewayServiceClient = new GatewayServiceClient(); + // Prepare the request message. + $request = new HttpBody(); + // Call the API and handle any network failures. try { /** @var HttpBody $response */ - $response = $gatewayServiceClient->getResource(); + $response = $gatewayServiceClient->getResource($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeConnectGateway/samples/V1beta1/GatewayServiceClient/patch_resource.php b/GkeConnectGateway/samples/V1beta1/GatewayServiceClient/patch_resource.php index 8eae540f1a74..f53a62aa8f8b 100644 --- a/GkeConnectGateway/samples/V1beta1/GatewayServiceClient/patch_resource.php +++ b/GkeConnectGateway/samples/V1beta1/GatewayServiceClient/patch_resource.php @@ -25,7 +25,7 @@ // [START connectgateway_v1beta1_generated_GatewayService_PatchResource_sync] use Google\ApiCore\ApiException; use Google\Api\HttpBody; -use Google\Cloud\GkeConnect\Gateway\V1beta1\GatewayServiceClient; +use Google\Cloud\GkeConnect\Gateway\V1beta1\Client\GatewayServiceClient; /** * PatchResource performs an HTTP PATCH on the Kubernetes API Server. @@ -41,10 +41,13 @@ function patch_resource_sample(): void // Create a client. $gatewayServiceClient = new GatewayServiceClient(); + // Prepare the request message. + $request = new HttpBody(); + // Call the API and handle any network failures. try { /** @var HttpBody $response */ - $response = $gatewayServiceClient->patchResource(); + $response = $gatewayServiceClient->patchResource($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeConnectGateway/samples/V1beta1/GatewayServiceClient/post_resource.php b/GkeConnectGateway/samples/V1beta1/GatewayServiceClient/post_resource.php index 4ca1aae89c85..1209b4ce0b2f 100644 --- a/GkeConnectGateway/samples/V1beta1/GatewayServiceClient/post_resource.php +++ b/GkeConnectGateway/samples/V1beta1/GatewayServiceClient/post_resource.php @@ -25,7 +25,7 @@ // [START connectgateway_v1beta1_generated_GatewayService_PostResource_sync] use Google\ApiCore\ApiException; use Google\Api\HttpBody; -use Google\Cloud\GkeConnect\Gateway\V1beta1\GatewayServiceClient; +use Google\Cloud\GkeConnect\Gateway\V1beta1\Client\GatewayServiceClient; /** * PostResource performs an HTTP POST on the Kubernetes API Server. @@ -41,10 +41,13 @@ function post_resource_sample(): void // Create a client. $gatewayServiceClient = new GatewayServiceClient(); + // Prepare the request message. + $request = new HttpBody(); + // Call the API and handle any network failures. try { /** @var HttpBody $response */ - $response = $gatewayServiceClient->postResource(); + $response = $gatewayServiceClient->postResource($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeConnectGateway/samples/V1beta1/GatewayServiceClient/put_resource.php b/GkeConnectGateway/samples/V1beta1/GatewayServiceClient/put_resource.php index 4d57f6b652b1..7a92210d63f4 100644 --- a/GkeConnectGateway/samples/V1beta1/GatewayServiceClient/put_resource.php +++ b/GkeConnectGateway/samples/V1beta1/GatewayServiceClient/put_resource.php @@ -25,7 +25,7 @@ // [START connectgateway_v1beta1_generated_GatewayService_PutResource_sync] use Google\ApiCore\ApiException; use Google\Api\HttpBody; -use Google\Cloud\GkeConnect\Gateway\V1beta1\GatewayServiceClient; +use Google\Cloud\GkeConnect\Gateway\V1beta1\Client\GatewayServiceClient; /** * PutResource performs an HTTP PUT on the Kubernetes API Server. @@ -41,10 +41,13 @@ function put_resource_sample(): void // Create a client. $gatewayServiceClient = new GatewayServiceClient(); + // Prepare the request message. + $request = new HttpBody(); + // Call the API and handle any network failures. try { /** @var HttpBody $response */ - $response = $gatewayServiceClient->putResource(); + $response = $gatewayServiceClient->putResource($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeConnectGateway/src/V1beta1/Client/BaseClient/GatewayServiceBaseClient.php b/GkeConnectGateway/src/V1beta1/Client/BaseClient/GatewayServiceBaseClient.php new file mode 100644 index 000000000000..0943657e4764 --- /dev/null +++ b/GkeConnectGateway/src/V1beta1/Client/BaseClient/GatewayServiceBaseClient.php @@ -0,0 +1,304 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/gateway_service_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/gateway_service_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/gateway_service_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/gateway_service_rest_client_config.php', + ], + ], + ]; + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'connectgateway.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + * + * @experimental + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * DeleteResource performs an HTTP DELETE on the Kubernetes API Server. + * + * The async variant is {@see self::deleteResourceAsync()} . + * + * @param HttpBody $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return HttpBody + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function deleteResource(HttpBody $request, array $callOptions = []): HttpBody + { + return $this->startApiCall('DeleteResource', $request, $callOptions)->wait(); + } + + /** + * GetResource performs an HTTP GET request on the Kubernetes API Server. + * + * The async variant is {@see self::getResourceAsync()} . + * + * @param HttpBody $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return HttpBody + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function getResource(HttpBody $request, array $callOptions = []): HttpBody + { + return $this->startApiCall('GetResource', $request, $callOptions)->wait(); + } + + /** + * PatchResource performs an HTTP PATCH on the Kubernetes API Server. + * + * The async variant is {@see self::patchResourceAsync()} . + * + * @param HttpBody $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return HttpBody + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function patchResource(HttpBody $request, array $callOptions = []): HttpBody + { + return $this->startApiCall('PatchResource', $request, $callOptions)->wait(); + } + + /** + * PostResource performs an HTTP POST on the Kubernetes API Server. + * + * The async variant is {@see self::postResourceAsync()} . + * + * @param HttpBody $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return HttpBody + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function postResource(HttpBody $request, array $callOptions = []): HttpBody + { + return $this->startApiCall('PostResource', $request, $callOptions)->wait(); + } + + /** + * PutResource performs an HTTP PUT on the Kubernetes API Server. + * + * The async variant is {@see self::putResourceAsync()} . + * + * @param HttpBody $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return HttpBody + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function putResource(HttpBody $request, array $callOptions = []): HttpBody + { + return $this->startApiCall('PutResource', $request, $callOptions)->wait(); + } +} diff --git a/GkeConnectGateway/src/V1beta1/Client/GatewayServiceClient.php b/GkeConnectGateway/src/V1beta1/Client/GatewayServiceClient.php new file mode 100644 index 000000000000..769dad76db63 --- /dev/null +++ b/GkeConnectGateway/src/V1beta1/Client/GatewayServiceClient.php @@ -0,0 +1,42 @@ + [ - 'google.cloud.gkeconnect.gateway.v1beta1.GatewayService' => [], + 'google.cloud.gkeconnect.gateway.v1beta1.GatewayService' => [ + 'DeleteResource' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Api\HttpBody', + ], + 'GetResource' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Api\HttpBody', + ], + 'PatchResource' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Api\HttpBody', + ], + 'PostResource' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Api\HttpBody', + ], + 'PutResource' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Api\HttpBody', + ], + ], ], ]; diff --git a/GkeConnectGateway/tests/Unit/V1beta1/Client/GatewayServiceClientTest.php b/GkeConnectGateway/tests/Unit/V1beta1/Client/GatewayServiceClientTest.php new file mode 100644 index 000000000000..ae83ba4026ac --- /dev/null +++ b/GkeConnectGateway/tests/Unit/V1beta1/Client/GatewayServiceClientTest.php @@ -0,0 +1,377 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return GatewayServiceClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new GatewayServiceClient($options); + } + + /** @test */ + public function deleteResourceTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $contentType2 = 'contentType2540291827'; + $data2 = '-35'; + $expectedResponse = new HttpBody(); + $expectedResponse->setContentType($contentType2); + $expectedResponse->setData($data2); + $transport->addResponse($expectedResponse); + $request = new HttpBody(); + $response = $gapicClient->deleteResource($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkeconnect.gateway.v1beta1.GatewayService/DeleteResource', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function deleteResourceExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + $request = new HttpBody(); + try { + $gapicClient->deleteResource($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getResourceTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $contentType2 = 'contentType2540291827'; + $data2 = '-35'; + $expectedResponse = new HttpBody(); + $expectedResponse->setContentType($contentType2); + $expectedResponse->setData($data2); + $transport->addResponse($expectedResponse); + $request = new HttpBody(); + $response = $gapicClient->getResource($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkeconnect.gateway.v1beta1.GatewayService/GetResource', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getResourceExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + $request = new HttpBody(); + try { + $gapicClient->getResource($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function patchResourceTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $contentType2 = 'contentType2540291827'; + $data2 = '-35'; + $expectedResponse = new HttpBody(); + $expectedResponse->setContentType($contentType2); + $expectedResponse->setData($data2); + $transport->addResponse($expectedResponse); + $request = new HttpBody(); + $response = $gapicClient->patchResource($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkeconnect.gateway.v1beta1.GatewayService/PatchResource', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function patchResourceExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + $request = new HttpBody(); + try { + $gapicClient->patchResource($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function postResourceTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $contentType2 = 'contentType2540291827'; + $data2 = '-35'; + $expectedResponse = new HttpBody(); + $expectedResponse->setContentType($contentType2); + $expectedResponse->setData($data2); + $transport->addResponse($expectedResponse); + $request = new HttpBody(); + $response = $gapicClient->postResource($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkeconnect.gateway.v1beta1.GatewayService/PostResource', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function postResourceExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + $request = new HttpBody(); + try { + $gapicClient->postResource($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function putResourceTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $contentType2 = 'contentType2540291827'; + $data2 = '-35'; + $expectedResponse = new HttpBody(); + $expectedResponse->setContentType($contentType2); + $expectedResponse->setData($data2); + $transport->addResponse($expectedResponse); + $request = new HttpBody(); + $response = $gapicClient->putResource($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkeconnect.gateway.v1beta1.GatewayService/PutResource', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function putResourceExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + $request = new HttpBody(); + try { + $gapicClient->putResource($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function deleteResourceAsyncTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $contentType2 = 'contentType2540291827'; + $data2 = '-35'; + $expectedResponse = new HttpBody(); + $expectedResponse->setContentType($contentType2); + $expectedResponse->setData($data2); + $transport->addResponse($expectedResponse); + $request = new HttpBody(); + $response = $gapicClient->deleteResourceAsync($request)->wait(); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkeconnect.gateway.v1beta1.GatewayService/DeleteResource', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } +} diff --git a/GkeMultiCloud/samples/V1/AttachedClustersClient/create_attached_cluster.php b/GkeMultiCloud/samples/V1/AttachedClustersClient/create_attached_cluster.php index ec1b428a3029..9602d94ed329 100644 --- a/GkeMultiCloud/samples/V1/AttachedClustersClient/create_attached_cluster.php +++ b/GkeMultiCloud/samples/V1/AttachedClustersClient/create_attached_cluster.php @@ -26,8 +26,9 @@ use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; use Google\Cloud\GkeMultiCloud\V1\AttachedCluster; -use Google\Cloud\GkeMultiCloud\V1\AttachedClustersClient; use Google\Cloud\GkeMultiCloud\V1\AttachedOidcConfig; +use Google\Cloud\GkeMultiCloud\V1\Client\AttachedClustersClient; +use Google\Cloud\GkeMultiCloud\V1\CreateAttachedClusterRequest; use Google\Cloud\GkeMultiCloud\V1\Fleet; use Google\Rpc\Status; @@ -82,7 +83,7 @@ function create_attached_cluster_sample( // Create a client. $attachedClustersClient = new AttachedClustersClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $attachedClusterOidcConfig = new AttachedOidcConfig(); $attachedClusterFleet = (new Fleet()) ->setProject($attachedClusterFleetProject); @@ -91,15 +92,15 @@ function create_attached_cluster_sample( ->setPlatformVersion($attachedClusterPlatformVersion) ->setDistribution($attachedClusterDistribution) ->setFleet($attachedClusterFleet); + $request = (new CreateAttachedClusterRequest()) + ->setParent($formattedParent) + ->setAttachedCluster($attachedCluster) + ->setAttachedClusterId($attachedClusterId); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $attachedClustersClient->createAttachedCluster( - $formattedParent, - $attachedCluster, - $attachedClusterId - ); + $response = $attachedClustersClient->createAttachedCluster($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeMultiCloud/samples/V1/AttachedClustersClient/delete_attached_cluster.php b/GkeMultiCloud/samples/V1/AttachedClustersClient/delete_attached_cluster.php index b9225a8c0980..ceab2cdb831d 100644 --- a/GkeMultiCloud/samples/V1/AttachedClustersClient/delete_attached_cluster.php +++ b/GkeMultiCloud/samples/V1/AttachedClustersClient/delete_attached_cluster.php @@ -25,7 +25,8 @@ // [START gkemulticloud_v1_generated_AttachedClusters_DeleteAttachedCluster_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\GkeMultiCloud\V1\AttachedClustersClient; +use Google\Cloud\GkeMultiCloud\V1\Client\AttachedClustersClient; +use Google\Cloud\GkeMultiCloud\V1\DeleteAttachedClusterRequest; use Google\Rpc\Status; /** @@ -51,10 +52,14 @@ function delete_attached_cluster_sample(string $formattedName): void // Create a client. $attachedClustersClient = new AttachedClustersClient(); + // Prepare the request message. + $request = (new DeleteAttachedClusterRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $attachedClustersClient->deleteAttachedCluster($formattedName); + $response = $attachedClustersClient->deleteAttachedCluster($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeMultiCloud/samples/V1/AttachedClustersClient/generate_attached_cluster_install_manifest.php b/GkeMultiCloud/samples/V1/AttachedClustersClient/generate_attached_cluster_install_manifest.php index 453b1092b933..6bbdc89eb690 100644 --- a/GkeMultiCloud/samples/V1/AttachedClustersClient/generate_attached_cluster_install_manifest.php +++ b/GkeMultiCloud/samples/V1/AttachedClustersClient/generate_attached_cluster_install_manifest.php @@ -24,7 +24,8 @@ // [START gkemulticloud_v1_generated_AttachedClusters_GenerateAttachedClusterInstallManifest_sync] use Google\ApiCore\ApiException; -use Google\Cloud\GkeMultiCloud\V1\AttachedClustersClient; +use Google\Cloud\GkeMultiCloud\V1\Client\AttachedClustersClient; +use Google\Cloud\GkeMultiCloud\V1\GenerateAttachedClusterInstallManifestRequest; use Google\Cloud\GkeMultiCloud\V1\GenerateAttachedClusterInstallManifestResponse; /** @@ -68,14 +69,16 @@ function generate_attached_cluster_install_manifest_sample( // Create a client. $attachedClustersClient = new AttachedClustersClient(); + // Prepare the request message. + $request = (new GenerateAttachedClusterInstallManifestRequest()) + ->setParent($formattedParent) + ->setAttachedClusterId($attachedClusterId) + ->setPlatformVersion($platformVersion); + // Call the API and handle any network failures. try { /** @var GenerateAttachedClusterInstallManifestResponse $response */ - $response = $attachedClustersClient->generateAttachedClusterInstallManifest( - $formattedParent, - $attachedClusterId, - $platformVersion - ); + $response = $attachedClustersClient->generateAttachedClusterInstallManifest($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeMultiCloud/samples/V1/AttachedClustersClient/get_attached_cluster.php b/GkeMultiCloud/samples/V1/AttachedClustersClient/get_attached_cluster.php index 37222ce39e70..f14454ffd819 100644 --- a/GkeMultiCloud/samples/V1/AttachedClustersClient/get_attached_cluster.php +++ b/GkeMultiCloud/samples/V1/AttachedClustersClient/get_attached_cluster.php @@ -25,7 +25,8 @@ // [START gkemulticloud_v1_generated_AttachedClusters_GetAttachedCluster_sync] use Google\ApiCore\ApiException; use Google\Cloud\GkeMultiCloud\V1\AttachedCluster; -use Google\Cloud\GkeMultiCloud\V1\AttachedClustersClient; +use Google\Cloud\GkeMultiCloud\V1\Client\AttachedClustersClient; +use Google\Cloud\GkeMultiCloud\V1\GetAttachedClusterRequest; /** * Describes a specific @@ -47,10 +48,14 @@ function get_attached_cluster_sample(string $formattedName): void // Create a client. $attachedClustersClient = new AttachedClustersClient(); + // Prepare the request message. + $request = (new GetAttachedClusterRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var AttachedCluster $response */ - $response = $attachedClustersClient->getAttachedCluster($formattedName); + $response = $attachedClustersClient->getAttachedCluster($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeMultiCloud/samples/V1/AttachedClustersClient/get_attached_server_config.php b/GkeMultiCloud/samples/V1/AttachedClustersClient/get_attached_server_config.php index 44cc44fa2497..b749472446f5 100644 --- a/GkeMultiCloud/samples/V1/AttachedClustersClient/get_attached_server_config.php +++ b/GkeMultiCloud/samples/V1/AttachedClustersClient/get_attached_server_config.php @@ -24,8 +24,9 @@ // [START gkemulticloud_v1_generated_AttachedClusters_GetAttachedServerConfig_sync] use Google\ApiCore\ApiException; -use Google\Cloud\GkeMultiCloud\V1\AttachedClustersClient; use Google\Cloud\GkeMultiCloud\V1\AttachedServerConfig; +use Google\Cloud\GkeMultiCloud\V1\Client\AttachedClustersClient; +use Google\Cloud\GkeMultiCloud\V1\GetAttachedServerConfigRequest; /** * Returns information, such as supported Kubernetes versions, on a given @@ -47,10 +48,14 @@ function get_attached_server_config_sample(string $formattedName): void // Create a client. $attachedClustersClient = new AttachedClustersClient(); + // Prepare the request message. + $request = (new GetAttachedServerConfigRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var AttachedServerConfig $response */ - $response = $attachedClustersClient->getAttachedServerConfig($formattedName); + $response = $attachedClustersClient->getAttachedServerConfig($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeMultiCloud/samples/V1/AttachedClustersClient/import_attached_cluster.php b/GkeMultiCloud/samples/V1/AttachedClustersClient/import_attached_cluster.php index 59c385b8c57e..1bac2a21595f 100644 --- a/GkeMultiCloud/samples/V1/AttachedClustersClient/import_attached_cluster.php +++ b/GkeMultiCloud/samples/V1/AttachedClustersClient/import_attached_cluster.php @@ -26,7 +26,8 @@ use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; use Google\Cloud\GkeMultiCloud\V1\AttachedCluster; -use Google\Cloud\GkeMultiCloud\V1\AttachedClustersClient; +use Google\Cloud\GkeMultiCloud\V1\Client\AttachedClustersClient; +use Google\Cloud\GkeMultiCloud\V1\ImportAttachedClusterRequest; use Google\Rpc\Status; /** @@ -69,15 +70,17 @@ function import_attached_cluster_sample( // Create a client. $attachedClustersClient = new AttachedClustersClient(); + // Prepare the request message. + $request = (new ImportAttachedClusterRequest()) + ->setParent($formattedParent) + ->setFleetMembership($fleetMembership) + ->setPlatformVersion($platformVersion) + ->setDistribution($distribution); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $attachedClustersClient->importAttachedCluster( - $formattedParent, - $fleetMembership, - $platformVersion, - $distribution - ); + $response = $attachedClustersClient->importAttachedCluster($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeMultiCloud/samples/V1/AttachedClustersClient/list_attached_clusters.php b/GkeMultiCloud/samples/V1/AttachedClustersClient/list_attached_clusters.php index 240b6297facd..85e1777824a1 100644 --- a/GkeMultiCloud/samples/V1/AttachedClustersClient/list_attached_clusters.php +++ b/GkeMultiCloud/samples/V1/AttachedClustersClient/list_attached_clusters.php @@ -26,7 +26,8 @@ use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; use Google\Cloud\GkeMultiCloud\V1\AttachedCluster; -use Google\Cloud\GkeMultiCloud\V1\AttachedClustersClient; +use Google\Cloud\GkeMultiCloud\V1\Client\AttachedClustersClient; +use Google\Cloud\GkeMultiCloud\V1\ListAttachedClustersRequest; /** * Lists all [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] @@ -46,10 +47,14 @@ function list_attached_clusters_sample(string $formattedParent): void // Create a client. $attachedClustersClient = new AttachedClustersClient(); + // Prepare the request message. + $request = (new ListAttachedClustersRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $attachedClustersClient->listAttachedClusters($formattedParent); + $response = $attachedClustersClient->listAttachedClusters($request); /** @var AttachedCluster $element */ foreach ($response as $element) { diff --git a/GkeMultiCloud/samples/V1/AttachedClustersClient/update_attached_cluster.php b/GkeMultiCloud/samples/V1/AttachedClustersClient/update_attached_cluster.php index 0675297730e3..648a7a15e607 100644 --- a/GkeMultiCloud/samples/V1/AttachedClustersClient/update_attached_cluster.php +++ b/GkeMultiCloud/samples/V1/AttachedClustersClient/update_attached_cluster.php @@ -26,9 +26,10 @@ use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; use Google\Cloud\GkeMultiCloud\V1\AttachedCluster; -use Google\Cloud\GkeMultiCloud\V1\AttachedClustersClient; use Google\Cloud\GkeMultiCloud\V1\AttachedOidcConfig; +use Google\Cloud\GkeMultiCloud\V1\Client\AttachedClustersClient; use Google\Cloud\GkeMultiCloud\V1\Fleet; +use Google\Cloud\GkeMultiCloud\V1\UpdateAttachedClusterRequest; use Google\Protobuf\FieldMask; use Google\Rpc\Status; @@ -58,7 +59,7 @@ function update_attached_cluster_sample( // Create a client. $attachedClustersClient = new AttachedClustersClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $attachedClusterOidcConfig = new AttachedOidcConfig(); $attachedClusterFleet = (new Fleet()) ->setProject($attachedClusterFleetProject); @@ -68,11 +69,14 @@ function update_attached_cluster_sample( ->setDistribution($attachedClusterDistribution) ->setFleet($attachedClusterFleet); $updateMask = new FieldMask(); + $request = (new UpdateAttachedClusterRequest()) + ->setAttachedCluster($attachedCluster) + ->setUpdateMask($updateMask); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $attachedClustersClient->updateAttachedCluster($attachedCluster, $updateMask); + $response = $attachedClustersClient->updateAttachedCluster($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeMultiCloud/samples/V1/AwsClustersClient/create_aws_cluster.php b/GkeMultiCloud/samples/V1/AwsClustersClient/create_aws_cluster.php index bc832d664719..65eaf649bcb2 100644 --- a/GkeMultiCloud/samples/V1/AwsClustersClient/create_aws_cluster.php +++ b/GkeMultiCloud/samples/V1/AwsClustersClient/create_aws_cluster.php @@ -29,11 +29,12 @@ use Google\Cloud\GkeMultiCloud\V1\AwsCluster; use Google\Cloud\GkeMultiCloud\V1\AwsClusterNetworking; use Google\Cloud\GkeMultiCloud\V1\AwsClusterUser; -use Google\Cloud\GkeMultiCloud\V1\AwsClustersClient; use Google\Cloud\GkeMultiCloud\V1\AwsConfigEncryption; use Google\Cloud\GkeMultiCloud\V1\AwsControlPlane; use Google\Cloud\GkeMultiCloud\V1\AwsDatabaseEncryption; use Google\Cloud\GkeMultiCloud\V1\AwsServicesAuthentication; +use Google\Cloud\GkeMultiCloud\V1\Client\AwsClustersClient; +use Google\Cloud\GkeMultiCloud\V1\CreateAwsClusterRequest; use Google\Cloud\GkeMultiCloud\V1\Fleet; use Google\Rpc\Status; @@ -121,7 +122,7 @@ function create_aws_cluster_sample( // Create a client. $awsClustersClient = new AwsClustersClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $awsClusterNetworkingPodAddressCidrBlocks = [$awsClusterNetworkingPodAddressCidrBlocksElement,]; $awsClusterNetworkingServiceAddressCidrBlocks = [ $awsClusterNetworkingServiceAddressCidrBlocksElement, @@ -157,11 +158,15 @@ function create_aws_cluster_sample( ->setControlPlane($awsClusterControlPlane) ->setAuthorization($awsClusterAuthorization) ->setFleet($awsClusterFleet); + $request = (new CreateAwsClusterRequest()) + ->setParent($formattedParent) + ->setAwsCluster($awsCluster) + ->setAwsClusterId($awsClusterId); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $awsClustersClient->createAwsCluster($formattedParent, $awsCluster, $awsClusterId); + $response = $awsClustersClient->createAwsCluster($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeMultiCloud/samples/V1/AwsClustersClient/create_aws_node_pool.php b/GkeMultiCloud/samples/V1/AwsClustersClient/create_aws_node_pool.php index b97d31d03933..d51dc8eedd95 100644 --- a/GkeMultiCloud/samples/V1/AwsClustersClient/create_aws_node_pool.php +++ b/GkeMultiCloud/samples/V1/AwsClustersClient/create_aws_node_pool.php @@ -25,11 +25,12 @@ // [START gkemulticloud_v1_generated_AwsClusters_CreateAwsNodePool_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\GkeMultiCloud\V1\AwsClustersClient; use Google\Cloud\GkeMultiCloud\V1\AwsConfigEncryption; use Google\Cloud\GkeMultiCloud\V1\AwsNodeConfig; use Google\Cloud\GkeMultiCloud\V1\AwsNodePool; use Google\Cloud\GkeMultiCloud\V1\AwsNodePoolAutoscaling; +use Google\Cloud\GkeMultiCloud\V1\Client\AwsClustersClient; +use Google\Cloud\GkeMultiCloud\V1\CreateAwsNodePoolRequest; use Google\Cloud\GkeMultiCloud\V1\MaxPodsConstraint; use Google\Rpc\Status; @@ -89,7 +90,7 @@ function create_aws_node_pool_sample( // Create a client. $awsClustersClient = new AwsClustersClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $awsNodePoolConfigConfigEncryption = (new AwsConfigEncryption()) ->setKmsKeyArn($awsNodePoolConfigConfigEncryptionKmsKeyArn); $awsNodePoolConfig = (new AwsNodeConfig()) @@ -106,11 +107,15 @@ function create_aws_node_pool_sample( ->setAutoscaling($awsNodePoolAutoscaling) ->setSubnetId($awsNodePoolSubnetId) ->setMaxPodsConstraint($awsNodePoolMaxPodsConstraint); + $request = (new CreateAwsNodePoolRequest()) + ->setParent($formattedParent) + ->setAwsNodePool($awsNodePool) + ->setAwsNodePoolId($awsNodePoolId); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $awsClustersClient->createAwsNodePool($formattedParent, $awsNodePool, $awsNodePoolId); + $response = $awsClustersClient->createAwsNodePool($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeMultiCloud/samples/V1/AwsClustersClient/delete_aws_cluster.php b/GkeMultiCloud/samples/V1/AwsClustersClient/delete_aws_cluster.php index ac7533000156..2c8396a039b9 100644 --- a/GkeMultiCloud/samples/V1/AwsClustersClient/delete_aws_cluster.php +++ b/GkeMultiCloud/samples/V1/AwsClustersClient/delete_aws_cluster.php @@ -25,7 +25,8 @@ // [START gkemulticloud_v1_generated_AwsClusters_DeleteAwsCluster_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\GkeMultiCloud\V1\AwsClustersClient; +use Google\Cloud\GkeMultiCloud\V1\Client\AwsClustersClient; +use Google\Cloud\GkeMultiCloud\V1\DeleteAwsClusterRequest; use Google\Rpc\Status; /** @@ -54,10 +55,14 @@ function delete_aws_cluster_sample(string $formattedName): void // Create a client. $awsClustersClient = new AwsClustersClient(); + // Prepare the request message. + $request = (new DeleteAwsClusterRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $awsClustersClient->deleteAwsCluster($formattedName); + $response = $awsClustersClient->deleteAwsCluster($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeMultiCloud/samples/V1/AwsClustersClient/delete_aws_node_pool.php b/GkeMultiCloud/samples/V1/AwsClustersClient/delete_aws_node_pool.php index 79fe862ddb01..8a57db07e3ba 100644 --- a/GkeMultiCloud/samples/V1/AwsClustersClient/delete_aws_node_pool.php +++ b/GkeMultiCloud/samples/V1/AwsClustersClient/delete_aws_node_pool.php @@ -25,7 +25,8 @@ // [START gkemulticloud_v1_generated_AwsClusters_DeleteAwsNodePool_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\GkeMultiCloud\V1\AwsClustersClient; +use Google\Cloud\GkeMultiCloud\V1\Client\AwsClustersClient; +use Google\Cloud\GkeMultiCloud\V1\DeleteAwsNodePoolRequest; use Google\Rpc\Status; /** @@ -51,10 +52,14 @@ function delete_aws_node_pool_sample(string $formattedName): void // Create a client. $awsClustersClient = new AwsClustersClient(); + // Prepare the request message. + $request = (new DeleteAwsNodePoolRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $awsClustersClient->deleteAwsNodePool($formattedName); + $response = $awsClustersClient->deleteAwsNodePool($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeMultiCloud/samples/V1/AwsClustersClient/generate_aws_access_token.php b/GkeMultiCloud/samples/V1/AwsClustersClient/generate_aws_access_token.php index 107c79ee7022..ba284eb35be2 100644 --- a/GkeMultiCloud/samples/V1/AwsClustersClient/generate_aws_access_token.php +++ b/GkeMultiCloud/samples/V1/AwsClustersClient/generate_aws_access_token.php @@ -24,7 +24,8 @@ // [START gkemulticloud_v1_generated_AwsClusters_GenerateAwsAccessToken_sync] use Google\ApiCore\ApiException; -use Google\Cloud\GkeMultiCloud\V1\AwsClustersClient; +use Google\Cloud\GkeMultiCloud\V1\Client\AwsClustersClient; +use Google\Cloud\GkeMultiCloud\V1\GenerateAwsAccessTokenRequest; use Google\Cloud\GkeMultiCloud\V1\GenerateAwsAccessTokenResponse; /** @@ -47,10 +48,14 @@ function generate_aws_access_token_sample(string $formattedAwsCluster): void // Create a client. $awsClustersClient = new AwsClustersClient(); + // Prepare the request message. + $request = (new GenerateAwsAccessTokenRequest()) + ->setAwsCluster($formattedAwsCluster); + // Call the API and handle any network failures. try { /** @var GenerateAwsAccessTokenResponse $response */ - $response = $awsClustersClient->generateAwsAccessToken($formattedAwsCluster); + $response = $awsClustersClient->generateAwsAccessToken($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeMultiCloud/samples/V1/AwsClustersClient/get_aws_cluster.php b/GkeMultiCloud/samples/V1/AwsClustersClient/get_aws_cluster.php index a92d74cb568b..4ef54c87a896 100644 --- a/GkeMultiCloud/samples/V1/AwsClustersClient/get_aws_cluster.php +++ b/GkeMultiCloud/samples/V1/AwsClustersClient/get_aws_cluster.php @@ -25,7 +25,8 @@ // [START gkemulticloud_v1_generated_AwsClusters_GetAwsCluster_sync] use Google\ApiCore\ApiException; use Google\Cloud\GkeMultiCloud\V1\AwsCluster; -use Google\Cloud\GkeMultiCloud\V1\AwsClustersClient; +use Google\Cloud\GkeMultiCloud\V1\Client\AwsClustersClient; +use Google\Cloud\GkeMultiCloud\V1\GetAwsClusterRequest; /** * Describes a specific [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] @@ -47,10 +48,14 @@ function get_aws_cluster_sample(string $formattedName): void // Create a client. $awsClustersClient = new AwsClustersClient(); + // Prepare the request message. + $request = (new GetAwsClusterRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var AwsCluster $response */ - $response = $awsClustersClient->getAwsCluster($formattedName); + $response = $awsClustersClient->getAwsCluster($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeMultiCloud/samples/V1/AwsClustersClient/get_aws_node_pool.php b/GkeMultiCloud/samples/V1/AwsClustersClient/get_aws_node_pool.php index fb17d2ab126c..9878a7a611af 100644 --- a/GkeMultiCloud/samples/V1/AwsClustersClient/get_aws_node_pool.php +++ b/GkeMultiCloud/samples/V1/AwsClustersClient/get_aws_node_pool.php @@ -24,8 +24,9 @@ // [START gkemulticloud_v1_generated_AwsClusters_GetAwsNodePool_sync] use Google\ApiCore\ApiException; -use Google\Cloud\GkeMultiCloud\V1\AwsClustersClient; use Google\Cloud\GkeMultiCloud\V1\AwsNodePool; +use Google\Cloud\GkeMultiCloud\V1\Client\AwsClustersClient; +use Google\Cloud\GkeMultiCloud\V1\GetAwsNodePoolRequest; /** * Describes a specific @@ -47,10 +48,14 @@ function get_aws_node_pool_sample(string $formattedName): void // Create a client. $awsClustersClient = new AwsClustersClient(); + // Prepare the request message. + $request = (new GetAwsNodePoolRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var AwsNodePool $response */ - $response = $awsClustersClient->getAwsNodePool($formattedName); + $response = $awsClustersClient->getAwsNodePool($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeMultiCloud/samples/V1/AwsClustersClient/get_aws_server_config.php b/GkeMultiCloud/samples/V1/AwsClustersClient/get_aws_server_config.php index 9db146ac3794..19e6ebf5d7de 100644 --- a/GkeMultiCloud/samples/V1/AwsClustersClient/get_aws_server_config.php +++ b/GkeMultiCloud/samples/V1/AwsClustersClient/get_aws_server_config.php @@ -24,8 +24,9 @@ // [START gkemulticloud_v1_generated_AwsClusters_GetAwsServerConfig_sync] use Google\ApiCore\ApiException; -use Google\Cloud\GkeMultiCloud\V1\AwsClustersClient; use Google\Cloud\GkeMultiCloud\V1\AwsServerConfig; +use Google\Cloud\GkeMultiCloud\V1\Client\AwsClustersClient; +use Google\Cloud\GkeMultiCloud\V1\GetAwsServerConfigRequest; /** * Returns information, such as supported AWS regions and Kubernetes @@ -47,10 +48,14 @@ function get_aws_server_config_sample(string $formattedName): void // Create a client. $awsClustersClient = new AwsClustersClient(); + // Prepare the request message. + $request = (new GetAwsServerConfigRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var AwsServerConfig $response */ - $response = $awsClustersClient->getAwsServerConfig($formattedName); + $response = $awsClustersClient->getAwsServerConfig($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeMultiCloud/samples/V1/AwsClustersClient/list_aws_clusters.php b/GkeMultiCloud/samples/V1/AwsClustersClient/list_aws_clusters.php index f524caa5c7a5..36964e24f143 100644 --- a/GkeMultiCloud/samples/V1/AwsClustersClient/list_aws_clusters.php +++ b/GkeMultiCloud/samples/V1/AwsClustersClient/list_aws_clusters.php @@ -26,7 +26,8 @@ use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; use Google\Cloud\GkeMultiCloud\V1\AwsCluster; -use Google\Cloud\GkeMultiCloud\V1\AwsClustersClient; +use Google\Cloud\GkeMultiCloud\V1\Client\AwsClustersClient; +use Google\Cloud\GkeMultiCloud\V1\ListAwsClustersRequest; /** * Lists all [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resources @@ -46,10 +47,14 @@ function list_aws_clusters_sample(string $formattedParent): void // Create a client. $awsClustersClient = new AwsClustersClient(); + // Prepare the request message. + $request = (new ListAwsClustersRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $awsClustersClient->listAwsClusters($formattedParent); + $response = $awsClustersClient->listAwsClusters($request); /** @var AwsCluster $element */ foreach ($response as $element) { diff --git a/GkeMultiCloud/samples/V1/AwsClustersClient/list_aws_node_pools.php b/GkeMultiCloud/samples/V1/AwsClustersClient/list_aws_node_pools.php index 0da606e94859..4c1c486b0ee4 100644 --- a/GkeMultiCloud/samples/V1/AwsClustersClient/list_aws_node_pools.php +++ b/GkeMultiCloud/samples/V1/AwsClustersClient/list_aws_node_pools.php @@ -25,8 +25,9 @@ // [START gkemulticloud_v1_generated_AwsClusters_ListAwsNodePools_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\GkeMultiCloud\V1\AwsClustersClient; use Google\Cloud\GkeMultiCloud\V1\AwsNodePool; +use Google\Cloud\GkeMultiCloud\V1\Client\AwsClustersClient; +use Google\Cloud\GkeMultiCloud\V1\ListAwsNodePoolsRequest; /** * Lists all [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] @@ -48,10 +49,14 @@ function list_aws_node_pools_sample(string $formattedParent): void // Create a client. $awsClustersClient = new AwsClustersClient(); + // Prepare the request message. + $request = (new ListAwsNodePoolsRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $awsClustersClient->listAwsNodePools($formattedParent); + $response = $awsClustersClient->listAwsNodePools($request); /** @var AwsNodePool $element */ foreach ($response as $element) { diff --git a/GkeMultiCloud/samples/V1/AwsClustersClient/update_aws_cluster.php b/GkeMultiCloud/samples/V1/AwsClustersClient/update_aws_cluster.php index ee96b446dede..7ea2382f78d5 100644 --- a/GkeMultiCloud/samples/V1/AwsClustersClient/update_aws_cluster.php +++ b/GkeMultiCloud/samples/V1/AwsClustersClient/update_aws_cluster.php @@ -29,12 +29,13 @@ use Google\Cloud\GkeMultiCloud\V1\AwsCluster; use Google\Cloud\GkeMultiCloud\V1\AwsClusterNetworking; use Google\Cloud\GkeMultiCloud\V1\AwsClusterUser; -use Google\Cloud\GkeMultiCloud\V1\AwsClustersClient; use Google\Cloud\GkeMultiCloud\V1\AwsConfigEncryption; use Google\Cloud\GkeMultiCloud\V1\AwsControlPlane; use Google\Cloud\GkeMultiCloud\V1\AwsDatabaseEncryption; use Google\Cloud\GkeMultiCloud\V1\AwsServicesAuthentication; +use Google\Cloud\GkeMultiCloud\V1\Client\AwsClustersClient; use Google\Cloud\GkeMultiCloud\V1\Fleet; +use Google\Cloud\GkeMultiCloud\V1\UpdateAwsClusterRequest; use Google\Protobuf\FieldMask; use Google\Rpc\Status; @@ -97,7 +98,7 @@ function update_aws_cluster_sample( // Create a client. $awsClustersClient = new AwsClustersClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $awsClusterNetworkingPodAddressCidrBlocks = [$awsClusterNetworkingPodAddressCidrBlocksElement,]; $awsClusterNetworkingServiceAddressCidrBlocks = [ $awsClusterNetworkingServiceAddressCidrBlocksElement, @@ -134,11 +135,14 @@ function update_aws_cluster_sample( ->setAuthorization($awsClusterAuthorization) ->setFleet($awsClusterFleet); $updateMask = new FieldMask(); + $request = (new UpdateAwsClusterRequest()) + ->setAwsCluster($awsCluster) + ->setUpdateMask($updateMask); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $awsClustersClient->updateAwsCluster($awsCluster, $updateMask); + $response = $awsClustersClient->updateAwsCluster($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeMultiCloud/samples/V1/AwsClustersClient/update_aws_node_pool.php b/GkeMultiCloud/samples/V1/AwsClustersClient/update_aws_node_pool.php index e17d2dfdf42c..1c536991a600 100644 --- a/GkeMultiCloud/samples/V1/AwsClustersClient/update_aws_node_pool.php +++ b/GkeMultiCloud/samples/V1/AwsClustersClient/update_aws_node_pool.php @@ -25,12 +25,13 @@ // [START gkemulticloud_v1_generated_AwsClusters_UpdateAwsNodePool_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\GkeMultiCloud\V1\AwsClustersClient; use Google\Cloud\GkeMultiCloud\V1\AwsConfigEncryption; use Google\Cloud\GkeMultiCloud\V1\AwsNodeConfig; use Google\Cloud\GkeMultiCloud\V1\AwsNodePool; use Google\Cloud\GkeMultiCloud\V1\AwsNodePoolAutoscaling; +use Google\Cloud\GkeMultiCloud\V1\Client\AwsClustersClient; use Google\Cloud\GkeMultiCloud\V1\MaxPodsConstraint; +use Google\Cloud\GkeMultiCloud\V1\UpdateAwsNodePoolRequest; use Google\Protobuf\FieldMask; use Google\Rpc\Status; @@ -65,7 +66,7 @@ function update_aws_node_pool_sample( // Create a client. $awsClustersClient = new AwsClustersClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $awsNodePoolConfigConfigEncryption = (new AwsConfigEncryption()) ->setKmsKeyArn($awsNodePoolConfigConfigEncryptionKmsKeyArn); $awsNodePoolConfig = (new AwsNodeConfig()) @@ -83,11 +84,14 @@ function update_aws_node_pool_sample( ->setSubnetId($awsNodePoolSubnetId) ->setMaxPodsConstraint($awsNodePoolMaxPodsConstraint); $updateMask = new FieldMask(); + $request = (new UpdateAwsNodePoolRequest()) + ->setAwsNodePool($awsNodePool) + ->setUpdateMask($updateMask); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $awsClustersClient->updateAwsNodePool($awsNodePool, $updateMask); + $response = $awsClustersClient->updateAwsNodePool($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeMultiCloud/samples/V1/AzureClustersClient/create_azure_client.php b/GkeMultiCloud/samples/V1/AzureClustersClient/create_azure_client.php index b1add7f7bbdd..64ba99249fcf 100644 --- a/GkeMultiCloud/samples/V1/AzureClustersClient/create_azure_client.php +++ b/GkeMultiCloud/samples/V1/AzureClustersClient/create_azure_client.php @@ -26,7 +26,8 @@ use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; use Google\Cloud\GkeMultiCloud\V1\AzureClient; -use Google\Cloud\GkeMultiCloud\V1\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\Client\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\CreateAzureClientRequest; use Google\Rpc\Status; /** @@ -71,15 +72,19 @@ function create_azure_client_sample( // Create a client. $azureClustersClient = new AzureClustersClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $azureClient = (new AzureClient()) ->setTenantId($azureClientTenantId) ->setApplicationId($azureClientApplicationId); + $request = (new CreateAzureClientRequest()) + ->setParent($formattedParent) + ->setAzureClient($azureClient) + ->setAzureClientId($azureClientId); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $azureClustersClient->createAzureClient($formattedParent, $azureClient, $azureClientId); + $response = $azureClustersClient->createAzureClient($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeMultiCloud/samples/V1/AzureClustersClient/create_azure_cluster.php b/GkeMultiCloud/samples/V1/AzureClustersClient/create_azure_cluster.php index 7ca44820d024..19ae828f69b4 100644 --- a/GkeMultiCloud/samples/V1/AzureClustersClient/create_azure_cluster.php +++ b/GkeMultiCloud/samples/V1/AzureClustersClient/create_azure_cluster.php @@ -29,9 +29,10 @@ use Google\Cloud\GkeMultiCloud\V1\AzureCluster; use Google\Cloud\GkeMultiCloud\V1\AzureClusterNetworking; use Google\Cloud\GkeMultiCloud\V1\AzureClusterUser; -use Google\Cloud\GkeMultiCloud\V1\AzureClustersClient; use Google\Cloud\GkeMultiCloud\V1\AzureControlPlane; use Google\Cloud\GkeMultiCloud\V1\AzureSshConfig; +use Google\Cloud\GkeMultiCloud\V1\Client\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\CreateAzureClusterRequest; use Google\Cloud\GkeMultiCloud\V1\Fleet; use Google\Rpc\Status; @@ -126,7 +127,7 @@ function create_azure_cluster_sample( // Create a client. $azureClustersClient = new AzureClustersClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $azureClusterNetworkingPodAddressCidrBlocks = [ $azureClusterNetworkingPodAddressCidrBlocksElement, ]; @@ -156,15 +157,15 @@ function create_azure_cluster_sample( ->setControlPlane($azureClusterControlPlane) ->setAuthorization($azureClusterAuthorization) ->setFleet($azureClusterFleet); + $request = (new CreateAzureClusterRequest()) + ->setParent($formattedParent) + ->setAzureCluster($azureCluster) + ->setAzureClusterId($azureClusterId); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $azureClustersClient->createAzureCluster( - $formattedParent, - $azureCluster, - $azureClusterId - ); + $response = $azureClustersClient->createAzureCluster($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeMultiCloud/samples/V1/AzureClustersClient/create_azure_node_pool.php b/GkeMultiCloud/samples/V1/AzureClustersClient/create_azure_node_pool.php index 037860627c4f..89dffd634280 100644 --- a/GkeMultiCloud/samples/V1/AzureClustersClient/create_azure_node_pool.php +++ b/GkeMultiCloud/samples/V1/AzureClustersClient/create_azure_node_pool.php @@ -25,11 +25,12 @@ // [START gkemulticloud_v1_generated_AzureClusters_CreateAzureNodePool_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\GkeMultiCloud\V1\AzureClustersClient; use Google\Cloud\GkeMultiCloud\V1\AzureNodeConfig; use Google\Cloud\GkeMultiCloud\V1\AzureNodePool; use Google\Cloud\GkeMultiCloud\V1\AzureNodePoolAutoscaling; use Google\Cloud\GkeMultiCloud\V1\AzureSshConfig; +use Google\Cloud\GkeMultiCloud\V1\Client\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\CreateAzureNodePoolRequest; use Google\Cloud\GkeMultiCloud\V1\MaxPodsConstraint; use Google\Rpc\Status; @@ -85,7 +86,7 @@ function create_azure_node_pool_sample( // Create a client. $azureClustersClient = new AzureClustersClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $azureNodePoolConfigSshConfig = (new AzureSshConfig()) ->setAuthorizedKey($azureNodePoolConfigSshConfigAuthorizedKey); $azureNodePoolConfig = (new AzureNodeConfig()) @@ -101,15 +102,15 @@ function create_azure_node_pool_sample( ->setSubnetId($azureNodePoolSubnetId) ->setAutoscaling($azureNodePoolAutoscaling) ->setMaxPodsConstraint($azureNodePoolMaxPodsConstraint); + $request = (new CreateAzureNodePoolRequest()) + ->setParent($formattedParent) + ->setAzureNodePool($azureNodePool) + ->setAzureNodePoolId($azureNodePoolId); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $azureClustersClient->createAzureNodePool( - $formattedParent, - $azureNodePool, - $azureNodePoolId - ); + $response = $azureClustersClient->createAzureNodePool($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeMultiCloud/samples/V1/AzureClustersClient/delete_azure_client.php b/GkeMultiCloud/samples/V1/AzureClustersClient/delete_azure_client.php index 03dc723aaa18..3eeac638e7c2 100644 --- a/GkeMultiCloud/samples/V1/AzureClustersClient/delete_azure_client.php +++ b/GkeMultiCloud/samples/V1/AzureClustersClient/delete_azure_client.php @@ -25,7 +25,8 @@ // [START gkemulticloud_v1_generated_AzureClusters_DeleteAzureClient_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\GkeMultiCloud\V1\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\Client\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\DeleteAzureClientRequest; use Google\Rpc\Status; /** @@ -55,10 +56,14 @@ function delete_azure_client_sample(string $formattedName): void // Create a client. $azureClustersClient = new AzureClustersClient(); + // Prepare the request message. + $request = (new DeleteAzureClientRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $azureClustersClient->deleteAzureClient($formattedName); + $response = $azureClustersClient->deleteAzureClient($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeMultiCloud/samples/V1/AzureClustersClient/delete_azure_cluster.php b/GkeMultiCloud/samples/V1/AzureClustersClient/delete_azure_cluster.php index ad8eb1c219d5..727338d8c062 100644 --- a/GkeMultiCloud/samples/V1/AzureClustersClient/delete_azure_cluster.php +++ b/GkeMultiCloud/samples/V1/AzureClustersClient/delete_azure_cluster.php @@ -25,7 +25,8 @@ // [START gkemulticloud_v1_generated_AzureClusters_DeleteAzureCluster_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\GkeMultiCloud\V1\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\Client\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\DeleteAzureClusterRequest; use Google\Rpc\Status; /** @@ -54,10 +55,14 @@ function delete_azure_cluster_sample(string $formattedName): void // Create a client. $azureClustersClient = new AzureClustersClient(); + // Prepare the request message. + $request = (new DeleteAzureClusterRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $azureClustersClient->deleteAzureCluster($formattedName); + $response = $azureClustersClient->deleteAzureCluster($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeMultiCloud/samples/V1/AzureClustersClient/delete_azure_node_pool.php b/GkeMultiCloud/samples/V1/AzureClustersClient/delete_azure_node_pool.php index aff62d100ed7..c2b3f11704fa 100644 --- a/GkeMultiCloud/samples/V1/AzureClustersClient/delete_azure_node_pool.php +++ b/GkeMultiCloud/samples/V1/AzureClustersClient/delete_azure_node_pool.php @@ -25,7 +25,8 @@ // [START gkemulticloud_v1_generated_AzureClusters_DeleteAzureNodePool_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\GkeMultiCloud\V1\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\Client\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\DeleteAzureNodePoolRequest; use Google\Rpc\Status; /** @@ -51,10 +52,14 @@ function delete_azure_node_pool_sample(string $formattedName): void // Create a client. $azureClustersClient = new AzureClustersClient(); + // Prepare the request message. + $request = (new DeleteAzureNodePoolRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $azureClustersClient->deleteAzureNodePool($formattedName); + $response = $azureClustersClient->deleteAzureNodePool($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeMultiCloud/samples/V1/AzureClustersClient/generate_azure_access_token.php b/GkeMultiCloud/samples/V1/AzureClustersClient/generate_azure_access_token.php index cfaf60fe58c9..e3c8034d3094 100644 --- a/GkeMultiCloud/samples/V1/AzureClustersClient/generate_azure_access_token.php +++ b/GkeMultiCloud/samples/V1/AzureClustersClient/generate_azure_access_token.php @@ -24,7 +24,8 @@ // [START gkemulticloud_v1_generated_AzureClusters_GenerateAzureAccessToken_sync] use Google\ApiCore\ApiException; -use Google\Cloud\GkeMultiCloud\V1\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\Client\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\GenerateAzureAccessTokenRequest; use Google\Cloud\GkeMultiCloud\V1\GenerateAzureAccessTokenResponse; /** @@ -47,10 +48,14 @@ function generate_azure_access_token_sample(string $formattedAzureCluster): void // Create a client. $azureClustersClient = new AzureClustersClient(); + // Prepare the request message. + $request = (new GenerateAzureAccessTokenRequest()) + ->setAzureCluster($formattedAzureCluster); + // Call the API and handle any network failures. try { /** @var GenerateAzureAccessTokenResponse $response */ - $response = $azureClustersClient->generateAzureAccessToken($formattedAzureCluster); + $response = $azureClustersClient->generateAzureAccessToken($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeMultiCloud/samples/V1/AzureClustersClient/get_azure_client.php b/GkeMultiCloud/samples/V1/AzureClustersClient/get_azure_client.php index 23be24df6692..b01d5a7d74fa 100644 --- a/GkeMultiCloud/samples/V1/AzureClustersClient/get_azure_client.php +++ b/GkeMultiCloud/samples/V1/AzureClustersClient/get_azure_client.php @@ -25,7 +25,8 @@ // [START gkemulticloud_v1_generated_AzureClusters_GetAzureClient_sync] use Google\ApiCore\ApiException; use Google\Cloud\GkeMultiCloud\V1\AzureClient; -use Google\Cloud\GkeMultiCloud\V1\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\Client\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\GetAzureClientRequest; /** * Describes a specific @@ -48,10 +49,14 @@ function get_azure_client_sample(string $formattedName): void // Create a client. $azureClustersClient = new AzureClustersClient(); + // Prepare the request message. + $request = (new GetAzureClientRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var AzureClient $response */ - $response = $azureClustersClient->getAzureClient($formattedName); + $response = $azureClustersClient->getAzureClient($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeMultiCloud/samples/V1/AzureClustersClient/get_azure_cluster.php b/GkeMultiCloud/samples/V1/AzureClustersClient/get_azure_cluster.php index fec310725e75..391320390d17 100644 --- a/GkeMultiCloud/samples/V1/AzureClustersClient/get_azure_cluster.php +++ b/GkeMultiCloud/samples/V1/AzureClustersClient/get_azure_cluster.php @@ -25,7 +25,8 @@ // [START gkemulticloud_v1_generated_AzureClusters_GetAzureCluster_sync] use Google\ApiCore\ApiException; use Google\Cloud\GkeMultiCloud\V1\AzureCluster; -use Google\Cloud\GkeMultiCloud\V1\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\Client\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\GetAzureClusterRequest; /** * Describes a specific @@ -47,10 +48,14 @@ function get_azure_cluster_sample(string $formattedName): void // Create a client. $azureClustersClient = new AzureClustersClient(); + // Prepare the request message. + $request = (new GetAzureClusterRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var AzureCluster $response */ - $response = $azureClustersClient->getAzureCluster($formattedName); + $response = $azureClustersClient->getAzureCluster($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeMultiCloud/samples/V1/AzureClustersClient/get_azure_node_pool.php b/GkeMultiCloud/samples/V1/AzureClustersClient/get_azure_node_pool.php index cf546ffefc9d..a36886ca6bc4 100644 --- a/GkeMultiCloud/samples/V1/AzureClustersClient/get_azure_node_pool.php +++ b/GkeMultiCloud/samples/V1/AzureClustersClient/get_azure_node_pool.php @@ -24,8 +24,9 @@ // [START gkemulticloud_v1_generated_AzureClusters_GetAzureNodePool_sync] use Google\ApiCore\ApiException; -use Google\Cloud\GkeMultiCloud\V1\AzureClustersClient; use Google\Cloud\GkeMultiCloud\V1\AzureNodePool; +use Google\Cloud\GkeMultiCloud\V1\Client\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\GetAzureNodePoolRequest; /** * Describes a specific @@ -47,10 +48,14 @@ function get_azure_node_pool_sample(string $formattedName): void // Create a client. $azureClustersClient = new AzureClustersClient(); + // Prepare the request message. + $request = (new GetAzureNodePoolRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var AzureNodePool $response */ - $response = $azureClustersClient->getAzureNodePool($formattedName); + $response = $azureClustersClient->getAzureNodePool($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeMultiCloud/samples/V1/AzureClustersClient/get_azure_server_config.php b/GkeMultiCloud/samples/V1/AzureClustersClient/get_azure_server_config.php index 1062f5f5739c..e75ddf122041 100644 --- a/GkeMultiCloud/samples/V1/AzureClustersClient/get_azure_server_config.php +++ b/GkeMultiCloud/samples/V1/AzureClustersClient/get_azure_server_config.php @@ -24,8 +24,9 @@ // [START gkemulticloud_v1_generated_AzureClusters_GetAzureServerConfig_sync] use Google\ApiCore\ApiException; -use Google\Cloud\GkeMultiCloud\V1\AzureClustersClient; use Google\Cloud\GkeMultiCloud\V1\AzureServerConfig; +use Google\Cloud\GkeMultiCloud\V1\Client\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\GetAzureServerConfigRequest; /** * Returns information, such as supported Azure regions and Kubernetes @@ -47,10 +48,14 @@ function get_azure_server_config_sample(string $formattedName): void // Create a client. $azureClustersClient = new AzureClustersClient(); + // Prepare the request message. + $request = (new GetAzureServerConfigRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var AzureServerConfig $response */ - $response = $azureClustersClient->getAzureServerConfig($formattedName); + $response = $azureClustersClient->getAzureServerConfig($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/GkeMultiCloud/samples/V1/AzureClustersClient/list_azure_clients.php b/GkeMultiCloud/samples/V1/AzureClustersClient/list_azure_clients.php index e3efa8b6d894..66e65f6da21b 100644 --- a/GkeMultiCloud/samples/V1/AzureClustersClient/list_azure_clients.php +++ b/GkeMultiCloud/samples/V1/AzureClustersClient/list_azure_clients.php @@ -26,7 +26,8 @@ use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; use Google\Cloud\GkeMultiCloud\V1\AzureClient; -use Google\Cloud\GkeMultiCloud\V1\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\Client\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\ListAzureClientsRequest; /** * Lists all [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] @@ -46,10 +47,14 @@ function list_azure_clients_sample(string $formattedParent): void // Create a client. $azureClustersClient = new AzureClustersClient(); + // Prepare the request message. + $request = (new ListAzureClientsRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $azureClustersClient->listAzureClients($formattedParent); + $response = $azureClustersClient->listAzureClients($request); /** @var AzureClient $element */ foreach ($response as $element) { diff --git a/GkeMultiCloud/samples/V1/AzureClustersClient/list_azure_clusters.php b/GkeMultiCloud/samples/V1/AzureClustersClient/list_azure_clusters.php index b8af4c86dd10..a5f6da2ae8ca 100644 --- a/GkeMultiCloud/samples/V1/AzureClustersClient/list_azure_clusters.php +++ b/GkeMultiCloud/samples/V1/AzureClustersClient/list_azure_clusters.php @@ -26,7 +26,8 @@ use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; use Google\Cloud\GkeMultiCloud\V1\AzureCluster; -use Google\Cloud\GkeMultiCloud\V1\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\Client\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\ListAzureClustersRequest; /** * Lists all [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] @@ -46,10 +47,14 @@ function list_azure_clusters_sample(string $formattedParent): void // Create a client. $azureClustersClient = new AzureClustersClient(); + // Prepare the request message. + $request = (new ListAzureClustersRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $azureClustersClient->listAzureClusters($formattedParent); + $response = $azureClustersClient->listAzureClusters($request); /** @var AzureCluster $element */ foreach ($response as $element) { diff --git a/GkeMultiCloud/samples/V1/AzureClustersClient/list_azure_node_pools.php b/GkeMultiCloud/samples/V1/AzureClustersClient/list_azure_node_pools.php index 2c81ebfa2bfa..70b779be2b8c 100644 --- a/GkeMultiCloud/samples/V1/AzureClustersClient/list_azure_node_pools.php +++ b/GkeMultiCloud/samples/V1/AzureClustersClient/list_azure_node_pools.php @@ -25,8 +25,9 @@ // [START gkemulticloud_v1_generated_AzureClusters_ListAzureNodePools_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\GkeMultiCloud\V1\AzureClustersClient; use Google\Cloud\GkeMultiCloud\V1\AzureNodePool; +use Google\Cloud\GkeMultiCloud\V1\Client\AzureClustersClient; +use Google\Cloud\GkeMultiCloud\V1\ListAzureNodePoolsRequest; /** * Lists all [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] @@ -48,10 +49,14 @@ function list_azure_node_pools_sample(string $formattedParent): void // Create a client. $azureClustersClient = new AzureClustersClient(); + // Prepare the request message. + $request = (new ListAzureNodePoolsRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $azureClustersClient->listAzureNodePools($formattedParent); + $response = $azureClustersClient->listAzureNodePools($request); /** @var AzureNodePool $element */ foreach ($response as $element) { diff --git a/GkeMultiCloud/samples/V1/AzureClustersClient/update_azure_cluster.php b/GkeMultiCloud/samples/V1/AzureClustersClient/update_azure_cluster.php index 803ea26483e2..ca95447257cb 100644 --- a/GkeMultiCloud/samples/V1/AzureClustersClient/update_azure_cluster.php +++ b/GkeMultiCloud/samples/V1/AzureClustersClient/update_azure_cluster.php @@ -29,10 +29,11 @@ use Google\Cloud\GkeMultiCloud\V1\AzureCluster; use Google\Cloud\GkeMultiCloud\V1\AzureClusterNetworking; use Google\Cloud\GkeMultiCloud\V1\AzureClusterUser; -use Google\Cloud\GkeMultiCloud\V1\AzureClustersClient; use Google\Cloud\GkeMultiCloud\V1\AzureControlPlane; use Google\Cloud\GkeMultiCloud\V1\AzureSshConfig; +use Google\Cloud\GkeMultiCloud\V1\Client\AzureClustersClient; use Google\Cloud\GkeMultiCloud\V1\Fleet; +use Google\Cloud\GkeMultiCloud\V1\UpdateAzureClusterRequest; use Google\Protobuf\FieldMask; use Google\Rpc\Status; @@ -102,7 +103,7 @@ function update_azure_cluster_sample( // Create a client. $azureClustersClient = new AzureClustersClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $azureClusterNetworkingPodAddressCidrBlocks = [ $azureClusterNetworkingPodAddressCidrBlocksElement, ]; @@ -133,11 +134,14 @@ function update_azure_cluster_sample( ->setAuthorization($azureClusterAuthorization) ->setFleet($azureClusterFleet); $updateMask = new FieldMask(); + $request = (new UpdateAzureClusterRequest()) + ->setAzureCluster($azureCluster) + ->setUpdateMask($updateMask); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $azureClustersClient->updateAzureCluster($azureCluster, $updateMask); + $response = $azureClustersClient->updateAzureCluster($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeMultiCloud/samples/V1/AzureClustersClient/update_azure_node_pool.php b/GkeMultiCloud/samples/V1/AzureClustersClient/update_azure_node_pool.php index f3ec43e2c263..5cea6a535a3b 100644 --- a/GkeMultiCloud/samples/V1/AzureClustersClient/update_azure_node_pool.php +++ b/GkeMultiCloud/samples/V1/AzureClustersClient/update_azure_node_pool.php @@ -25,12 +25,13 @@ // [START gkemulticloud_v1_generated_AzureClusters_UpdateAzureNodePool_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\GkeMultiCloud\V1\AzureClustersClient; use Google\Cloud\GkeMultiCloud\V1\AzureNodeConfig; use Google\Cloud\GkeMultiCloud\V1\AzureNodePool; use Google\Cloud\GkeMultiCloud\V1\AzureNodePoolAutoscaling; use Google\Cloud\GkeMultiCloud\V1\AzureSshConfig; +use Google\Cloud\GkeMultiCloud\V1\Client\AzureClustersClient; use Google\Cloud\GkeMultiCloud\V1\MaxPodsConstraint; +use Google\Cloud\GkeMultiCloud\V1\UpdateAzureNodePoolRequest; use Google\Protobuf\FieldMask; use Google\Rpc\Status; @@ -61,7 +62,7 @@ function update_azure_node_pool_sample( // Create a client. $azureClustersClient = new AzureClustersClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $azureNodePoolConfigSshConfig = (new AzureSshConfig()) ->setAuthorizedKey($azureNodePoolConfigSshConfigAuthorizedKey); $azureNodePoolConfig = (new AzureNodeConfig()) @@ -78,11 +79,14 @@ function update_azure_node_pool_sample( ->setAutoscaling($azureNodePoolAutoscaling) ->setMaxPodsConstraint($azureNodePoolMaxPodsConstraint); $updateMask = new FieldMask(); + $request = (new UpdateAzureNodePoolRequest()) + ->setAzureNodePool($azureNodePool) + ->setUpdateMask($updateMask); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $azureClustersClient->updateAzureNodePool($azureNodePool, $updateMask); + $response = $azureClustersClient->updateAzureNodePool($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/GkeMultiCloud/src/V1/Client/AttachedClustersClient.php b/GkeMultiCloud/src/V1/Client/AttachedClustersClient.php new file mode 100644 index 000000000000..fed5d98cce71 --- /dev/null +++ b/GkeMultiCloud/src/V1/Client/AttachedClustersClient.php @@ -0,0 +1,40 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/attached_clusters_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/attached_clusters_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/attached_clusters_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/attached_clusters_rest_client_config.php', + ], + ], + ]; + } + + /** + * Return an OperationsClient object with the same endpoint as $this. + * + * @return OperationsClient + */ + public function getOperationsClient() + { + return $this->operationsClient; + } + + /** + * Resume an existing long running operation that was previously started by a long + * running API method. If $methodName is not provided, or does not match a long + * running API method, then the operation can still be resumed, but the + * OperationResponse object will not deserialize the final response. + * + * @param string $operationName The name of the long running operation + * @param string $methodName The name of the method used to start the operation + * + * @return OperationResponse + */ + public function resumeOperation($operationName, $methodName = null) + { + $options = isset($this->descriptors[$methodName]['longRunning']) ? $this->descriptors[$methodName]['longRunning'] : []; + $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); + $operation->reload(); + return $operation; + } + + /** + * Formats a string containing the fully-qualified path to represent a + * attached_cluster resource. + * + * @param string $project + * @param string $location + * @param string $attachedCluster + * + * @return string The formatted attached_cluster resource. + */ + public static function attachedClusterName(string $project, string $location, string $attachedCluster): string + { + return self::getPathTemplate('attachedCluster')->render([ + 'project' => $project, + 'location' => $location, + 'attached_cluster' => $attachedCluster, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * attached_server_config resource. + * + * @param string $project + * @param string $location + * + * @return string The formatted attached_server_config resource. + */ + public static function attachedServerConfigName(string $project, string $location): string + { + return self::getPathTemplate('attachedServerConfig')->render([ + 'project' => $project, + 'location' => $location, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a location + * resource. + * + * @param string $project + * @param string $location + * + * @return string The formatted location resource. + */ + public static function locationName(string $project, string $location): string + { + return self::getPathTemplate('location')->render([ + 'project' => $project, + 'location' => $location, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - attachedCluster: projects/{project}/locations/{location}/attachedClusters/{attached_cluster} + * - attachedServerConfig: projects/{project}/locations/{location}/attachedServerConfig + * - location: projects/{project}/locations/{location} + * + * The optional $template argument can be supplied to specify a particular pattern, + * and must match one of the templates listed above. If no $template argument is + * provided, or if the $template argument does not match one of the templates + * listed, then parseName will check each of the supported templates, and return + * the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + */ + public static function parseName(string $formattedName, string $template = null): array + { + return self::parseFormattedName($formattedName, $template); + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'gkemulticloud.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + $this->operationsClient = $this->createOperationsClient($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Creates a new + * [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] resource + * on a given Google Cloud Platform project and region. + * + * If successful, the response contains a newly created + * [Operation][google.longrunning.Operation] resource that can be + * described to track the status of the operation. + * + * The async variant is {@see self::createAttachedClusterAsync()} . + * + * @param CreateAttachedClusterRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createAttachedCluster(CreateAttachedClusterRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreateAttachedCluster', $request, $callOptions)->wait(); + } + + /** + * Deletes a specific + * [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] resource. + * + * If successful, the response contains a newly created + * [Operation][google.longrunning.Operation] resource that can be + * described to track the status of the operation. + * + * The async variant is {@see self::deleteAttachedClusterAsync()} . + * + * @param DeleteAttachedClusterRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteAttachedCluster(DeleteAttachedClusterRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('DeleteAttachedCluster', $request, $callOptions)->wait(); + } + + /** + * Generates the install manifest to be installed on the target cluster. + * + * The async variant is {@see self::generateAttachedClusterInstallManifestAsync()} + * . + * + * @param GenerateAttachedClusterInstallManifestRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return GenerateAttachedClusterInstallManifestResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function generateAttachedClusterInstallManifest(GenerateAttachedClusterInstallManifestRequest $request, array $callOptions = []): GenerateAttachedClusterInstallManifestResponse + { + return $this->startApiCall('GenerateAttachedClusterInstallManifest', $request, $callOptions)->wait(); + } + + /** + * Describes a specific + * [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] resource. + * + * The async variant is {@see self::getAttachedClusterAsync()} . + * + * @param GetAttachedClusterRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return AttachedCluster + * + * @throws ApiException Thrown if the API call fails. + */ + public function getAttachedCluster(GetAttachedClusterRequest $request, array $callOptions = []): AttachedCluster + { + return $this->startApiCall('GetAttachedCluster', $request, $callOptions)->wait(); + } + + /** + * Returns information, such as supported Kubernetes versions, on a given + * Google Cloud location. + * + * The async variant is {@see self::getAttachedServerConfigAsync()} . + * + * @param GetAttachedServerConfigRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return AttachedServerConfig + * + * @throws ApiException Thrown if the API call fails. + */ + public function getAttachedServerConfig(GetAttachedServerConfigRequest $request, array $callOptions = []): AttachedServerConfig + { + return $this->startApiCall('GetAttachedServerConfig', $request, $callOptions)->wait(); + } + + /** + * Imports creates a new + * [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] resource + * by importing an existing Fleet Membership resource. + * + * Attached Clusters created before the introduction of the Anthos Multi-Cloud + * API can be imported through this method. + * + * If successful, the response contains a newly created + * [Operation][google.longrunning.Operation] resource that can be + * described to track the status of the operation. + * + * The async variant is {@see self::importAttachedClusterAsync()} . + * + * @param ImportAttachedClusterRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function importAttachedCluster(ImportAttachedClusterRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('ImportAttachedCluster', $request, $callOptions)->wait(); + } + + /** + * Lists all [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] + * resources on a given Google Cloud project and region. + * + * The async variant is {@see self::listAttachedClustersAsync()} . + * + * @param ListAttachedClustersRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listAttachedClusters(ListAttachedClustersRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListAttachedClusters', $request, $callOptions); + } + + /** + * Updates an + * [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster]. + * + * The async variant is {@see self::updateAttachedClusterAsync()} . + * + * @param UpdateAttachedClusterRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function updateAttachedCluster(UpdateAttachedClusterRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('UpdateAttachedCluster', $request, $callOptions)->wait(); + } +} diff --git a/GkeMultiCloud/src/V1/Client/BaseClient/AwsClustersBaseClient.php b/GkeMultiCloud/src/V1/Client/BaseClient/AwsClustersBaseClient.php new file mode 100644 index 000000000000..9111531aee67 --- /dev/null +++ b/GkeMultiCloud/src/V1/Client/BaseClient/AwsClustersBaseClient.php @@ -0,0 +1,650 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/aws_clusters_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/aws_clusters_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/aws_clusters_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/aws_clusters_rest_client_config.php', + ], + ], + ]; + } + + /** + * Return an OperationsClient object with the same endpoint as $this. + * + * @return OperationsClient + */ + public function getOperationsClient() + { + return $this->operationsClient; + } + + /** + * Resume an existing long running operation that was previously started by a long + * running API method. If $methodName is not provided, or does not match a long + * running API method, then the operation can still be resumed, but the + * OperationResponse object will not deserialize the final response. + * + * @param string $operationName The name of the long running operation + * @param string $methodName The name of the method used to start the operation + * + * @return OperationResponse + */ + public function resumeOperation($operationName, $methodName = null) + { + $options = isset($this->descriptors[$methodName]['longRunning']) ? $this->descriptors[$methodName]['longRunning'] : []; + $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); + $operation->reload(); + return $operation; + } + + /** + * Formats a string containing the fully-qualified path to represent a aws_cluster + * resource. + * + * @param string $project + * @param string $location + * @param string $awsCluster + * + * @return string The formatted aws_cluster resource. + */ + public static function awsClusterName(string $project, string $location, string $awsCluster): string + { + return self::getPathTemplate('awsCluster')->render([ + 'project' => $project, + 'location' => $location, + 'aws_cluster' => $awsCluster, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * aws_node_pool resource. + * + * @param string $project + * @param string $location + * @param string $awsCluster + * @param string $awsNodePool + * + * @return string The formatted aws_node_pool resource. + */ + public static function awsNodePoolName(string $project, string $location, string $awsCluster, string $awsNodePool): string + { + return self::getPathTemplate('awsNodePool')->render([ + 'project' => $project, + 'location' => $location, + 'aws_cluster' => $awsCluster, + 'aws_node_pool' => $awsNodePool, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * aws_server_config resource. + * + * @param string $project + * @param string $location + * + * @return string The formatted aws_server_config resource. + */ + public static function awsServerConfigName(string $project, string $location): string + { + return self::getPathTemplate('awsServerConfig')->render([ + 'project' => $project, + 'location' => $location, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a location + * resource. + * + * @param string $project + * @param string $location + * + * @return string The formatted location resource. + */ + public static function locationName(string $project, string $location): string + { + return self::getPathTemplate('location')->render([ + 'project' => $project, + 'location' => $location, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - awsCluster: projects/{project}/locations/{location}/awsClusters/{aws_cluster} + * - awsNodePool: projects/{project}/locations/{location}/awsClusters/{aws_cluster}/awsNodePools/{aws_node_pool} + * - awsServerConfig: projects/{project}/locations/{location}/awsServerConfig + * - location: projects/{project}/locations/{location} + * + * The optional $template argument can be supplied to specify a particular pattern, + * and must match one of the templates listed above. If no $template argument is + * provided, or if the $template argument does not match one of the templates + * listed, then parseName will check each of the supported templates, and return + * the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + */ + public static function parseName(string $formattedName, string $template = null): array + { + return self::parseFormattedName($formattedName, $template); + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'gkemulticloud.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + $this->operationsClient = $this->createOperationsClient($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Creates a new [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + * resource on a given Google Cloud Platform project and region. + * + * If successful, the response contains a newly created + * [Operation][google.longrunning.Operation] resource that can be + * described to track the status of the operation. + * + * The async variant is {@see self::createAwsClusterAsync()} . + * + * @param CreateAwsClusterRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createAwsCluster(CreateAwsClusterRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreateAwsCluster', $request, $callOptions)->wait(); + } + + /** + * Creates a new [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool], + * attached to a given [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. + * + * If successful, the response contains a newly created + * [Operation][google.longrunning.Operation] resource that can be + * described to track the status of the operation. + * + * The async variant is {@see self::createAwsNodePoolAsync()} . + * + * @param CreateAwsNodePoolRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createAwsNodePool(CreateAwsNodePoolRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreateAwsNodePool', $request, $callOptions)->wait(); + } + + /** + * Deletes a specific [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + * resource. + * + * Fails if the cluster has one or more associated + * [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] resources. + * + * If successful, the response contains a newly created + * [Operation][google.longrunning.Operation] resource that can be + * described to track the status of the operation. + * + * The async variant is {@see self::deleteAwsClusterAsync()} . + * + * @param DeleteAwsClusterRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteAwsCluster(DeleteAwsClusterRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('DeleteAwsCluster', $request, $callOptions)->wait(); + } + + /** + * Deletes a specific [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + * resource. + * + * If successful, the response contains a newly created + * [Operation][google.longrunning.Operation] resource that can be + * described to track the status of the operation. + * + * The async variant is {@see self::deleteAwsNodePoolAsync()} . + * + * @param DeleteAwsNodePoolRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteAwsNodePool(DeleteAwsNodePoolRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('DeleteAwsNodePool', $request, $callOptions)->wait(); + } + + /** + * Generates a short-lived access token to authenticate to a given + * [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource. + * + * The async variant is {@see self::generateAwsAccessTokenAsync()} . + * + * @param GenerateAwsAccessTokenRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return GenerateAwsAccessTokenResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function generateAwsAccessToken(GenerateAwsAccessTokenRequest $request, array $callOptions = []): GenerateAwsAccessTokenResponse + { + return $this->startApiCall('GenerateAwsAccessToken', $request, $callOptions)->wait(); + } + + /** + * Describes a specific [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + * resource. + * + * The async variant is {@see self::getAwsClusterAsync()} . + * + * @param GetAwsClusterRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return AwsCluster + * + * @throws ApiException Thrown if the API call fails. + */ + public function getAwsCluster(GetAwsClusterRequest $request, array $callOptions = []): AwsCluster + { + return $this->startApiCall('GetAwsCluster', $request, $callOptions)->wait(); + } + + /** + * Describes a specific + * [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] resource. + * + * The async variant is {@see self::getAwsNodePoolAsync()} . + * + * @param GetAwsNodePoolRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return AwsNodePool + * + * @throws ApiException Thrown if the API call fails. + */ + public function getAwsNodePool(GetAwsNodePoolRequest $request, array $callOptions = []): AwsNodePool + { + return $this->startApiCall('GetAwsNodePool', $request, $callOptions)->wait(); + } + + /** + * Returns information, such as supported AWS regions and Kubernetes + * versions, on a given Google Cloud location. + * + * The async variant is {@see self::getAwsServerConfigAsync()} . + * + * @param GetAwsServerConfigRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return AwsServerConfig + * + * @throws ApiException Thrown if the API call fails. + */ + public function getAwsServerConfig(GetAwsServerConfigRequest $request, array $callOptions = []): AwsServerConfig + { + return $this->startApiCall('GetAwsServerConfig', $request, $callOptions)->wait(); + } + + /** + * Lists all [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resources + * on a given Google Cloud project and region. + * + * The async variant is {@see self::listAwsClustersAsync()} . + * + * @param ListAwsClustersRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listAwsClusters(ListAwsClustersRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListAwsClusters', $request, $callOptions); + } + + /** + * Lists all [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + * resources on a given + * [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. + * + * The async variant is {@see self::listAwsNodePoolsAsync()} . + * + * @param ListAwsNodePoolsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listAwsNodePools(ListAwsNodePoolsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListAwsNodePools', $request, $callOptions); + } + + /** + * Updates an [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]. + * + * The async variant is {@see self::updateAwsClusterAsync()} . + * + * @param UpdateAwsClusterRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function updateAwsCluster(UpdateAwsClusterRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('UpdateAwsCluster', $request, $callOptions)->wait(); + } + + /** + * Updates an [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool]. + * + * The async variant is {@see self::updateAwsNodePoolAsync()} . + * + * @param UpdateAwsNodePoolRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function updateAwsNodePool(UpdateAwsNodePoolRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('UpdateAwsNodePool', $request, $callOptions)->wait(); + } +} diff --git a/GkeMultiCloud/src/V1/Client/BaseClient/AzureClustersBaseClient.php b/GkeMultiCloud/src/V1/Client/BaseClient/AzureClustersBaseClient.php new file mode 100644 index 000000000000..c38fee4c9c8e --- /dev/null +++ b/GkeMultiCloud/src/V1/Client/BaseClient/AzureClustersBaseClient.php @@ -0,0 +1,795 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/azure_clusters_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/azure_clusters_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/azure_clusters_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/azure_clusters_rest_client_config.php', + ], + ], + ]; + } + + /** + * Return an OperationsClient object with the same endpoint as $this. + * + * @return OperationsClient + */ + public function getOperationsClient() + { + return $this->operationsClient; + } + + /** + * Resume an existing long running operation that was previously started by a long + * running API method. If $methodName is not provided, or does not match a long + * running API method, then the operation can still be resumed, but the + * OperationResponse object will not deserialize the final response. + * + * @param string $operationName The name of the long running operation + * @param string $methodName The name of the method used to start the operation + * + * @return OperationResponse + */ + public function resumeOperation($operationName, $methodName = null) + { + $options = isset($this->descriptors[$methodName]['longRunning']) ? $this->descriptors[$methodName]['longRunning'] : []; + $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); + $operation->reload(); + return $operation; + } + + /** + * Formats a string containing the fully-qualified path to represent a azure_client + * resource. + * + * @param string $project + * @param string $location + * @param string $azureClient + * + * @return string The formatted azure_client resource. + */ + public static function azureClientName(string $project, string $location, string $azureClient): string + { + return self::getPathTemplate('azureClient')->render([ + 'project' => $project, + 'location' => $location, + 'azure_client' => $azureClient, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * azure_cluster resource. + * + * @param string $project + * @param string $location + * @param string $azureCluster + * + * @return string The formatted azure_cluster resource. + */ + public static function azureClusterName(string $project, string $location, string $azureCluster): string + { + return self::getPathTemplate('azureCluster')->render([ + 'project' => $project, + 'location' => $location, + 'azure_cluster' => $azureCluster, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * azure_node_pool resource. + * + * @param string $project + * @param string $location + * @param string $azureCluster + * @param string $azureNodePool + * + * @return string The formatted azure_node_pool resource. + */ + public static function azureNodePoolName(string $project, string $location, string $azureCluster, string $azureNodePool): string + { + return self::getPathTemplate('azureNodePool')->render([ + 'project' => $project, + 'location' => $location, + 'azure_cluster' => $azureCluster, + 'azure_node_pool' => $azureNodePool, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * azure_server_config resource. + * + * @param string $project + * @param string $location + * + * @return string The formatted azure_server_config resource. + */ + public static function azureServerConfigName(string $project, string $location): string + { + return self::getPathTemplate('azureServerConfig')->render([ + 'project' => $project, + 'location' => $location, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a location + * resource. + * + * @param string $project + * @param string $location + * + * @return string The formatted location resource. + */ + public static function locationName(string $project, string $location): string + { + return self::getPathTemplate('location')->render([ + 'project' => $project, + 'location' => $location, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - azureClient: projects/{project}/locations/{location}/azureClients/{azure_client} + * - azureCluster: projects/{project}/locations/{location}/azureClusters/{azure_cluster} + * - azureNodePool: projects/{project}/locations/{location}/azureClusters/{azure_cluster}/azureNodePools/{azure_node_pool} + * - azureServerConfig: projects/{project}/locations/{location}/azureServerConfig + * - location: projects/{project}/locations/{location} + * + * The optional $template argument can be supplied to specify a particular pattern, + * and must match one of the templates listed above. If no $template argument is + * provided, or if the $template argument does not match one of the templates + * listed, then parseName will check each of the supported templates, and return + * the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + */ + public static function parseName(string $formattedName, string $template = null): array + { + return self::parseFormattedName($formattedName, $template); + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'gkemulticloud.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + $this->operationsClient = $this->createOperationsClient($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Creates a new [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + * resource on a given Google Cloud project and region. + * + * `AzureClient` resources hold client authentication + * information needed by the Anthos Multicloud API to manage Azure resources + * on your Azure subscription on your behalf. + * + * If successful, the response contains a newly created + * [Operation][google.longrunning.Operation] resource that can be + * described to track the status of the operation. + * + * The async variant is {@see self::createAzureClientAsync()} . + * + * @param CreateAzureClientRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createAzureClient(CreateAzureClientRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreateAzureClient', $request, $callOptions)->wait(); + } + + /** + * Creates a new [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + * resource on a given Google Cloud Platform project and region. + * + * If successful, the response contains a newly created + * [Operation][google.longrunning.Operation] resource that can be + * described to track the status of the operation. + * + * The async variant is {@see self::createAzureClusterAsync()} . + * + * @param CreateAzureClusterRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createAzureCluster(CreateAzureClusterRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreateAzureCluster', $request, $callOptions)->wait(); + } + + /** + * Creates a new [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool], + * attached to a given + * [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. + * + * If successful, the response contains a newly created + * [Operation][google.longrunning.Operation] resource that can be + * described to track the status of the operation. + * + * The async variant is {@see self::createAzureNodePoolAsync()} . + * + * @param CreateAzureNodePoolRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createAzureNodePool(CreateAzureNodePoolRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreateAzureNodePool', $request, $callOptions)->wait(); + } + + /** + * Deletes a specific [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + * resource. + * + * If the client is used by one or more clusters, deletion will + * fail and a `FAILED_PRECONDITION` error will be returned. + * + * If successful, the response contains a newly created + * [Operation][google.longrunning.Operation] resource that can be + * described to track the status of the operation. + * + * The async variant is {@see self::deleteAzureClientAsync()} . + * + * @param DeleteAzureClientRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteAzureClient(DeleteAzureClientRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('DeleteAzureClient', $request, $callOptions)->wait(); + } + + /** + * Deletes a specific + * [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] resource. + * + * Fails if the cluster has one or more associated + * [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] resources. + * + * If successful, the response contains a newly created + * [Operation][google.longrunning.Operation] resource that can be + * described to track the status of the operation. + * + * The async variant is {@see self::deleteAzureClusterAsync()} . + * + * @param DeleteAzureClusterRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteAzureCluster(DeleteAzureClusterRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('DeleteAzureCluster', $request, $callOptions)->wait(); + } + + /** + * Deletes a specific + * [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] resource. + * + * If successful, the response contains a newly created + * [Operation][google.longrunning.Operation] resource that can be + * described to track the status of the operation. + * + * The async variant is {@see self::deleteAzureNodePoolAsync()} . + * + * @param DeleteAzureNodePoolRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteAzureNodePool(DeleteAzureNodePoolRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('DeleteAzureNodePool', $request, $callOptions)->wait(); + } + + /** + * Generates a short-lived access token to authenticate to a given + * [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] resource. + * + * The async variant is {@see self::generateAzureAccessTokenAsync()} . + * + * @param GenerateAzureAccessTokenRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return GenerateAzureAccessTokenResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function generateAzureAccessToken(GenerateAzureAccessTokenRequest $request, array $callOptions = []): GenerateAzureAccessTokenResponse + { + return $this->startApiCall('GenerateAzureAccessToken', $request, $callOptions)->wait(); + } + + /** + * Describes a specific + * [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] resource. + * + * The async variant is {@see self::getAzureClientAsync()} . + * + * @param GetAzureClientRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return AzureClient + * + * @throws ApiException Thrown if the API call fails. + */ + public function getAzureClient(GetAzureClientRequest $request, array $callOptions = []): AzureClient + { + return $this->startApiCall('GetAzureClient', $request, $callOptions)->wait(); + } + + /** + * Describes a specific + * [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] resource. + * + * The async variant is {@see self::getAzureClusterAsync()} . + * + * @param GetAzureClusterRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return AzureCluster + * + * @throws ApiException Thrown if the API call fails. + */ + public function getAzureCluster(GetAzureClusterRequest $request, array $callOptions = []): AzureCluster + { + return $this->startApiCall('GetAzureCluster', $request, $callOptions)->wait(); + } + + /** + * Describes a specific + * [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] resource. + * + * The async variant is {@see self::getAzureNodePoolAsync()} . + * + * @param GetAzureNodePoolRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return AzureNodePool + * + * @throws ApiException Thrown if the API call fails. + */ + public function getAzureNodePool(GetAzureNodePoolRequest $request, array $callOptions = []): AzureNodePool + { + return $this->startApiCall('GetAzureNodePool', $request, $callOptions)->wait(); + } + + /** + * Returns information, such as supported Azure regions and Kubernetes + * versions, on a given Google Cloud location. + * + * The async variant is {@see self::getAzureServerConfigAsync()} . + * + * @param GetAzureServerConfigRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return AzureServerConfig + * + * @throws ApiException Thrown if the API call fails. + */ + public function getAzureServerConfig(GetAzureServerConfigRequest $request, array $callOptions = []): AzureServerConfig + { + return $this->startApiCall('GetAzureServerConfig', $request, $callOptions)->wait(); + } + + /** + * Lists all [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] + * resources on a given Google Cloud project and region. + * + * The async variant is {@see self::listAzureClientsAsync()} . + * + * @param ListAzureClientsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listAzureClients(ListAzureClientsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListAzureClients', $request, $callOptions); + } + + /** + * Lists all [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + * resources on a given Google Cloud project and region. + * + * The async variant is {@see self::listAzureClustersAsync()} . + * + * @param ListAzureClustersRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listAzureClusters(ListAzureClustersRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListAzureClusters', $request, $callOptions); + } + + /** + * Lists all [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + * resources on a given + * [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. + * + * The async variant is {@see self::listAzureNodePoolsAsync()} . + * + * @param ListAzureNodePoolsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listAzureNodePools(ListAzureNodePoolsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListAzureNodePools', $request, $callOptions); + } + + /** + * Updates an [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]. + * + * The async variant is {@see self::updateAzureClusterAsync()} . + * + * @param UpdateAzureClusterRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function updateAzureCluster(UpdateAzureClusterRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('UpdateAzureCluster', $request, $callOptions)->wait(); + } + + /** + * Updates an [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool]. + * + * The async variant is {@see self::updateAzureNodePoolAsync()} . + * + * @param UpdateAzureNodePoolRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function updateAzureNodePool(UpdateAzureNodePoolRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('UpdateAzureNodePool', $request, $callOptions)->wait(); + } +} diff --git a/GkeMultiCloud/src/V1/CreateAttachedClusterRequest.php b/GkeMultiCloud/src/V1/CreateAttachedClusterRequest.php index 9a3b0fc560e7..301f9ac6f9ed 100644 --- a/GkeMultiCloud/src/V1/CreateAttachedClusterRequest.php +++ b/GkeMultiCloud/src/V1/CreateAttachedClusterRequest.php @@ -52,6 +52,40 @@ class CreateAttachedClusterRequest extends \Google\Protobuf\Internal\Message */ private $validate_only = false; + /** + * @param string $parent Required. The parent location where this + * [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] resource + * will be created. + * + * Location names are formatted as `projects//locations/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud resource names. Please see + * {@see AttachedClustersClient::locationName()} for help formatting this field. + * @param \Google\Cloud\GkeMultiCloud\V1\AttachedCluster $attachedCluster Required. The specification of the + * [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] to create. + * @param string $attachedClusterId Required. A client provided ID the resource. Must be unique within the + * parent resource. + * + * The provided ID will be part of the + * [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] resource + * name formatted as + * `projects//locations//attachedClusters/`. + * + * Valid characters are `/[a-z][0-9]-/`. Cannot be longer than 63 characters. + * + * @return \Google\Cloud\GkeMultiCloud\V1\CreateAttachedClusterRequest + * + * @experimental + */ + public static function build(string $parent, \Google\Cloud\GkeMultiCloud\V1\AttachedCluster $attachedCluster, string $attachedClusterId): self + { + return (new self()) + ->setParent($parent) + ->setAttachedCluster($attachedCluster) + ->setAttachedClusterId($attachedClusterId); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/CreateAwsClusterRequest.php b/GkeMultiCloud/src/V1/CreateAwsClusterRequest.php index 878fe63fff74..b51f9782ca4a 100644 --- a/GkeMultiCloud/src/V1/CreateAwsClusterRequest.php +++ b/GkeMultiCloud/src/V1/CreateAwsClusterRequest.php @@ -52,6 +52,40 @@ class CreateAwsClusterRequest extends \Google\Protobuf\Internal\Message */ private $validate_only = false; + /** + * @param string $parent Required. The parent location where this + * [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource will be + * created. + * + * Location names are formatted as `projects//locations/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud resource names. Please see + * {@see AwsClustersClient::locationName()} for help formatting this field. + * @param \Google\Cloud\GkeMultiCloud\V1\AwsCluster $awsCluster Required. The specification of the + * [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] to create. + * @param string $awsClusterId Required. A client provided ID the resource. Must be unique within the + * parent resource. + * + * The provided ID will be part of the + * [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource name + * formatted as + * `projects//locations//awsClusters/`. + * + * Valid characters are `/[a-z][0-9]-/`. Cannot be longer than 63 characters. + * + * @return \Google\Cloud\GkeMultiCloud\V1\CreateAwsClusterRequest + * + * @experimental + */ + public static function build(string $parent, \Google\Cloud\GkeMultiCloud\V1\AwsCluster $awsCluster, string $awsClusterId): self + { + return (new self()) + ->setParent($parent) + ->setAwsCluster($awsCluster) + ->setAwsClusterId($awsClusterId); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/CreateAwsNodePoolRequest.php b/GkeMultiCloud/src/V1/CreateAwsNodePoolRequest.php index 7ae3b9fef711..f8e52fb6e59f 100644 --- a/GkeMultiCloud/src/V1/CreateAwsNodePoolRequest.php +++ b/GkeMultiCloud/src/V1/CreateAwsNodePoolRequest.php @@ -53,6 +53,40 @@ class CreateAwsNodePoolRequest extends \Google\Protobuf\Internal\Message */ private $validate_only = false; + /** + * @param string $parent Required. The [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + * resource where this node pool will be created. + * + * `AwsCluster` names are formatted as + * `projects//locations//awsClusters/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud resource names. Please see + * {@see AwsClustersClient::awsClusterName()} for help formatting this field. + * @param \Google\Cloud\GkeMultiCloud\V1\AwsNodePool $awsNodePool Required. The specification of the + * [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] to create. + * @param string $awsNodePoolId Required. A client provided ID the resource. Must be unique within the + * parent resource. + * + * The provided ID will be part of the + * [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] resource name + * formatted as + * `projects//locations//awsClusters//awsNodePools/`. + * + * Valid characters are `/[a-z][0-9]-/`. Cannot be longer than 63 characters. + * + * @return \Google\Cloud\GkeMultiCloud\V1\CreateAwsNodePoolRequest + * + * @experimental + */ + public static function build(string $parent, \Google\Cloud\GkeMultiCloud\V1\AwsNodePool $awsNodePool, string $awsNodePoolId): self + { + return (new self()) + ->setParent($parent) + ->setAwsNodePool($awsNodePool) + ->setAwsNodePoolId($awsNodePoolId); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/CreateAzureClientRequest.php b/GkeMultiCloud/src/V1/CreateAzureClientRequest.php index 37a7934caa9e..cf5549d7917c 100644 --- a/GkeMultiCloud/src/V1/CreateAzureClientRequest.php +++ b/GkeMultiCloud/src/V1/CreateAzureClientRequest.php @@ -52,6 +52,40 @@ class CreateAzureClientRequest extends \Google\Protobuf\Internal\Message */ private $validate_only = false; + /** + * @param string $parent Required. The parent location where this + * [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] resource will be + * created. + * + * Location names are formatted as `projects//locations/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud resource names. Please see + * {@see AzureClustersClient::locationName()} for help formatting this field. + * @param \Google\Cloud\GkeMultiCloud\V1\AzureClient $azureClient Required. The specification of the + * [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] to create. + * @param string $azureClientId Required. A client provided ID the resource. Must be unique within the + * parent resource. + * + * The provided ID will be part of the + * [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] resource name + * formatted as + * `projects//locations//azureClients/`. + * + * Valid characters are `/[a-z][0-9]-/`. Cannot be longer than 63 characters. + * + * @return \Google\Cloud\GkeMultiCloud\V1\CreateAzureClientRequest + * + * @experimental + */ + public static function build(string $parent, \Google\Cloud\GkeMultiCloud\V1\AzureClient $azureClient, string $azureClientId): self + { + return (new self()) + ->setParent($parent) + ->setAzureClient($azureClient) + ->setAzureClientId($azureClientId); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/CreateAzureClusterRequest.php b/GkeMultiCloud/src/V1/CreateAzureClusterRequest.php index a7ad4c813d2c..df2cb207a28a 100644 --- a/GkeMultiCloud/src/V1/CreateAzureClusterRequest.php +++ b/GkeMultiCloud/src/V1/CreateAzureClusterRequest.php @@ -52,6 +52,40 @@ class CreateAzureClusterRequest extends \Google\Protobuf\Internal\Message */ private $validate_only = false; + /** + * @param string $parent Required. The parent location where this + * [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] resource will be + * created. + * + * Location names are formatted as `projects//locations/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud resource names. Please see + * {@see AzureClustersClient::locationName()} for help formatting this field. + * @param \Google\Cloud\GkeMultiCloud\V1\AzureCluster $azureCluster Required. The specification of the + * [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] to create. + * @param string $azureClusterId Required. A client provided ID the resource. Must be unique within the + * parent resource. + * + * The provided ID will be part of the + * [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] resource name + * formatted as + * `projects//locations//azureClusters/`. + * + * Valid characters are `/[a-z][0-9]-/`. Cannot be longer than 63 characters. + * + * @return \Google\Cloud\GkeMultiCloud\V1\CreateAzureClusterRequest + * + * @experimental + */ + public static function build(string $parent, \Google\Cloud\GkeMultiCloud\V1\AzureCluster $azureCluster, string $azureClusterId): self + { + return (new self()) + ->setParent($parent) + ->setAzureCluster($azureCluster) + ->setAzureClusterId($azureClusterId); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/CreateAzureNodePoolRequest.php b/GkeMultiCloud/src/V1/CreateAzureNodePoolRequest.php index 7b09bd663f9c..79a319740af6 100644 --- a/GkeMultiCloud/src/V1/CreateAzureNodePoolRequest.php +++ b/GkeMultiCloud/src/V1/CreateAzureNodePoolRequest.php @@ -52,6 +52,39 @@ class CreateAzureNodePoolRequest extends \Google\Protobuf\Internal\Message */ private $validate_only = false; + /** + * @param string $parent Required. The [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + * resource where this node pool will be created. + * + * Location names are formatted as `projects//locations/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud resource names. Please see + * {@see AzureClustersClient::azureClusterName()} for help formatting this field. + * @param \Google\Cloud\GkeMultiCloud\V1\AzureNodePool $azureNodePool Required. The specification of the + * [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] to create. + * @param string $azureNodePoolId Required. A client provided ID the resource. Must be unique within the + * parent resource. + * + * The provided ID will be part of the + * [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] resource name + * formatted as + * `projects//locations//azureClusters//azureNodePools/`. + * + * Valid characters are `/[a-z][0-9]-/`. Cannot be longer than 63 characters. + * + * @return \Google\Cloud\GkeMultiCloud\V1\CreateAzureNodePoolRequest + * + * @experimental + */ + public static function build(string $parent, \Google\Cloud\GkeMultiCloud\V1\AzureNodePool $azureNodePool, string $azureNodePoolId): self + { + return (new self()) + ->setParent($parent) + ->setAzureNodePool($azureNodePool) + ->setAzureNodePoolId($azureNodePoolId); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/DeleteAttachedClusterRequest.php b/GkeMultiCloud/src/V1/DeleteAttachedClusterRequest.php index 5bc63e0e5182..5e7432150286 100644 --- a/GkeMultiCloud/src/V1/DeleteAttachedClusterRequest.php +++ b/GkeMultiCloud/src/V1/DeleteAttachedClusterRequest.php @@ -63,6 +63,27 @@ class DeleteAttachedClusterRequest extends \Google\Protobuf\Internal\Message */ private $etag = ''; + /** + * @param string $name Required. The resource name the + * [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] to delete. + * + * `AttachedCluster` names are formatted as + * `projects//locations//attachedClusters/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud Platform resource names. Please see + * {@see AttachedClustersClient::attachedClusterName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\DeleteAttachedClusterRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/DeleteAwsClusterRequest.php b/GkeMultiCloud/src/V1/DeleteAwsClusterRequest.php index a67ed19903b7..b6c25081142f 100644 --- a/GkeMultiCloud/src/V1/DeleteAwsClusterRequest.php +++ b/GkeMultiCloud/src/V1/DeleteAwsClusterRequest.php @@ -53,6 +53,27 @@ class DeleteAwsClusterRequest extends \Google\Protobuf\Internal\Message */ private $etag = ''; + /** + * @param string $name Required. The resource name the + * [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] to delete. + * + * `AwsCluster` names are formatted as + * `projects//locations//awsClusters/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud Platform resource names. Please see + * {@see AwsClustersClient::awsClusterName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\DeleteAwsClusterRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/DeleteAwsNodePoolRequest.php b/GkeMultiCloud/src/V1/DeleteAwsNodePoolRequest.php index 279e41bdb7c3..7c4d66a71ebe 100644 --- a/GkeMultiCloud/src/V1/DeleteAwsNodePoolRequest.php +++ b/GkeMultiCloud/src/V1/DeleteAwsNodePoolRequest.php @@ -54,6 +54,27 @@ class DeleteAwsNodePoolRequest extends \Google\Protobuf\Internal\Message */ private $etag = ''; + /** + * @param string $name Required. The resource name the + * [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] to delete. + * + * `AwsNodePool` names are formatted as + * `projects//locations//awsClusters//awsNodePools/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud resource names. Please see + * {@see AwsClustersClient::awsNodePoolName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\DeleteAwsNodePoolRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/DeleteAzureClientRequest.php b/GkeMultiCloud/src/V1/DeleteAzureClientRequest.php index b08c03ee705d..b0633da6b550 100644 --- a/GkeMultiCloud/src/V1/DeleteAzureClientRequest.php +++ b/GkeMultiCloud/src/V1/DeleteAzureClientRequest.php @@ -44,6 +44,28 @@ class DeleteAzureClientRequest extends \Google\Protobuf\Internal\Message */ private $validate_only = false; + /** + * @param string $name Required. The resource name the + * [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] to delete. + * + * [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] names are + * formatted as + * `projects//locations//azureClients/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud resource names. Please see + * {@see AzureClustersClient::azureClientName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\DeleteAzureClientRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/DeleteAzureClusterRequest.php b/GkeMultiCloud/src/V1/DeleteAzureClusterRequest.php index 9354374927a7..b1ea86f133fc 100644 --- a/GkeMultiCloud/src/V1/DeleteAzureClusterRequest.php +++ b/GkeMultiCloud/src/V1/DeleteAzureClusterRequest.php @@ -53,6 +53,27 @@ class DeleteAzureClusterRequest extends \Google\Protobuf\Internal\Message */ private $etag = ''; + /** + * @param string $name Required. The resource name the + * [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] to delete. + * + * `AzureCluster` names are formatted as + * `projects//locations//azureClusters/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud Platform resource names. Please see + * {@see AzureClustersClient::azureClusterName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\DeleteAzureClusterRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/DeleteAzureNodePoolRequest.php b/GkeMultiCloud/src/V1/DeleteAzureNodePoolRequest.php index 118b23f993c4..e5dae821e371 100644 --- a/GkeMultiCloud/src/V1/DeleteAzureNodePoolRequest.php +++ b/GkeMultiCloud/src/V1/DeleteAzureNodePoolRequest.php @@ -55,6 +55,27 @@ class DeleteAzureNodePoolRequest extends \Google\Protobuf\Internal\Message */ private $etag = ''; + /** + * @param string $name Required. The resource name the + * [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] to delete. + * + * `AzureNodePool` names are formatted as + * `projects//locations//azureClusters//azureNodePools/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud resource names. Please see + * {@see AzureClustersClient::azureNodePoolName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\DeleteAzureNodePoolRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/GenerateAttachedClusterInstallManifestRequest.php b/GkeMultiCloud/src/V1/GenerateAttachedClusterInstallManifestRequest.php index 80a66e90ff90..bdd8aa78dc74 100644 --- a/GkeMultiCloud/src/V1/GenerateAttachedClusterInstallManifestRequest.php +++ b/GkeMultiCloud/src/V1/GenerateAttachedClusterInstallManifestRequest.php @@ -53,6 +53,43 @@ class GenerateAttachedClusterInstallManifestRequest extends \Google\Protobuf\Int */ private $platform_version = ''; + /** + * @param string $parent Required. The parent location where this + * [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] resource + * will be created. + * + * Location names are formatted as `projects//locations/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud resource names. Please see + * {@see AttachedClustersClient::locationName()} for help formatting this field. + * @param string $attachedClusterId Required. A client provided ID of the resource. Must be unique within the + * parent resource. + * + * The provided ID will be part of the + * [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] resource + * name formatted as + * `projects//locations//attachedClusters/`. + * + * Valid characters are `/[a-z][0-9]-/`. Cannot be longer than 63 characters. + * + * When generating an install manifest for importing an existing Membership + * resource, the attached_cluster_id field must be the Membership id. + * + * Membership names are formatted as + * `projects//locations//memberships/`. + * + * @return \Google\Cloud\GkeMultiCloud\V1\GenerateAttachedClusterInstallManifestRequest + * + * @experimental + */ + public static function build(string $parent, string $attachedClusterId): self + { + return (new self()) + ->setParent($parent) + ->setAttachedClusterId($attachedClusterId); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/GetAttachedClusterRequest.php b/GkeMultiCloud/src/V1/GetAttachedClusterRequest.php index 09fefcdf2391..cc6b0532a72c 100644 --- a/GkeMultiCloud/src/V1/GetAttachedClusterRequest.php +++ b/GkeMultiCloud/src/V1/GetAttachedClusterRequest.php @@ -28,6 +28,28 @@ class GetAttachedClusterRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The name of the + * [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] resource + * to describe. + * + * `AttachedCluster` names are formatted as + * `projects//locations//attachedClusters/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud Platform resource names. Please see + * {@see AttachedClustersClient::attachedClusterName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\GetAttachedClusterRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/GetAttachedServerConfigRequest.php b/GkeMultiCloud/src/V1/GetAttachedServerConfigRequest.php index 8f0b463f18ce..1513a1dd1087 100644 --- a/GkeMultiCloud/src/V1/GetAttachedServerConfigRequest.php +++ b/GkeMultiCloud/src/V1/GetAttachedServerConfigRequest.php @@ -29,6 +29,28 @@ class GetAttachedServerConfigRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The name of the + * [AttachedServerConfig][google.cloud.gkemulticloud.v1.AttachedServerConfig] + * resource to describe. + * + * `AttachedServerConfig` names are formatted as + * `projects//locations//attachedServerConfig`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud resource names. Please see + * {@see AttachedClustersClient::attachedServerConfigName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\GetAttachedServerConfigRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/GetAwsClusterRequest.php b/GkeMultiCloud/src/V1/GetAwsClusterRequest.php index 7eaa0775ff6e..0ffbc250e084 100644 --- a/GkeMultiCloud/src/V1/GetAwsClusterRequest.php +++ b/GkeMultiCloud/src/V1/GetAwsClusterRequest.php @@ -28,6 +28,28 @@ class GetAwsClusterRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The name of the + * [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resource to + * describe. + * + * `AwsCluster` names are formatted as + * `projects//locations//awsClusters/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud Platform resource names. Please see + * {@see AwsClustersClient::awsClusterName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\GetAwsClusterRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/GetAwsNodePoolRequest.php b/GkeMultiCloud/src/V1/GetAwsNodePoolRequest.php index 0f57213bb1ce..3ba8153490bf 100644 --- a/GkeMultiCloud/src/V1/GetAwsNodePoolRequest.php +++ b/GkeMultiCloud/src/V1/GetAwsNodePoolRequest.php @@ -28,6 +28,28 @@ class GetAwsNodePoolRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The name of the + * [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] resource to + * describe. + * + * `AwsNodePool` names are formatted as + * `projects//locations//awsClusters//awsNodePools/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud resource names. Please see + * {@see AwsClustersClient::awsNodePoolName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\GetAwsNodePoolRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/GetAwsServerConfigRequest.php b/GkeMultiCloud/src/V1/GetAwsServerConfigRequest.php index 14bd0a54aef5..b7eff6dbf2dc 100644 --- a/GkeMultiCloud/src/V1/GetAwsServerConfigRequest.php +++ b/GkeMultiCloud/src/V1/GetAwsServerConfigRequest.php @@ -28,6 +28,28 @@ class GetAwsServerConfigRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The name of the + * [AwsServerConfig][google.cloud.gkemulticloud.v1.AwsServerConfig] resource + * to describe. + * + * `AwsServerConfig` names are formatted as + * `projects//locations//awsServerConfig`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud resource names. Please see + * {@see AwsClustersClient::awsServerConfigName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\GetAwsServerConfigRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/GetAzureClientRequest.php b/GkeMultiCloud/src/V1/GetAzureClientRequest.php index 6bd856707aa7..1cff6d467ea8 100644 --- a/GkeMultiCloud/src/V1/GetAzureClientRequest.php +++ b/GkeMultiCloud/src/V1/GetAzureClientRequest.php @@ -29,6 +29,29 @@ class GetAzureClientRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The name of the + * [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] resource to + * describe. + * + * [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] names are + * formatted as + * `projects//locations//azureClients/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud resource names. Please see + * {@see AzureClustersClient::azureClientName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\GetAzureClientRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/GetAzureClusterRequest.php b/GkeMultiCloud/src/V1/GetAzureClusterRequest.php index 72dd555a33b1..156772580440 100644 --- a/GkeMultiCloud/src/V1/GetAzureClusterRequest.php +++ b/GkeMultiCloud/src/V1/GetAzureClusterRequest.php @@ -28,6 +28,28 @@ class GetAzureClusterRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The name of the + * [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] resource to + * describe. + * + * `AzureCluster` names are formatted as + * `projects//locations//azureClusters/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud Platform resource names. Please see + * {@see AzureClustersClient::azureClusterName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\GetAzureClusterRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/GetAzureNodePoolRequest.php b/GkeMultiCloud/src/V1/GetAzureNodePoolRequest.php index 280bcba5691f..8f406b4d7358 100644 --- a/GkeMultiCloud/src/V1/GetAzureNodePoolRequest.php +++ b/GkeMultiCloud/src/V1/GetAzureNodePoolRequest.php @@ -28,6 +28,28 @@ class GetAzureNodePoolRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The name of the + * [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] resource to + * describe. + * + * `AzureNodePool` names are formatted as + * `projects//locations//azureClusters//azureNodePools/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud resource names. Please see + * {@see AzureClustersClient::azureNodePoolName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\GetAzureNodePoolRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/GetAzureServerConfigRequest.php b/GkeMultiCloud/src/V1/GetAzureServerConfigRequest.php index d3067f5c4acb..719887b2e9a5 100644 --- a/GkeMultiCloud/src/V1/GetAzureServerConfigRequest.php +++ b/GkeMultiCloud/src/V1/GetAzureServerConfigRequest.php @@ -28,6 +28,28 @@ class GetAzureServerConfigRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The name of the + * [AzureServerConfig][google.cloud.gkemulticloud.v1.AzureServerConfig] + * resource to describe. + * + * `AzureServerConfig` names are formatted as + * `projects//locations//azureServerConfig`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud resource names. Please see + * {@see AzureClustersClient::azureServerConfigName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\GetAzureServerConfigRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/ImportAttachedClusterRequest.php b/GkeMultiCloud/src/V1/ImportAttachedClusterRequest.php index bc11c4ca0d0f..934c9bcd1497 100644 --- a/GkeMultiCloud/src/V1/ImportAttachedClusterRequest.php +++ b/GkeMultiCloud/src/V1/ImportAttachedClusterRequest.php @@ -55,6 +55,29 @@ class ImportAttachedClusterRequest extends \Google\Protobuf\Internal\Message */ private $distribution = ''; + /** + * @param string $parent Required. The parent location where this + * [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] resource + * will be created. + * + * Location names are formatted as `projects//locations/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud resource names. Please see + * {@see AttachedClustersClient::locationName()} for help formatting this field. + * @param string $fleetMembership Required. The name of the fleet membership resource to import. + * + * @return \Google\Cloud\GkeMultiCloud\V1\ImportAttachedClusterRequest + * + * @experimental + */ + public static function build(string $parent, string $fleetMembership): self + { + return (new self()) + ->setParent($parent) + ->setFleetMembership($fleetMembership); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/ListAttachedClustersRequest.php b/GkeMultiCloud/src/V1/ListAttachedClustersRequest.php index 9a0d92d33a40..55aa669845b4 100644 --- a/GkeMultiCloud/src/V1/ListAttachedClustersRequest.php +++ b/GkeMultiCloud/src/V1/ListAttachedClustersRequest.php @@ -45,6 +45,26 @@ class ListAttachedClustersRequest extends \Google\Protobuf\Internal\Message */ private $page_token = ''; + /** + * @param string $parent Required. The parent location which owns this collection of + * [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] resources. + * + * Location names are formatted as `projects//locations/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud Platform resource names. Please see + * {@see AttachedClustersClient::locationName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\ListAttachedClustersRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/ListAwsClustersRequest.php b/GkeMultiCloud/src/V1/ListAwsClustersRequest.php index 844fdfa21aa5..0333c6b08863 100644 --- a/GkeMultiCloud/src/V1/ListAwsClustersRequest.php +++ b/GkeMultiCloud/src/V1/ListAwsClustersRequest.php @@ -45,6 +45,26 @@ class ListAwsClustersRequest extends \Google\Protobuf\Internal\Message */ private $page_token = ''; + /** + * @param string $parent Required. The parent location which owns this collection of + * [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] resources. + * + * Location names are formatted as `projects//locations/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud Platform resource names. Please see + * {@see AwsClustersClient::locationName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\ListAwsClustersRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/ListAwsNodePoolsRequest.php b/GkeMultiCloud/src/V1/ListAwsNodePoolsRequest.php index 4a124caab83b..a2613f9a2e82 100644 --- a/GkeMultiCloud/src/V1/ListAwsNodePoolsRequest.php +++ b/GkeMultiCloud/src/V1/ListAwsNodePoolsRequest.php @@ -46,6 +46,27 @@ class ListAwsNodePoolsRequest extends \Google\Protobuf\Internal\Message */ private $page_token = ''; + /** + * @param string $parent Required. The parent `AwsCluster` which owns this collection of + * [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] resources. + * + * `AwsCluster` names are formatted as + * `projects//locations//awsClusters/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud resource names. Please see + * {@see AwsClustersClient::awsClusterName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\ListAwsNodePoolsRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/ListAzureClientsRequest.php b/GkeMultiCloud/src/V1/ListAzureClientsRequest.php index 796e03512f8a..55271adcd723 100644 --- a/GkeMultiCloud/src/V1/ListAzureClientsRequest.php +++ b/GkeMultiCloud/src/V1/ListAzureClientsRequest.php @@ -45,6 +45,26 @@ class ListAzureClientsRequest extends \Google\Protobuf\Internal\Message */ private $page_token = ''; + /** + * @param string $parent Required. The parent location which owns this collection of + * [AzureClient][google.cloud.gkemulticloud.v1.AzureClient] resources. + * + * Location names are formatted as `projects//locations/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud Platform resource names. Please see + * {@see AzureClustersClient::locationName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\ListAzureClientsRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/ListAzureClustersRequest.php b/GkeMultiCloud/src/V1/ListAzureClustersRequest.php index ac4bccf25bc5..fd27ca16f6bf 100644 --- a/GkeMultiCloud/src/V1/ListAzureClustersRequest.php +++ b/GkeMultiCloud/src/V1/ListAzureClustersRequest.php @@ -45,6 +45,26 @@ class ListAzureClustersRequest extends \Google\Protobuf\Internal\Message */ private $page_token = ''; + /** + * @param string $parent Required. The parent location which owns this collection of + * [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] resources. + * + * Location names are formatted as `projects//locations/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud Platform resource names. Please see + * {@see AzureClustersClient::locationName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\ListAzureClustersRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/ListAzureNodePoolsRequest.php b/GkeMultiCloud/src/V1/ListAzureNodePoolsRequest.php index 7db6022e2813..6bc2ea1ea9b8 100644 --- a/GkeMultiCloud/src/V1/ListAzureNodePoolsRequest.php +++ b/GkeMultiCloud/src/V1/ListAzureNodePoolsRequest.php @@ -46,6 +46,27 @@ class ListAzureNodePoolsRequest extends \Google\Protobuf\Internal\Message */ private $page_token = ''; + /** + * @param string $parent Required. The parent `AzureCluster` which owns this collection of + * [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] resources. + * + * `AzureCluster` names are formatted as + * `projects//locations//azureClusters/`. + * + * See [Resource Names](https://cloud.google.com/apis/design/resource_names) + * for more details on Google Cloud resource names. Please see + * {@see AzureClustersClient::azureClusterName()} for help formatting this field. + * + * @return \Google\Cloud\GkeMultiCloud\V1\ListAzureNodePoolsRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/UpdateAttachedClusterRequest.php b/GkeMultiCloud/src/V1/UpdateAttachedClusterRequest.php index 1fe3553467e9..e140ffe081a1 100644 --- a/GkeMultiCloud/src/V1/UpdateAttachedClusterRequest.php +++ b/GkeMultiCloud/src/V1/UpdateAttachedClusterRequest.php @@ -45,6 +45,33 @@ class UpdateAttachedClusterRequest extends \Google\Protobuf\Internal\Message */ private $update_mask = null; + /** + * @param \Google\Cloud\GkeMultiCloud\V1\AttachedCluster $attachedCluster Required. The + * [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster] resource + * to update. + * @param \Google\Protobuf\FieldMask $updateMask Required. Mask of fields to update. At least one path must be supplied in + * this field. The elements of the repeated paths field can only include these + * fields from + * [AttachedCluster][google.cloud.gkemulticloud.v1.AttachedCluster]: + * + * * `description`. + * * `annotations`. + * * `platform_version`. + * * `authorization.admin_users`. + * * `logging_config.component_config.enable_components`. + * * `monitoring_config.managed_prometheus_config.enabled`. + * + * @return \Google\Cloud\GkeMultiCloud\V1\UpdateAttachedClusterRequest + * + * @experimental + */ + public static function build(\Google\Cloud\GkeMultiCloud\V1\AttachedCluster $attachedCluster, \Google\Protobuf\FieldMask $updateMask): self + { + return (new self()) + ->setAttachedCluster($attachedCluster) + ->setUpdateMask($updateMask); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/UpdateAwsClusterRequest.php b/GkeMultiCloud/src/V1/UpdateAwsClusterRequest.php index fe65ffffd6fd..7cad294bf907 100644 --- a/GkeMultiCloud/src/V1/UpdateAwsClusterRequest.php +++ b/GkeMultiCloud/src/V1/UpdateAwsClusterRequest.php @@ -60,6 +60,48 @@ class UpdateAwsClusterRequest extends \Google\Protobuf\Internal\Message */ private $update_mask = null; + /** + * @param \Google\Cloud\GkeMultiCloud\V1\AwsCluster $awsCluster Required. The [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster] + * resource to update. + * @param \Google\Protobuf\FieldMask $updateMask Required. Mask of fields to update. At least one path must be supplied in + * this field. The elements of the repeated paths field can only include these + * fields from [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]: + * + * * `description`. + * * `annotations`. + * * `control_plane.version`. + * * `authorization.admin_users`. + * * `control_plane.aws_services_authentication.role_arn`. + * * `control_plane.aws_services_authentication.role_session_name`. + * * `control_plane.config_encryption.kms_key_arn`. + * * `control_plane.instance_type`. + * * `control_plane.security_group_ids`. + * * `control_plane.proxy_config`. + * * `control_plane.proxy_config.secret_arn`. + * * `control_plane.proxy_config.secret_version`. + * * `control_plane.root_volume.size_gib`. + * * `control_plane.root_volume.volume_type`. + * * `control_plane.root_volume.iops`. + * * `control_plane.root_volume.kms_key_arn`. + * * `control_plane.ssh_config`. + * * `control_plane.ssh_config.ec2_key_pair`. + * * `control_plane.instance_placement.tenancy`. + * * `control_plane.iam_instance_profile`. + * * `logging_config.component_config.enable_components`. + * * `control_plane.tags`. + * * `monitoring_config.managed_prometheus_config.enabled`. + * + * @return \Google\Cloud\GkeMultiCloud\V1\UpdateAwsClusterRequest + * + * @experimental + */ + public static function build(\Google\Cloud\GkeMultiCloud\V1\AwsCluster $awsCluster, \Google\Protobuf\FieldMask $updateMask): self + { + return (new self()) + ->setAwsCluster($awsCluster) + ->setUpdateMask($updateMask); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/UpdateAwsNodePoolRequest.php b/GkeMultiCloud/src/V1/UpdateAwsNodePoolRequest.php index a514f1ceda50..ec398db6a8f1 100644 --- a/GkeMultiCloud/src/V1/UpdateAwsNodePoolRequest.php +++ b/GkeMultiCloud/src/V1/UpdateAwsNodePoolRequest.php @@ -59,6 +59,47 @@ class UpdateAwsNodePoolRequest extends \Google\Protobuf\Internal\Message */ private $update_mask = null; + /** + * @param \Google\Cloud\GkeMultiCloud\V1\AwsNodePool $awsNodePool Required. The [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool] + * resource to update. + * @param \Google\Protobuf\FieldMask $updateMask Required. Mask of fields to update. At least one path must be supplied in + * this field. The elements of the repeated paths field can only include these + * fields from [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool]: + * + * * `annotations`. + * * `version`. + * * `autoscaling.min_node_count`. + * * `autoscaling.max_node_count`. + * * `config.config_encryption.kms_key_arn`. + * * `config.security_group_ids`. + * * `config.root_volume.iops`. + * * `config.root_volume.kms_key_arn`. + * * `config.root_volume.volume_type`. + * * `config.root_volume.size_gib`. + * * `config.proxy_config`. + * * `config.proxy_config.secret_arn`. + * * `config.proxy_config.secret_version`. + * * `config.ssh_config`. + * * `config.ssh_config.ec2_key_pair`. + * * `config.instance_placement.tenancy`. + * * `config.iam_instance_profile`. + * * `config.labels`. + * * `config.tags`. + * * `config.autoscaling_metrics_collection`. + * * `config.autoscaling_metrics_collection.granularity`. + * * `config.autoscaling_metrics_collection.metrics`. + * + * @return \Google\Cloud\GkeMultiCloud\V1\UpdateAwsNodePoolRequest + * + * @experimental + */ + public static function build(\Google\Cloud\GkeMultiCloud\V1\AwsNodePool $awsNodePool, \Google\Protobuf\FieldMask $updateMask): self + { + return (new self()) + ->setAwsNodePool($awsNodePool) + ->setUpdateMask($updateMask); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/UpdateAzureClusterRequest.php b/GkeMultiCloud/src/V1/UpdateAzureClusterRequest.php index 54bcbad0783e..2d5c00754b6d 100644 --- a/GkeMultiCloud/src/V1/UpdateAzureClusterRequest.php +++ b/GkeMultiCloud/src/V1/UpdateAzureClusterRequest.php @@ -53,6 +53,41 @@ class UpdateAzureClusterRequest extends \Google\Protobuf\Internal\Message */ private $update_mask = null; + /** + * @param \Google\Cloud\GkeMultiCloud\V1\AzureCluster $azureCluster Required. The [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster] + * resource to update. + * @param \Google\Protobuf\FieldMask $updateMask Required. Mask of fields to update. At least one path must be supplied in + * this field. The elements of the repeated paths field can only include these + * fields from [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]: + * + * * `description`. + * * `azureClient`. + * * `control_plane.version`. + * * `control_plane.vm_size`. + * * `annotations`. + * * `authorization.admin_users`. + * * `control_plane.root_volume.size_gib`. + * * `azure_services_authentication`. + * * `azure_services_authentication.tenant_id`. + * * `azure_services_authentication.application_id`. + * * `control_plane.proxy_config`. + * * `control_plane.proxy_config.resource_group_id`. + * * `control_plane.proxy_config.secret_id`. + * * `control_plane.ssh_config.authorized_key`. + * * `logging_config.component_config.enable_components` + * * `monitoring_config.managed_prometheus_config.enabled`. + * + * @return \Google\Cloud\GkeMultiCloud\V1\UpdateAzureClusterRequest + * + * @experimental + */ + public static function build(\Google\Cloud\GkeMultiCloud\V1\AzureCluster $azureCluster, \Google\Protobuf\FieldMask $updateMask): self + { + return (new self()) + ->setAzureCluster($azureCluster) + ->setUpdateMask($updateMask); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/UpdateAzureNodePoolRequest.php b/GkeMultiCloud/src/V1/UpdateAzureNodePoolRequest.php index 3221a2fc59fc..050bbdc857e1 100644 --- a/GkeMultiCloud/src/V1/UpdateAzureNodePoolRequest.php +++ b/GkeMultiCloud/src/V1/UpdateAzureNodePoolRequest.php @@ -42,6 +42,30 @@ class UpdateAzureNodePoolRequest extends \Google\Protobuf\Internal\Message */ private $update_mask = null; + /** + * @param \Google\Cloud\GkeMultiCloud\V1\AzureNodePool $azureNodePool Required. The [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool] + * resource to update. + * @param \Google\Protobuf\FieldMask $updateMask Required. Mask of fields to update. At least one path must be supplied in + * this field. The elements of the repeated paths field can only include these + * fields from [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool]: + * + * *. `annotations`. + * * `version`. + * * `autoscaling.min_node_count`. + * * `autoscaling.max_node_count`. + * * `config.ssh_config.authorized_key`. + * + * @return \Google\Cloud\GkeMultiCloud\V1\UpdateAzureNodePoolRequest + * + * @experimental + */ + public static function build(\Google\Cloud\GkeMultiCloud\V1\AzureNodePool $azureNodePool, \Google\Protobuf\FieldMask $updateMask): self + { + return (new self()) + ->setAzureNodePool($azureNodePool) + ->setUpdateMask($updateMask); + } + /** * Constructor. * diff --git a/GkeMultiCloud/src/V1/resources/attached_clusters_descriptor_config.php b/GkeMultiCloud/src/V1/resources/attached_clusters_descriptor_config.php index 7fd39638c34b..ae4a8852eeec 100644 --- a/GkeMultiCloud/src/V1/resources/attached_clusters_descriptor_config.php +++ b/GkeMultiCloud/src/V1/resources/attached_clusters_descriptor_config.php @@ -12,6 +12,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'DeleteAttachedCluster' => [ 'longRunning' => [ @@ -22,6 +31,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'ImportAttachedCluster' => [ 'longRunning' => [ @@ -32,6 +50,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'UpdateAttachedCluster' => [ 'longRunning' => [ @@ -42,6 +69,52 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'attached_cluster.name', + 'fieldAccessors' => [ + 'getAttachedCluster', + 'getName', + ], + ], + ], + ], + 'GenerateAttachedClusterInstallManifest' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GkeMultiCloud\V1\GenerateAttachedClusterInstallManifestResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'GetAttachedCluster' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GkeMultiCloud\V1\AttachedCluster', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetAttachedServerConfig' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GkeMultiCloud\V1\AttachedServerConfig', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'ListAttachedClusters' => [ 'pageStreaming' => [ @@ -52,6 +125,21 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getAttachedClusters', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\GkeMultiCloud\V1\ListAttachedClustersResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'templateMap' => [ + 'attachedCluster' => 'projects/{project}/locations/{location}/attachedClusters/{attached_cluster}', + 'attachedServerConfig' => 'projects/{project}/locations/{location}/attachedServerConfig', + 'location' => 'projects/{project}/locations/{location}', ], ], ], diff --git a/GkeMultiCloud/src/V1/resources/aws_clusters_descriptor_config.php b/GkeMultiCloud/src/V1/resources/aws_clusters_descriptor_config.php index 9a86fcf0c4b2..96093aa25a3c 100644 --- a/GkeMultiCloud/src/V1/resources/aws_clusters_descriptor_config.php +++ b/GkeMultiCloud/src/V1/resources/aws_clusters_descriptor_config.php @@ -12,6 +12,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'CreateAwsNodePool' => [ 'longRunning' => [ @@ -22,6 +31,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'DeleteAwsCluster' => [ 'longRunning' => [ @@ -32,6 +50,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'DeleteAwsNodePool' => [ 'longRunning' => [ @@ -42,6 +69,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'UpdateAwsCluster' => [ 'longRunning' => [ @@ -52,6 +88,16 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'aws_cluster.name', + 'fieldAccessors' => [ + 'getAwsCluster', + 'getName', + ], + ], + ], ], 'UpdateAwsNodePool' => [ 'longRunning' => [ @@ -62,6 +108,64 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'aws_node_pool.name', + 'fieldAccessors' => [ + 'getAwsNodePool', + 'getName', + ], + ], + ], + ], + 'GenerateAwsAccessToken' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GkeMultiCloud\V1\GenerateAwsAccessTokenResponse', + 'headerParams' => [ + [ + 'keyName' => 'aws_cluster', + 'fieldAccessors' => [ + 'getAwsCluster', + ], + ], + ], + ], + 'GetAwsCluster' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GkeMultiCloud\V1\AwsCluster', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetAwsNodePool' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GkeMultiCloud\V1\AwsNodePool', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetAwsServerConfig' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GkeMultiCloud\V1\AwsServerConfig', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'ListAwsClusters' => [ 'pageStreaming' => [ @@ -72,6 +176,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getAwsClusters', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\GkeMultiCloud\V1\ListAwsClustersResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'ListAwsNodePools' => [ 'pageStreaming' => [ @@ -82,6 +196,22 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getAwsNodePools', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\GkeMultiCloud\V1\ListAwsNodePoolsResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'templateMap' => [ + 'awsCluster' => 'projects/{project}/locations/{location}/awsClusters/{aws_cluster}', + 'awsNodePool' => 'projects/{project}/locations/{location}/awsClusters/{aws_cluster}/awsNodePools/{aws_node_pool}', + 'awsServerConfig' => 'projects/{project}/locations/{location}/awsServerConfig', + 'location' => 'projects/{project}/locations/{location}', ], ], ], diff --git a/GkeMultiCloud/src/V1/resources/azure_clusters_descriptor_config.php b/GkeMultiCloud/src/V1/resources/azure_clusters_descriptor_config.php index b2d05d9d141f..d2bb16b41b19 100644 --- a/GkeMultiCloud/src/V1/resources/azure_clusters_descriptor_config.php +++ b/GkeMultiCloud/src/V1/resources/azure_clusters_descriptor_config.php @@ -12,6 +12,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'CreateAzureCluster' => [ 'longRunning' => [ @@ -22,6 +31,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'CreateAzureNodePool' => [ 'longRunning' => [ @@ -32,6 +50,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'DeleteAzureClient' => [ 'longRunning' => [ @@ -42,6 +69,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'DeleteAzureCluster' => [ 'longRunning' => [ @@ -52,6 +88,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'DeleteAzureNodePool' => [ 'longRunning' => [ @@ -62,6 +107,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'UpdateAzureCluster' => [ 'longRunning' => [ @@ -72,6 +126,16 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'azure_cluster.name', + 'fieldAccessors' => [ + 'getAzureCluster', + 'getName', + ], + ], + ], ], 'UpdateAzureNodePool' => [ 'longRunning' => [ @@ -82,6 +146,76 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'azure_node_pool.name', + 'fieldAccessors' => [ + 'getAzureNodePool', + 'getName', + ], + ], + ], + ], + 'GenerateAzureAccessToken' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GkeMultiCloud\V1\GenerateAzureAccessTokenResponse', + 'headerParams' => [ + [ + 'keyName' => 'azure_cluster', + 'fieldAccessors' => [ + 'getAzureCluster', + ], + ], + ], + ], + 'GetAzureClient' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GkeMultiCloud\V1\AzureClient', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetAzureCluster' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GkeMultiCloud\V1\AzureCluster', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetAzureNodePool' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GkeMultiCloud\V1\AzureNodePool', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetAzureServerConfig' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\GkeMultiCloud\V1\AzureServerConfig', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'ListAzureClients' => [ 'pageStreaming' => [ @@ -92,6 +226,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getAzureClients', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\GkeMultiCloud\V1\ListAzureClientsResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'ListAzureClusters' => [ 'pageStreaming' => [ @@ -102,6 +246,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getAzureClusters', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\GkeMultiCloud\V1\ListAzureClustersResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'ListAzureNodePools' => [ 'pageStreaming' => [ @@ -112,6 +266,23 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getAzureNodePools', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\GkeMultiCloud\V1\ListAzureNodePoolsResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'templateMap' => [ + 'azureClient' => 'projects/{project}/locations/{location}/azureClients/{azure_client}', + 'azureCluster' => 'projects/{project}/locations/{location}/azureClusters/{azure_cluster}', + 'azureNodePool' => 'projects/{project}/locations/{location}/azureClusters/{azure_cluster}/azureNodePools/{azure_node_pool}', + 'azureServerConfig' => 'projects/{project}/locations/{location}/azureServerConfig', + 'location' => 'projects/{project}/locations/{location}', ], ], ], diff --git a/GkeMultiCloud/tests/Unit/V1/Client/AttachedClustersClientTest.php b/GkeMultiCloud/tests/Unit/V1/Client/AttachedClustersClientTest.php new file mode 100644 index 000000000000..fd2d633592c2 --- /dev/null +++ b/GkeMultiCloud/tests/Unit/V1/Client/AttachedClustersClientTest.php @@ -0,0 +1,1086 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return AttachedClustersClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new AttachedClustersClient($options); + } + + /** @test */ + public function createAttachedClusterTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createAttachedClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $description = 'description-1724546052'; + $platformVersion = 'platformVersion1813514508'; + $distribution = 'distribution-1580708220'; + $clusterRegion = 'clusterRegion993903833'; + $uid = 'uid115792'; + $reconciling = false; + $etag = 'etag3123477'; + $kubernetesVersion = 'kubernetesVersion50850015'; + $expectedResponse = new AttachedCluster(); + $expectedResponse->setName($name); + $expectedResponse->setDescription($description); + $expectedResponse->setPlatformVersion($platformVersion); + $expectedResponse->setDistribution($distribution); + $expectedResponse->setClusterRegion($clusterRegion); + $expectedResponse->setUid($uid); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setEtag($etag); + $expectedResponse->setKubernetesVersion($kubernetesVersion); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createAttachedClusterTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $attachedCluster = new AttachedCluster(); + $attachedClusterOidcConfig = new AttachedOidcConfig(); + $attachedCluster->setOidcConfig($attachedClusterOidcConfig); + $attachedClusterPlatformVersion = 'attachedClusterPlatformVersion-208126385'; + $attachedCluster->setPlatformVersion($attachedClusterPlatformVersion); + $attachedClusterDistribution = 'attachedClusterDistribution1692601690'; + $attachedCluster->setDistribution($attachedClusterDistribution); + $attachedClusterFleet = new Fleet(); + $fleetProject = 'fleetProject604893675'; + $attachedClusterFleet->setProject($fleetProject); + $attachedCluster->setFleet($attachedClusterFleet); + $attachedClusterId = 'attachedClusterId-249426181'; + $request = (new CreateAttachedClusterRequest()) + ->setParent($formattedParent) + ->setAttachedCluster($attachedCluster) + ->setAttachedClusterId($attachedClusterId); + $response = $gapicClient->createAttachedCluster($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AttachedClusters/CreateAttachedCluster', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getAttachedCluster(); + $this->assertProtobufEquals($attachedCluster, $actualValue); + $actualValue = $actualApiRequestObject->getAttachedClusterId(); + $this->assertProtobufEquals($attachedClusterId, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createAttachedClusterTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createAttachedClusterExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createAttachedClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $attachedCluster = new AttachedCluster(); + $attachedClusterOidcConfig = new AttachedOidcConfig(); + $attachedCluster->setOidcConfig($attachedClusterOidcConfig); + $attachedClusterPlatformVersion = 'attachedClusterPlatformVersion-208126385'; + $attachedCluster->setPlatformVersion($attachedClusterPlatformVersion); + $attachedClusterDistribution = 'attachedClusterDistribution1692601690'; + $attachedCluster->setDistribution($attachedClusterDistribution); + $attachedClusterFleet = new Fleet(); + $fleetProject = 'fleetProject604893675'; + $attachedClusterFleet->setProject($fleetProject); + $attachedCluster->setFleet($attachedClusterFleet); + $attachedClusterId = 'attachedClusterId-249426181'; + $request = (new CreateAttachedClusterRequest()) + ->setParent($formattedParent) + ->setAttachedCluster($attachedCluster) + ->setAttachedClusterId($attachedClusterId); + $response = $gapicClient->createAttachedCluster($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createAttachedClusterTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteAttachedClusterTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteAttachedClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new GPBEmpty(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/deleteAttachedClusterTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedName = $gapicClient->attachedClusterName('[PROJECT]', '[LOCATION]', '[ATTACHED_CLUSTER]'); + $request = (new DeleteAttachedClusterRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteAttachedCluster($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AttachedClusters/DeleteAttachedCluster', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteAttachedClusterTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteAttachedClusterExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteAttachedClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->attachedClusterName('[PROJECT]', '[LOCATION]', '[ATTACHED_CLUSTER]'); + $request = (new DeleteAttachedClusterRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteAttachedCluster($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteAttachedClusterTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function generateAttachedClusterInstallManifestTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $manifest = 'manifest130625071'; + $expectedResponse = new GenerateAttachedClusterInstallManifestResponse(); + $expectedResponse->setManifest($manifest); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $attachedClusterId = 'attachedClusterId-249426181'; + $platformVersion = 'platformVersion1813514508'; + $request = (new GenerateAttachedClusterInstallManifestRequest()) + ->setParent($formattedParent) + ->setAttachedClusterId($attachedClusterId) + ->setPlatformVersion($platformVersion); + $response = $gapicClient->generateAttachedClusterInstallManifest($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AttachedClusters/GenerateAttachedClusterInstallManifest', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualRequestObject->getAttachedClusterId(); + $this->assertProtobufEquals($attachedClusterId, $actualValue); + $actualValue = $actualRequestObject->getPlatformVersion(); + $this->assertProtobufEquals($platformVersion, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function generateAttachedClusterInstallManifestExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $attachedClusterId = 'attachedClusterId-249426181'; + $platformVersion = 'platformVersion1813514508'; + $request = (new GenerateAttachedClusterInstallManifestRequest()) + ->setParent($formattedParent) + ->setAttachedClusterId($attachedClusterId) + ->setPlatformVersion($platformVersion); + try { + $gapicClient->generateAttachedClusterInstallManifest($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getAttachedClusterTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $description = 'description-1724546052'; + $platformVersion = 'platformVersion1813514508'; + $distribution = 'distribution-1580708220'; + $clusterRegion = 'clusterRegion993903833'; + $uid = 'uid115792'; + $reconciling = false; + $etag = 'etag3123477'; + $kubernetesVersion = 'kubernetesVersion50850015'; + $expectedResponse = new AttachedCluster(); + $expectedResponse->setName($name2); + $expectedResponse->setDescription($description); + $expectedResponse->setPlatformVersion($platformVersion); + $expectedResponse->setDistribution($distribution); + $expectedResponse->setClusterRegion($clusterRegion); + $expectedResponse->setUid($uid); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setEtag($etag); + $expectedResponse->setKubernetesVersion($kubernetesVersion); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->attachedClusterName('[PROJECT]', '[LOCATION]', '[ATTACHED_CLUSTER]'); + $request = (new GetAttachedClusterRequest()) + ->setName($formattedName); + $response = $gapicClient->getAttachedCluster($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AttachedClusters/GetAttachedCluster', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getAttachedClusterExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->attachedClusterName('[PROJECT]', '[LOCATION]', '[ATTACHED_CLUSTER]'); + $request = (new GetAttachedClusterRequest()) + ->setName($formattedName); + try { + $gapicClient->getAttachedCluster($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getAttachedServerConfigTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $expectedResponse = new AttachedServerConfig(); + $expectedResponse->setName($name2); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->attachedServerConfigName('[PROJECT]', '[LOCATION]'); + $request = (new GetAttachedServerConfigRequest()) + ->setName($formattedName); + $response = $gapicClient->getAttachedServerConfig($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AttachedClusters/GetAttachedServerConfig', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getAttachedServerConfigExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->attachedServerConfigName('[PROJECT]', '[LOCATION]'); + $request = (new GetAttachedServerConfigRequest()) + ->setName($formattedName); + try { + $gapicClient->getAttachedServerConfig($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function importAttachedClusterTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/importAttachedClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $description = 'description-1724546052'; + $platformVersion2 = 'platformVersion2-969276993'; + $distribution2 = 'distribution21357826359'; + $clusterRegion = 'clusterRegion993903833'; + $uid = 'uid115792'; + $reconciling = false; + $etag = 'etag3123477'; + $kubernetesVersion = 'kubernetesVersion50850015'; + $expectedResponse = new AttachedCluster(); + $expectedResponse->setName($name); + $expectedResponse->setDescription($description); + $expectedResponse->setPlatformVersion($platformVersion2); + $expectedResponse->setDistribution($distribution2); + $expectedResponse->setClusterRegion($clusterRegion); + $expectedResponse->setUid($uid); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setEtag($etag); + $expectedResponse->setKubernetesVersion($kubernetesVersion); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/importAttachedClusterTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $fleetMembership = 'fleetMembership1817977703'; + $platformVersion = 'platformVersion1813514508'; + $distribution = 'distribution-1580708220'; + $request = (new ImportAttachedClusterRequest()) + ->setParent($formattedParent) + ->setFleetMembership($fleetMembership) + ->setPlatformVersion($platformVersion) + ->setDistribution($distribution); + $response = $gapicClient->importAttachedCluster($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AttachedClusters/ImportAttachedCluster', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getFleetMembership(); + $this->assertProtobufEquals($fleetMembership, $actualValue); + $actualValue = $actualApiRequestObject->getPlatformVersion(); + $this->assertProtobufEquals($platformVersion, $actualValue); + $actualValue = $actualApiRequestObject->getDistribution(); + $this->assertProtobufEquals($distribution, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/importAttachedClusterTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function importAttachedClusterExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/importAttachedClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $fleetMembership = 'fleetMembership1817977703'; + $platformVersion = 'platformVersion1813514508'; + $distribution = 'distribution-1580708220'; + $request = (new ImportAttachedClusterRequest()) + ->setParent($formattedParent) + ->setFleetMembership($fleetMembership) + ->setPlatformVersion($platformVersion) + ->setDistribution($distribution); + $response = $gapicClient->importAttachedCluster($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/importAttachedClusterTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function listAttachedClustersTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $attachedClustersElement = new AttachedCluster(); + $attachedClusters = [ + $attachedClustersElement, + ]; + $expectedResponse = new ListAttachedClustersResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setAttachedClusters($attachedClusters); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListAttachedClustersRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listAttachedClusters($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getAttachedClusters()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AttachedClusters/ListAttachedClusters', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listAttachedClustersExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListAttachedClustersRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listAttachedClusters($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function updateAttachedClusterTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateAttachedClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $description = 'description-1724546052'; + $platformVersion = 'platformVersion1813514508'; + $distribution = 'distribution-1580708220'; + $clusterRegion = 'clusterRegion993903833'; + $uid = 'uid115792'; + $reconciling = false; + $etag = 'etag3123477'; + $kubernetesVersion = 'kubernetesVersion50850015'; + $expectedResponse = new AttachedCluster(); + $expectedResponse->setName($name); + $expectedResponse->setDescription($description); + $expectedResponse->setPlatformVersion($platformVersion); + $expectedResponse->setDistribution($distribution); + $expectedResponse->setClusterRegion($clusterRegion); + $expectedResponse->setUid($uid); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setEtag($etag); + $expectedResponse->setKubernetesVersion($kubernetesVersion); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/updateAttachedClusterTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $attachedCluster = new AttachedCluster(); + $attachedClusterOidcConfig = new AttachedOidcConfig(); + $attachedCluster->setOidcConfig($attachedClusterOidcConfig); + $attachedClusterPlatformVersion = 'attachedClusterPlatformVersion-208126385'; + $attachedCluster->setPlatformVersion($attachedClusterPlatformVersion); + $attachedClusterDistribution = 'attachedClusterDistribution1692601690'; + $attachedCluster->setDistribution($attachedClusterDistribution); + $attachedClusterFleet = new Fleet(); + $fleetProject = 'fleetProject604893675'; + $attachedClusterFleet->setProject($fleetProject); + $attachedCluster->setFleet($attachedClusterFleet); + $updateMask = new FieldMask(); + $request = (new UpdateAttachedClusterRequest()) + ->setAttachedCluster($attachedCluster) + ->setUpdateMask($updateMask); + $response = $gapicClient->updateAttachedCluster($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AttachedClusters/UpdateAttachedCluster', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getAttachedCluster(); + $this->assertProtobufEquals($attachedCluster, $actualValue); + $actualValue = $actualApiRequestObject->getUpdateMask(); + $this->assertProtobufEquals($updateMask, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateAttachedClusterTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateAttachedClusterExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateAttachedClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $attachedCluster = new AttachedCluster(); + $attachedClusterOidcConfig = new AttachedOidcConfig(); + $attachedCluster->setOidcConfig($attachedClusterOidcConfig); + $attachedClusterPlatformVersion = 'attachedClusterPlatformVersion-208126385'; + $attachedCluster->setPlatformVersion($attachedClusterPlatformVersion); + $attachedClusterDistribution = 'attachedClusterDistribution1692601690'; + $attachedCluster->setDistribution($attachedClusterDistribution); + $attachedClusterFleet = new Fleet(); + $fleetProject = 'fleetProject604893675'; + $attachedClusterFleet->setProject($fleetProject); + $attachedCluster->setFleet($attachedClusterFleet); + $updateMask = new FieldMask(); + $request = (new UpdateAttachedClusterRequest()) + ->setAttachedCluster($attachedCluster) + ->setUpdateMask($updateMask); + $response = $gapicClient->updateAttachedCluster($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateAttachedClusterTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createAttachedClusterAsyncTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createAttachedClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $description = 'description-1724546052'; + $platformVersion = 'platformVersion1813514508'; + $distribution = 'distribution-1580708220'; + $clusterRegion = 'clusterRegion993903833'; + $uid = 'uid115792'; + $reconciling = false; + $etag = 'etag3123477'; + $kubernetesVersion = 'kubernetesVersion50850015'; + $expectedResponse = new AttachedCluster(); + $expectedResponse->setName($name); + $expectedResponse->setDescription($description); + $expectedResponse->setPlatformVersion($platformVersion); + $expectedResponse->setDistribution($distribution); + $expectedResponse->setClusterRegion($clusterRegion); + $expectedResponse->setUid($uid); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setEtag($etag); + $expectedResponse->setKubernetesVersion($kubernetesVersion); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createAttachedClusterTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $attachedCluster = new AttachedCluster(); + $attachedClusterOidcConfig = new AttachedOidcConfig(); + $attachedCluster->setOidcConfig($attachedClusterOidcConfig); + $attachedClusterPlatformVersion = 'attachedClusterPlatformVersion-208126385'; + $attachedCluster->setPlatformVersion($attachedClusterPlatformVersion); + $attachedClusterDistribution = 'attachedClusterDistribution1692601690'; + $attachedCluster->setDistribution($attachedClusterDistribution); + $attachedClusterFleet = new Fleet(); + $fleetProject = 'fleetProject604893675'; + $attachedClusterFleet->setProject($fleetProject); + $attachedCluster->setFleet($attachedClusterFleet); + $attachedClusterId = 'attachedClusterId-249426181'; + $request = (new CreateAttachedClusterRequest()) + ->setParent($formattedParent) + ->setAttachedCluster($attachedCluster) + ->setAttachedClusterId($attachedClusterId); + $response = $gapicClient->createAttachedClusterAsync($request)->wait(); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AttachedClusters/CreateAttachedCluster', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getAttachedCluster(); + $this->assertProtobufEquals($attachedCluster, $actualValue); + $actualValue = $actualApiRequestObject->getAttachedClusterId(); + $this->assertProtobufEquals($attachedClusterId, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createAttachedClusterTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } +} diff --git a/GkeMultiCloud/tests/Unit/V1/Client/AwsClustersClientTest.php b/GkeMultiCloud/tests/Unit/V1/Client/AwsClustersClientTest.php new file mode 100644 index 000000000000..1a0aed506d8f --- /dev/null +++ b/GkeMultiCloud/tests/Unit/V1/Client/AwsClustersClientTest.php @@ -0,0 +1,1702 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return AwsClustersClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new AwsClustersClient($options); + } + + /** @test */ + public function createAwsClusterTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createAwsClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $description = 'description-1724546052'; + $awsRegion = 'awsRegion-1887255946'; + $endpoint = 'endpoint1741102485'; + $uid = 'uid115792'; + $reconciling = false; + $etag = 'etag3123477'; + $clusterCaCertificate = 'clusterCaCertificate1324742683'; + $expectedResponse = new AwsCluster(); + $expectedResponse->setName($name); + $expectedResponse->setDescription($description); + $expectedResponse->setAwsRegion($awsRegion); + $expectedResponse->setEndpoint($endpoint); + $expectedResponse->setUid($uid); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setEtag($etag); + $expectedResponse->setClusterCaCertificate($clusterCaCertificate); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createAwsClusterTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $awsCluster = new AwsCluster(); + $awsClusterNetworking = new AwsClusterNetworking(); + $networkingVpcId = 'networkingVpcId-1154507440'; + $awsClusterNetworking->setVpcId($networkingVpcId); + $networkingPodAddressCidrBlocks = []; + $awsClusterNetworking->setPodAddressCidrBlocks($networkingPodAddressCidrBlocks); + $networkingServiceAddressCidrBlocks = []; + $awsClusterNetworking->setServiceAddressCidrBlocks($networkingServiceAddressCidrBlocks); + $awsCluster->setNetworking($awsClusterNetworking); + $awsClusterAwsRegion = 'awsClusterAwsRegion574122132'; + $awsCluster->setAwsRegion($awsClusterAwsRegion); + $awsClusterControlPlane = new AwsControlPlane(); + $controlPlaneVersion = 'controlPlaneVersion648040665'; + $awsClusterControlPlane->setVersion($controlPlaneVersion); + $controlPlaneSubnetIds = []; + $awsClusterControlPlane->setSubnetIds($controlPlaneSubnetIds); + $controlPlaneIamInstanceProfile = 'controlPlaneIamInstanceProfile1905273246'; + $awsClusterControlPlane->setIamInstanceProfile($controlPlaneIamInstanceProfile); + $controlPlaneDatabaseEncryption = new AwsDatabaseEncryption(); + $databaseEncryptionKmsKeyArn = 'databaseEncryptionKmsKeyArn1858324593'; + $controlPlaneDatabaseEncryption->setKmsKeyArn($databaseEncryptionKmsKeyArn); + $awsClusterControlPlane->setDatabaseEncryption($controlPlaneDatabaseEncryption); + $controlPlaneAwsServicesAuthentication = new AwsServicesAuthentication(); + $awsServicesAuthenticationRoleArn = 'awsServicesAuthenticationRoleArn1905212596'; + $controlPlaneAwsServicesAuthentication->setRoleArn($awsServicesAuthenticationRoleArn); + $awsClusterControlPlane->setAwsServicesAuthentication($controlPlaneAwsServicesAuthentication); + $controlPlaneConfigEncryption = new AwsConfigEncryption(); + $configEncryptionKmsKeyArn = 'configEncryptionKmsKeyArn-992257206'; + $controlPlaneConfigEncryption->setKmsKeyArn($configEncryptionKmsKeyArn); + $awsClusterControlPlane->setConfigEncryption($controlPlaneConfigEncryption); + $awsCluster->setControlPlane($awsClusterControlPlane); + $awsClusterAuthorization = new AwsAuthorization(); + $authorizationAdminUsers = []; + $awsClusterAuthorization->setAdminUsers($authorizationAdminUsers); + $awsCluster->setAuthorization($awsClusterAuthorization); + $awsClusterFleet = new Fleet(); + $fleetProject = 'fleetProject604893675'; + $awsClusterFleet->setProject($fleetProject); + $awsCluster->setFleet($awsClusterFleet); + $awsClusterId = 'awsClusterId938438658'; + $request = (new CreateAwsClusterRequest()) + ->setParent($formattedParent) + ->setAwsCluster($awsCluster) + ->setAwsClusterId($awsClusterId); + $response = $gapicClient->createAwsCluster($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AwsClusters/CreateAwsCluster', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getAwsCluster(); + $this->assertProtobufEquals($awsCluster, $actualValue); + $actualValue = $actualApiRequestObject->getAwsClusterId(); + $this->assertProtobufEquals($awsClusterId, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createAwsClusterTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createAwsClusterExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createAwsClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $awsCluster = new AwsCluster(); + $awsClusterNetworking = new AwsClusterNetworking(); + $networkingVpcId = 'networkingVpcId-1154507440'; + $awsClusterNetworking->setVpcId($networkingVpcId); + $networkingPodAddressCidrBlocks = []; + $awsClusterNetworking->setPodAddressCidrBlocks($networkingPodAddressCidrBlocks); + $networkingServiceAddressCidrBlocks = []; + $awsClusterNetworking->setServiceAddressCidrBlocks($networkingServiceAddressCidrBlocks); + $awsCluster->setNetworking($awsClusterNetworking); + $awsClusterAwsRegion = 'awsClusterAwsRegion574122132'; + $awsCluster->setAwsRegion($awsClusterAwsRegion); + $awsClusterControlPlane = new AwsControlPlane(); + $controlPlaneVersion = 'controlPlaneVersion648040665'; + $awsClusterControlPlane->setVersion($controlPlaneVersion); + $controlPlaneSubnetIds = []; + $awsClusterControlPlane->setSubnetIds($controlPlaneSubnetIds); + $controlPlaneIamInstanceProfile = 'controlPlaneIamInstanceProfile1905273246'; + $awsClusterControlPlane->setIamInstanceProfile($controlPlaneIamInstanceProfile); + $controlPlaneDatabaseEncryption = new AwsDatabaseEncryption(); + $databaseEncryptionKmsKeyArn = 'databaseEncryptionKmsKeyArn1858324593'; + $controlPlaneDatabaseEncryption->setKmsKeyArn($databaseEncryptionKmsKeyArn); + $awsClusterControlPlane->setDatabaseEncryption($controlPlaneDatabaseEncryption); + $controlPlaneAwsServicesAuthentication = new AwsServicesAuthentication(); + $awsServicesAuthenticationRoleArn = 'awsServicesAuthenticationRoleArn1905212596'; + $controlPlaneAwsServicesAuthentication->setRoleArn($awsServicesAuthenticationRoleArn); + $awsClusterControlPlane->setAwsServicesAuthentication($controlPlaneAwsServicesAuthentication); + $controlPlaneConfigEncryption = new AwsConfigEncryption(); + $configEncryptionKmsKeyArn = 'configEncryptionKmsKeyArn-992257206'; + $controlPlaneConfigEncryption->setKmsKeyArn($configEncryptionKmsKeyArn); + $awsClusterControlPlane->setConfigEncryption($controlPlaneConfigEncryption); + $awsCluster->setControlPlane($awsClusterControlPlane); + $awsClusterAuthorization = new AwsAuthorization(); + $authorizationAdminUsers = []; + $awsClusterAuthorization->setAdminUsers($authorizationAdminUsers); + $awsCluster->setAuthorization($awsClusterAuthorization); + $awsClusterFleet = new Fleet(); + $fleetProject = 'fleetProject604893675'; + $awsClusterFleet->setProject($fleetProject); + $awsCluster->setFleet($awsClusterFleet); + $awsClusterId = 'awsClusterId938438658'; + $request = (new CreateAwsClusterRequest()) + ->setParent($formattedParent) + ->setAwsCluster($awsCluster) + ->setAwsClusterId($awsClusterId); + $response = $gapicClient->createAwsCluster($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createAwsClusterTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createAwsNodePoolTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createAwsNodePoolTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $version = 'version351608024'; + $subnetId = 'subnetId373593405'; + $uid = 'uid115792'; + $reconciling = false; + $etag = 'etag3123477'; + $expectedResponse = new AwsNodePool(); + $expectedResponse->setName($name); + $expectedResponse->setVersion($version); + $expectedResponse->setSubnetId($subnetId); + $expectedResponse->setUid($uid); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setEtag($etag); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createAwsNodePoolTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->awsClusterName('[PROJECT]', '[LOCATION]', '[AWS_CLUSTER]'); + $awsNodePool = new AwsNodePool(); + $awsNodePoolVersion = 'awsNodePoolVersion-617231107'; + $awsNodePool->setVersion($awsNodePoolVersion); + $awsNodePoolConfig = new AwsNodeConfig(); + $configIamInstanceProfile = 'configIamInstanceProfile805825313'; + $awsNodePoolConfig->setIamInstanceProfile($configIamInstanceProfile); + $configConfigEncryption = new AwsConfigEncryption(); + $configEncryptionKmsKeyArn = 'configEncryptionKmsKeyArn-992257206'; + $configConfigEncryption->setKmsKeyArn($configEncryptionKmsKeyArn); + $awsNodePoolConfig->setConfigEncryption($configConfigEncryption); + $awsNodePool->setConfig($awsNodePoolConfig); + $awsNodePoolAutoscaling = new AwsNodePoolAutoscaling(); + $autoscalingMinNodeCount = 1464441581; + $awsNodePoolAutoscaling->setMinNodeCount($autoscalingMinNodeCount); + $autoscalingMaxNodeCount = 1938867647; + $awsNodePoolAutoscaling->setMaxNodeCount($autoscalingMaxNodeCount); + $awsNodePool->setAutoscaling($awsNodePoolAutoscaling); + $awsNodePoolSubnetId = 'awsNodePoolSubnetId-2035401261'; + $awsNodePool->setSubnetId($awsNodePoolSubnetId); + $awsNodePoolMaxPodsConstraint = new MaxPodsConstraint(); + $maxPodsConstraintMaxPodsPerNode = 1072618940; + $awsNodePoolMaxPodsConstraint->setMaxPodsPerNode($maxPodsConstraintMaxPodsPerNode); + $awsNodePool->setMaxPodsConstraint($awsNodePoolMaxPodsConstraint); + $awsNodePoolId = 'awsNodePoolId1958033635'; + $request = (new CreateAwsNodePoolRequest()) + ->setParent($formattedParent) + ->setAwsNodePool($awsNodePool) + ->setAwsNodePoolId($awsNodePoolId); + $response = $gapicClient->createAwsNodePool($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AwsClusters/CreateAwsNodePool', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getAwsNodePool(); + $this->assertProtobufEquals($awsNodePool, $actualValue); + $actualValue = $actualApiRequestObject->getAwsNodePoolId(); + $this->assertProtobufEquals($awsNodePoolId, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createAwsNodePoolTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createAwsNodePoolExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createAwsNodePoolTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->awsClusterName('[PROJECT]', '[LOCATION]', '[AWS_CLUSTER]'); + $awsNodePool = new AwsNodePool(); + $awsNodePoolVersion = 'awsNodePoolVersion-617231107'; + $awsNodePool->setVersion($awsNodePoolVersion); + $awsNodePoolConfig = new AwsNodeConfig(); + $configIamInstanceProfile = 'configIamInstanceProfile805825313'; + $awsNodePoolConfig->setIamInstanceProfile($configIamInstanceProfile); + $configConfigEncryption = new AwsConfigEncryption(); + $configEncryptionKmsKeyArn = 'configEncryptionKmsKeyArn-992257206'; + $configConfigEncryption->setKmsKeyArn($configEncryptionKmsKeyArn); + $awsNodePoolConfig->setConfigEncryption($configConfigEncryption); + $awsNodePool->setConfig($awsNodePoolConfig); + $awsNodePoolAutoscaling = new AwsNodePoolAutoscaling(); + $autoscalingMinNodeCount = 1464441581; + $awsNodePoolAutoscaling->setMinNodeCount($autoscalingMinNodeCount); + $autoscalingMaxNodeCount = 1938867647; + $awsNodePoolAutoscaling->setMaxNodeCount($autoscalingMaxNodeCount); + $awsNodePool->setAutoscaling($awsNodePoolAutoscaling); + $awsNodePoolSubnetId = 'awsNodePoolSubnetId-2035401261'; + $awsNodePool->setSubnetId($awsNodePoolSubnetId); + $awsNodePoolMaxPodsConstraint = new MaxPodsConstraint(); + $maxPodsConstraintMaxPodsPerNode = 1072618940; + $awsNodePoolMaxPodsConstraint->setMaxPodsPerNode($maxPodsConstraintMaxPodsPerNode); + $awsNodePool->setMaxPodsConstraint($awsNodePoolMaxPodsConstraint); + $awsNodePoolId = 'awsNodePoolId1958033635'; + $request = (new CreateAwsNodePoolRequest()) + ->setParent($formattedParent) + ->setAwsNodePool($awsNodePool) + ->setAwsNodePoolId($awsNodePoolId); + $response = $gapicClient->createAwsNodePool($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createAwsNodePoolTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteAwsClusterTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteAwsClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new GPBEmpty(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/deleteAwsClusterTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedName = $gapicClient->awsClusterName('[PROJECT]', '[LOCATION]', '[AWS_CLUSTER]'); + $request = (new DeleteAwsClusterRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteAwsCluster($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AwsClusters/DeleteAwsCluster', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteAwsClusterTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteAwsClusterExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteAwsClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->awsClusterName('[PROJECT]', '[LOCATION]', '[AWS_CLUSTER]'); + $request = (new DeleteAwsClusterRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteAwsCluster($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteAwsClusterTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteAwsNodePoolTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteAwsNodePoolTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new GPBEmpty(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/deleteAwsNodePoolTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedName = $gapicClient->awsNodePoolName('[PROJECT]', '[LOCATION]', '[AWS_CLUSTER]', '[AWS_NODE_POOL]'); + $request = (new DeleteAwsNodePoolRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteAwsNodePool($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AwsClusters/DeleteAwsNodePool', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteAwsNodePoolTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteAwsNodePoolExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteAwsNodePoolTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->awsNodePoolName('[PROJECT]', '[LOCATION]', '[AWS_CLUSTER]', '[AWS_NODE_POOL]'); + $request = (new DeleteAwsNodePoolRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteAwsNodePool($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteAwsNodePoolTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function generateAwsAccessTokenTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $accessToken = 'accessToken-1938933922'; + $expectedResponse = new GenerateAwsAccessTokenResponse(); + $expectedResponse->setAccessToken($accessToken); + $transport->addResponse($expectedResponse); + // Mock request + $formattedAwsCluster = $gapicClient->awsClusterName('[PROJECT]', '[LOCATION]', '[AWS_CLUSTER]'); + $request = (new GenerateAwsAccessTokenRequest()) + ->setAwsCluster($formattedAwsCluster); + $response = $gapicClient->generateAwsAccessToken($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AwsClusters/GenerateAwsAccessToken', $actualFuncCall); + $actualValue = $actualRequestObject->getAwsCluster(); + $this->assertProtobufEquals($formattedAwsCluster, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function generateAwsAccessTokenExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedAwsCluster = $gapicClient->awsClusterName('[PROJECT]', '[LOCATION]', '[AWS_CLUSTER]'); + $request = (new GenerateAwsAccessTokenRequest()) + ->setAwsCluster($formattedAwsCluster); + try { + $gapicClient->generateAwsAccessToken($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getAwsClusterTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $description = 'description-1724546052'; + $awsRegion = 'awsRegion-1887255946'; + $endpoint = 'endpoint1741102485'; + $uid = 'uid115792'; + $reconciling = false; + $etag = 'etag3123477'; + $clusterCaCertificate = 'clusterCaCertificate1324742683'; + $expectedResponse = new AwsCluster(); + $expectedResponse->setName($name2); + $expectedResponse->setDescription($description); + $expectedResponse->setAwsRegion($awsRegion); + $expectedResponse->setEndpoint($endpoint); + $expectedResponse->setUid($uid); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setEtag($etag); + $expectedResponse->setClusterCaCertificate($clusterCaCertificate); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->awsClusterName('[PROJECT]', '[LOCATION]', '[AWS_CLUSTER]'); + $request = (new GetAwsClusterRequest()) + ->setName($formattedName); + $response = $gapicClient->getAwsCluster($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsCluster', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getAwsClusterExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->awsClusterName('[PROJECT]', '[LOCATION]', '[AWS_CLUSTER]'); + $request = (new GetAwsClusterRequest()) + ->setName($formattedName); + try { + $gapicClient->getAwsCluster($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getAwsNodePoolTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $version = 'version351608024'; + $subnetId = 'subnetId373593405'; + $uid = 'uid115792'; + $reconciling = false; + $etag = 'etag3123477'; + $expectedResponse = new AwsNodePool(); + $expectedResponse->setName($name2); + $expectedResponse->setVersion($version); + $expectedResponse->setSubnetId($subnetId); + $expectedResponse->setUid($uid); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setEtag($etag); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->awsNodePoolName('[PROJECT]', '[LOCATION]', '[AWS_CLUSTER]', '[AWS_NODE_POOL]'); + $request = (new GetAwsNodePoolRequest()) + ->setName($formattedName); + $response = $gapicClient->getAwsNodePool($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsNodePool', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getAwsNodePoolExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->awsNodePoolName('[PROJECT]', '[LOCATION]', '[AWS_CLUSTER]', '[AWS_NODE_POOL]'); + $request = (new GetAwsNodePoolRequest()) + ->setName($formattedName); + try { + $gapicClient->getAwsNodePool($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getAwsServerConfigTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $expectedResponse = new AwsServerConfig(); + $expectedResponse->setName($name2); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->awsServerConfigName('[PROJECT]', '[LOCATION]'); + $request = (new GetAwsServerConfigRequest()) + ->setName($formattedName); + $response = $gapicClient->getAwsServerConfig($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AwsClusters/GetAwsServerConfig', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getAwsServerConfigExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->awsServerConfigName('[PROJECT]', '[LOCATION]'); + $request = (new GetAwsServerConfigRequest()) + ->setName($formattedName); + try { + $gapicClient->getAwsServerConfig($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listAwsClustersTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $awsClustersElement = new AwsCluster(); + $awsClusters = [ + $awsClustersElement, + ]; + $expectedResponse = new ListAwsClustersResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setAwsClusters($awsClusters); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListAwsClustersRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listAwsClusters($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getAwsClusters()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AwsClusters/ListAwsClusters', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listAwsClustersExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListAwsClustersRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listAwsClusters($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listAwsNodePoolsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $awsNodePoolsElement = new AwsNodePool(); + $awsNodePools = [ + $awsNodePoolsElement, + ]; + $expectedResponse = new ListAwsNodePoolsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setAwsNodePools($awsNodePools); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->awsClusterName('[PROJECT]', '[LOCATION]', '[AWS_CLUSTER]'); + $request = (new ListAwsNodePoolsRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listAwsNodePools($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getAwsNodePools()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AwsClusters/ListAwsNodePools', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listAwsNodePoolsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->awsClusterName('[PROJECT]', '[LOCATION]', '[AWS_CLUSTER]'); + $request = (new ListAwsNodePoolsRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listAwsNodePools($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function updateAwsClusterTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateAwsClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $description = 'description-1724546052'; + $awsRegion = 'awsRegion-1887255946'; + $endpoint = 'endpoint1741102485'; + $uid = 'uid115792'; + $reconciling = false; + $etag = 'etag3123477'; + $clusterCaCertificate = 'clusterCaCertificate1324742683'; + $expectedResponse = new AwsCluster(); + $expectedResponse->setName($name); + $expectedResponse->setDescription($description); + $expectedResponse->setAwsRegion($awsRegion); + $expectedResponse->setEndpoint($endpoint); + $expectedResponse->setUid($uid); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setEtag($etag); + $expectedResponse->setClusterCaCertificate($clusterCaCertificate); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/updateAwsClusterTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $awsCluster = new AwsCluster(); + $awsClusterNetworking = new AwsClusterNetworking(); + $networkingVpcId = 'networkingVpcId-1154507440'; + $awsClusterNetworking->setVpcId($networkingVpcId); + $networkingPodAddressCidrBlocks = []; + $awsClusterNetworking->setPodAddressCidrBlocks($networkingPodAddressCidrBlocks); + $networkingServiceAddressCidrBlocks = []; + $awsClusterNetworking->setServiceAddressCidrBlocks($networkingServiceAddressCidrBlocks); + $awsCluster->setNetworking($awsClusterNetworking); + $awsClusterAwsRegion = 'awsClusterAwsRegion574122132'; + $awsCluster->setAwsRegion($awsClusterAwsRegion); + $awsClusterControlPlane = new AwsControlPlane(); + $controlPlaneVersion = 'controlPlaneVersion648040665'; + $awsClusterControlPlane->setVersion($controlPlaneVersion); + $controlPlaneSubnetIds = []; + $awsClusterControlPlane->setSubnetIds($controlPlaneSubnetIds); + $controlPlaneIamInstanceProfile = 'controlPlaneIamInstanceProfile1905273246'; + $awsClusterControlPlane->setIamInstanceProfile($controlPlaneIamInstanceProfile); + $controlPlaneDatabaseEncryption = new AwsDatabaseEncryption(); + $databaseEncryptionKmsKeyArn = 'databaseEncryptionKmsKeyArn1858324593'; + $controlPlaneDatabaseEncryption->setKmsKeyArn($databaseEncryptionKmsKeyArn); + $awsClusterControlPlane->setDatabaseEncryption($controlPlaneDatabaseEncryption); + $controlPlaneAwsServicesAuthentication = new AwsServicesAuthentication(); + $awsServicesAuthenticationRoleArn = 'awsServicesAuthenticationRoleArn1905212596'; + $controlPlaneAwsServicesAuthentication->setRoleArn($awsServicesAuthenticationRoleArn); + $awsClusterControlPlane->setAwsServicesAuthentication($controlPlaneAwsServicesAuthentication); + $controlPlaneConfigEncryption = new AwsConfigEncryption(); + $configEncryptionKmsKeyArn = 'configEncryptionKmsKeyArn-992257206'; + $controlPlaneConfigEncryption->setKmsKeyArn($configEncryptionKmsKeyArn); + $awsClusterControlPlane->setConfigEncryption($controlPlaneConfigEncryption); + $awsCluster->setControlPlane($awsClusterControlPlane); + $awsClusterAuthorization = new AwsAuthorization(); + $authorizationAdminUsers = []; + $awsClusterAuthorization->setAdminUsers($authorizationAdminUsers); + $awsCluster->setAuthorization($awsClusterAuthorization); + $awsClusterFleet = new Fleet(); + $fleetProject = 'fleetProject604893675'; + $awsClusterFleet->setProject($fleetProject); + $awsCluster->setFleet($awsClusterFleet); + $updateMask = new FieldMask(); + $request = (new UpdateAwsClusterRequest()) + ->setAwsCluster($awsCluster) + ->setUpdateMask($updateMask); + $response = $gapicClient->updateAwsCluster($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AwsClusters/UpdateAwsCluster', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getAwsCluster(); + $this->assertProtobufEquals($awsCluster, $actualValue); + $actualValue = $actualApiRequestObject->getUpdateMask(); + $this->assertProtobufEquals($updateMask, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateAwsClusterTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateAwsClusterExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateAwsClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $awsCluster = new AwsCluster(); + $awsClusterNetworking = new AwsClusterNetworking(); + $networkingVpcId = 'networkingVpcId-1154507440'; + $awsClusterNetworking->setVpcId($networkingVpcId); + $networkingPodAddressCidrBlocks = []; + $awsClusterNetworking->setPodAddressCidrBlocks($networkingPodAddressCidrBlocks); + $networkingServiceAddressCidrBlocks = []; + $awsClusterNetworking->setServiceAddressCidrBlocks($networkingServiceAddressCidrBlocks); + $awsCluster->setNetworking($awsClusterNetworking); + $awsClusterAwsRegion = 'awsClusterAwsRegion574122132'; + $awsCluster->setAwsRegion($awsClusterAwsRegion); + $awsClusterControlPlane = new AwsControlPlane(); + $controlPlaneVersion = 'controlPlaneVersion648040665'; + $awsClusterControlPlane->setVersion($controlPlaneVersion); + $controlPlaneSubnetIds = []; + $awsClusterControlPlane->setSubnetIds($controlPlaneSubnetIds); + $controlPlaneIamInstanceProfile = 'controlPlaneIamInstanceProfile1905273246'; + $awsClusterControlPlane->setIamInstanceProfile($controlPlaneIamInstanceProfile); + $controlPlaneDatabaseEncryption = new AwsDatabaseEncryption(); + $databaseEncryptionKmsKeyArn = 'databaseEncryptionKmsKeyArn1858324593'; + $controlPlaneDatabaseEncryption->setKmsKeyArn($databaseEncryptionKmsKeyArn); + $awsClusterControlPlane->setDatabaseEncryption($controlPlaneDatabaseEncryption); + $controlPlaneAwsServicesAuthentication = new AwsServicesAuthentication(); + $awsServicesAuthenticationRoleArn = 'awsServicesAuthenticationRoleArn1905212596'; + $controlPlaneAwsServicesAuthentication->setRoleArn($awsServicesAuthenticationRoleArn); + $awsClusterControlPlane->setAwsServicesAuthentication($controlPlaneAwsServicesAuthentication); + $controlPlaneConfigEncryption = new AwsConfigEncryption(); + $configEncryptionKmsKeyArn = 'configEncryptionKmsKeyArn-992257206'; + $controlPlaneConfigEncryption->setKmsKeyArn($configEncryptionKmsKeyArn); + $awsClusterControlPlane->setConfigEncryption($controlPlaneConfigEncryption); + $awsCluster->setControlPlane($awsClusterControlPlane); + $awsClusterAuthorization = new AwsAuthorization(); + $authorizationAdminUsers = []; + $awsClusterAuthorization->setAdminUsers($authorizationAdminUsers); + $awsCluster->setAuthorization($awsClusterAuthorization); + $awsClusterFleet = new Fleet(); + $fleetProject = 'fleetProject604893675'; + $awsClusterFleet->setProject($fleetProject); + $awsCluster->setFleet($awsClusterFleet); + $updateMask = new FieldMask(); + $request = (new UpdateAwsClusterRequest()) + ->setAwsCluster($awsCluster) + ->setUpdateMask($updateMask); + $response = $gapicClient->updateAwsCluster($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateAwsClusterTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateAwsNodePoolTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateAwsNodePoolTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $version = 'version351608024'; + $subnetId = 'subnetId373593405'; + $uid = 'uid115792'; + $reconciling = false; + $etag = 'etag3123477'; + $expectedResponse = new AwsNodePool(); + $expectedResponse->setName($name); + $expectedResponse->setVersion($version); + $expectedResponse->setSubnetId($subnetId); + $expectedResponse->setUid($uid); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setEtag($etag); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/updateAwsNodePoolTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $awsNodePool = new AwsNodePool(); + $awsNodePoolVersion = 'awsNodePoolVersion-617231107'; + $awsNodePool->setVersion($awsNodePoolVersion); + $awsNodePoolConfig = new AwsNodeConfig(); + $configIamInstanceProfile = 'configIamInstanceProfile805825313'; + $awsNodePoolConfig->setIamInstanceProfile($configIamInstanceProfile); + $configConfigEncryption = new AwsConfigEncryption(); + $configEncryptionKmsKeyArn = 'configEncryptionKmsKeyArn-992257206'; + $configConfigEncryption->setKmsKeyArn($configEncryptionKmsKeyArn); + $awsNodePoolConfig->setConfigEncryption($configConfigEncryption); + $awsNodePool->setConfig($awsNodePoolConfig); + $awsNodePoolAutoscaling = new AwsNodePoolAutoscaling(); + $autoscalingMinNodeCount = 1464441581; + $awsNodePoolAutoscaling->setMinNodeCount($autoscalingMinNodeCount); + $autoscalingMaxNodeCount = 1938867647; + $awsNodePoolAutoscaling->setMaxNodeCount($autoscalingMaxNodeCount); + $awsNodePool->setAutoscaling($awsNodePoolAutoscaling); + $awsNodePoolSubnetId = 'awsNodePoolSubnetId-2035401261'; + $awsNodePool->setSubnetId($awsNodePoolSubnetId); + $awsNodePoolMaxPodsConstraint = new MaxPodsConstraint(); + $maxPodsConstraintMaxPodsPerNode = 1072618940; + $awsNodePoolMaxPodsConstraint->setMaxPodsPerNode($maxPodsConstraintMaxPodsPerNode); + $awsNodePool->setMaxPodsConstraint($awsNodePoolMaxPodsConstraint); + $updateMask = new FieldMask(); + $request = (new UpdateAwsNodePoolRequest()) + ->setAwsNodePool($awsNodePool) + ->setUpdateMask($updateMask); + $response = $gapicClient->updateAwsNodePool($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AwsClusters/UpdateAwsNodePool', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getAwsNodePool(); + $this->assertProtobufEquals($awsNodePool, $actualValue); + $actualValue = $actualApiRequestObject->getUpdateMask(); + $this->assertProtobufEquals($updateMask, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateAwsNodePoolTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateAwsNodePoolExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateAwsNodePoolTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $awsNodePool = new AwsNodePool(); + $awsNodePoolVersion = 'awsNodePoolVersion-617231107'; + $awsNodePool->setVersion($awsNodePoolVersion); + $awsNodePoolConfig = new AwsNodeConfig(); + $configIamInstanceProfile = 'configIamInstanceProfile805825313'; + $awsNodePoolConfig->setIamInstanceProfile($configIamInstanceProfile); + $configConfigEncryption = new AwsConfigEncryption(); + $configEncryptionKmsKeyArn = 'configEncryptionKmsKeyArn-992257206'; + $configConfigEncryption->setKmsKeyArn($configEncryptionKmsKeyArn); + $awsNodePoolConfig->setConfigEncryption($configConfigEncryption); + $awsNodePool->setConfig($awsNodePoolConfig); + $awsNodePoolAutoscaling = new AwsNodePoolAutoscaling(); + $autoscalingMinNodeCount = 1464441581; + $awsNodePoolAutoscaling->setMinNodeCount($autoscalingMinNodeCount); + $autoscalingMaxNodeCount = 1938867647; + $awsNodePoolAutoscaling->setMaxNodeCount($autoscalingMaxNodeCount); + $awsNodePool->setAutoscaling($awsNodePoolAutoscaling); + $awsNodePoolSubnetId = 'awsNodePoolSubnetId-2035401261'; + $awsNodePool->setSubnetId($awsNodePoolSubnetId); + $awsNodePoolMaxPodsConstraint = new MaxPodsConstraint(); + $maxPodsConstraintMaxPodsPerNode = 1072618940; + $awsNodePoolMaxPodsConstraint->setMaxPodsPerNode($maxPodsConstraintMaxPodsPerNode); + $awsNodePool->setMaxPodsConstraint($awsNodePoolMaxPodsConstraint); + $updateMask = new FieldMask(); + $request = (new UpdateAwsNodePoolRequest()) + ->setAwsNodePool($awsNodePool) + ->setUpdateMask($updateMask); + $response = $gapicClient->updateAwsNodePool($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateAwsNodePoolTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createAwsClusterAsyncTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createAwsClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $description = 'description-1724546052'; + $awsRegion = 'awsRegion-1887255946'; + $endpoint = 'endpoint1741102485'; + $uid = 'uid115792'; + $reconciling = false; + $etag = 'etag3123477'; + $clusterCaCertificate = 'clusterCaCertificate1324742683'; + $expectedResponse = new AwsCluster(); + $expectedResponse->setName($name); + $expectedResponse->setDescription($description); + $expectedResponse->setAwsRegion($awsRegion); + $expectedResponse->setEndpoint($endpoint); + $expectedResponse->setUid($uid); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setEtag($etag); + $expectedResponse->setClusterCaCertificate($clusterCaCertificate); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createAwsClusterTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $awsCluster = new AwsCluster(); + $awsClusterNetworking = new AwsClusterNetworking(); + $networkingVpcId = 'networkingVpcId-1154507440'; + $awsClusterNetworking->setVpcId($networkingVpcId); + $networkingPodAddressCidrBlocks = []; + $awsClusterNetworking->setPodAddressCidrBlocks($networkingPodAddressCidrBlocks); + $networkingServiceAddressCidrBlocks = []; + $awsClusterNetworking->setServiceAddressCidrBlocks($networkingServiceAddressCidrBlocks); + $awsCluster->setNetworking($awsClusterNetworking); + $awsClusterAwsRegion = 'awsClusterAwsRegion574122132'; + $awsCluster->setAwsRegion($awsClusterAwsRegion); + $awsClusterControlPlane = new AwsControlPlane(); + $controlPlaneVersion = 'controlPlaneVersion648040665'; + $awsClusterControlPlane->setVersion($controlPlaneVersion); + $controlPlaneSubnetIds = []; + $awsClusterControlPlane->setSubnetIds($controlPlaneSubnetIds); + $controlPlaneIamInstanceProfile = 'controlPlaneIamInstanceProfile1905273246'; + $awsClusterControlPlane->setIamInstanceProfile($controlPlaneIamInstanceProfile); + $controlPlaneDatabaseEncryption = new AwsDatabaseEncryption(); + $databaseEncryptionKmsKeyArn = 'databaseEncryptionKmsKeyArn1858324593'; + $controlPlaneDatabaseEncryption->setKmsKeyArn($databaseEncryptionKmsKeyArn); + $awsClusterControlPlane->setDatabaseEncryption($controlPlaneDatabaseEncryption); + $controlPlaneAwsServicesAuthentication = new AwsServicesAuthentication(); + $awsServicesAuthenticationRoleArn = 'awsServicesAuthenticationRoleArn1905212596'; + $controlPlaneAwsServicesAuthentication->setRoleArn($awsServicesAuthenticationRoleArn); + $awsClusterControlPlane->setAwsServicesAuthentication($controlPlaneAwsServicesAuthentication); + $controlPlaneConfigEncryption = new AwsConfigEncryption(); + $configEncryptionKmsKeyArn = 'configEncryptionKmsKeyArn-992257206'; + $controlPlaneConfigEncryption->setKmsKeyArn($configEncryptionKmsKeyArn); + $awsClusterControlPlane->setConfigEncryption($controlPlaneConfigEncryption); + $awsCluster->setControlPlane($awsClusterControlPlane); + $awsClusterAuthorization = new AwsAuthorization(); + $authorizationAdminUsers = []; + $awsClusterAuthorization->setAdminUsers($authorizationAdminUsers); + $awsCluster->setAuthorization($awsClusterAuthorization); + $awsClusterFleet = new Fleet(); + $fleetProject = 'fleetProject604893675'; + $awsClusterFleet->setProject($fleetProject); + $awsCluster->setFleet($awsClusterFleet); + $awsClusterId = 'awsClusterId938438658'; + $request = (new CreateAwsClusterRequest()) + ->setParent($formattedParent) + ->setAwsCluster($awsCluster) + ->setAwsClusterId($awsClusterId); + $response = $gapicClient->createAwsClusterAsync($request)->wait(); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AwsClusters/CreateAwsCluster', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getAwsCluster(); + $this->assertProtobufEquals($awsCluster, $actualValue); + $actualValue = $actualApiRequestObject->getAwsClusterId(); + $this->assertProtobufEquals($awsClusterId, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createAwsClusterTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } +} diff --git a/GkeMultiCloud/tests/Unit/V1/Client/AzureClustersClientTest.php b/GkeMultiCloud/tests/Unit/V1/Client/AzureClustersClientTest.php new file mode 100644 index 000000000000..f87b121c8274 --- /dev/null +++ b/GkeMultiCloud/tests/Unit/V1/Client/AzureClustersClientTest.php @@ -0,0 +1,2058 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return AzureClustersClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new AzureClustersClient($options); + } + + /** @test */ + public function createAzureClientTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createAzureClientTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $tenantId = 'tenantId-1852780336'; + $applicationId = 'applicationId-1287148950'; + $reconciling = false; + $pemCertificate = 'pemCertificate1234463984'; + $uid = 'uid115792'; + $expectedResponse = new AzureClient(); + $expectedResponse->setName($name); + $expectedResponse->setTenantId($tenantId); + $expectedResponse->setApplicationId($applicationId); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setPemCertificate($pemCertificate); + $expectedResponse->setUid($uid); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createAzureClientTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $azureClient = new AzureClient(); + $azureClientTenantId = 'azureClientTenantId-567307073'; + $azureClient->setTenantId($azureClientTenantId); + $azureClientApplicationId = 'azureClientApplicationId264838513'; + $azureClient->setApplicationId($azureClientApplicationId); + $azureClientId = 'azureClientId315645023'; + $request = (new CreateAzureClientRequest()) + ->setParent($formattedParent) + ->setAzureClient($azureClient) + ->setAzureClientId($azureClientId); + $response = $gapicClient->createAzureClient($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AzureClusters/CreateAzureClient', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getAzureClient(); + $this->assertProtobufEquals($azureClient, $actualValue); + $actualValue = $actualApiRequestObject->getAzureClientId(); + $this->assertProtobufEquals($azureClientId, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createAzureClientTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createAzureClientExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createAzureClientTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $azureClient = new AzureClient(); + $azureClientTenantId = 'azureClientTenantId-567307073'; + $azureClient->setTenantId($azureClientTenantId); + $azureClientApplicationId = 'azureClientApplicationId264838513'; + $azureClient->setApplicationId($azureClientApplicationId); + $azureClientId = 'azureClientId315645023'; + $request = (new CreateAzureClientRequest()) + ->setParent($formattedParent) + ->setAzureClient($azureClient) + ->setAzureClientId($azureClientId); + $response = $gapicClient->createAzureClient($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createAzureClientTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createAzureClusterTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createAzureClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $description = 'description-1724546052'; + $azureRegion = 'azureRegion-253373788'; + $resourceGroupId = 'resourceGroupId-1092054036'; + $azureClient = 'azureClient-676290693'; + $endpoint = 'endpoint1741102485'; + $uid = 'uid115792'; + $reconciling = false; + $etag = 'etag3123477'; + $clusterCaCertificate = 'clusterCaCertificate1324742683'; + $expectedResponse = new AzureCluster(); + $expectedResponse->setName($name); + $expectedResponse->setDescription($description); + $expectedResponse->setAzureRegion($azureRegion); + $expectedResponse->setResourceGroupId($resourceGroupId); + $expectedResponse->setAzureClient($azureClient); + $expectedResponse->setEndpoint($endpoint); + $expectedResponse->setUid($uid); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setEtag($etag); + $expectedResponse->setClusterCaCertificate($clusterCaCertificate); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createAzureClusterTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $azureCluster = new AzureCluster(); + $azureClusterAzureRegion = 'azureClusterAzureRegion-1036501768'; + $azureCluster->setAzureRegion($azureClusterAzureRegion); + $azureClusterResourceGroupId = 'azureClusterResourceGroupId-1683734495'; + $azureCluster->setResourceGroupId($azureClusterResourceGroupId); + $azureClusterNetworking = new AzureClusterNetworking(); + $networkingVirtualNetworkId = 'networkingVirtualNetworkId-516550606'; + $azureClusterNetworking->setVirtualNetworkId($networkingVirtualNetworkId); + $networkingPodAddressCidrBlocks = []; + $azureClusterNetworking->setPodAddressCidrBlocks($networkingPodAddressCidrBlocks); + $networkingServiceAddressCidrBlocks = []; + $azureClusterNetworking->setServiceAddressCidrBlocks($networkingServiceAddressCidrBlocks); + $azureCluster->setNetworking($azureClusterNetworking); + $azureClusterControlPlane = new AzureControlPlane(); + $controlPlaneVersion = 'controlPlaneVersion648040665'; + $azureClusterControlPlane->setVersion($controlPlaneVersion); + $controlPlaneSshConfig = new AzureSshConfig(); + $sshConfigAuthorizedKey = 'sshConfigAuthorizedKey1626409850'; + $controlPlaneSshConfig->setAuthorizedKey($sshConfigAuthorizedKey); + $azureClusterControlPlane->setSshConfig($controlPlaneSshConfig); + $azureCluster->setControlPlane($azureClusterControlPlane); + $azureClusterAuthorization = new AzureAuthorization(); + $authorizationAdminUsers = []; + $azureClusterAuthorization->setAdminUsers($authorizationAdminUsers); + $azureCluster->setAuthorization($azureClusterAuthorization); + $azureClusterFleet = new Fleet(); + $fleetProject = 'fleetProject604893675'; + $azureClusterFleet->setProject($fleetProject); + $azureCluster->setFleet($azureClusterFleet); + $azureClusterId = 'azureClusterId332577072'; + $request = (new CreateAzureClusterRequest()) + ->setParent($formattedParent) + ->setAzureCluster($azureCluster) + ->setAzureClusterId($azureClusterId); + $response = $gapicClient->createAzureCluster($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AzureClusters/CreateAzureCluster', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getAzureCluster(); + $this->assertProtobufEquals($azureCluster, $actualValue); + $actualValue = $actualApiRequestObject->getAzureClusterId(); + $this->assertProtobufEquals($azureClusterId, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createAzureClusterTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createAzureClusterExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createAzureClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $azureCluster = new AzureCluster(); + $azureClusterAzureRegion = 'azureClusterAzureRegion-1036501768'; + $azureCluster->setAzureRegion($azureClusterAzureRegion); + $azureClusterResourceGroupId = 'azureClusterResourceGroupId-1683734495'; + $azureCluster->setResourceGroupId($azureClusterResourceGroupId); + $azureClusterNetworking = new AzureClusterNetworking(); + $networkingVirtualNetworkId = 'networkingVirtualNetworkId-516550606'; + $azureClusterNetworking->setVirtualNetworkId($networkingVirtualNetworkId); + $networkingPodAddressCidrBlocks = []; + $azureClusterNetworking->setPodAddressCidrBlocks($networkingPodAddressCidrBlocks); + $networkingServiceAddressCidrBlocks = []; + $azureClusterNetworking->setServiceAddressCidrBlocks($networkingServiceAddressCidrBlocks); + $azureCluster->setNetworking($azureClusterNetworking); + $azureClusterControlPlane = new AzureControlPlane(); + $controlPlaneVersion = 'controlPlaneVersion648040665'; + $azureClusterControlPlane->setVersion($controlPlaneVersion); + $controlPlaneSshConfig = new AzureSshConfig(); + $sshConfigAuthorizedKey = 'sshConfigAuthorizedKey1626409850'; + $controlPlaneSshConfig->setAuthorizedKey($sshConfigAuthorizedKey); + $azureClusterControlPlane->setSshConfig($controlPlaneSshConfig); + $azureCluster->setControlPlane($azureClusterControlPlane); + $azureClusterAuthorization = new AzureAuthorization(); + $authorizationAdminUsers = []; + $azureClusterAuthorization->setAdminUsers($authorizationAdminUsers); + $azureCluster->setAuthorization($azureClusterAuthorization); + $azureClusterFleet = new Fleet(); + $fleetProject = 'fleetProject604893675'; + $azureClusterFleet->setProject($fleetProject); + $azureCluster->setFleet($azureClusterFleet); + $azureClusterId = 'azureClusterId332577072'; + $request = (new CreateAzureClusterRequest()) + ->setParent($formattedParent) + ->setAzureCluster($azureCluster) + ->setAzureClusterId($azureClusterId); + $response = $gapicClient->createAzureCluster($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createAzureClusterTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createAzureNodePoolTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createAzureNodePoolTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $version = 'version351608024'; + $subnetId = 'subnetId373593405'; + $uid = 'uid115792'; + $reconciling = false; + $etag = 'etag3123477'; + $azureAvailabilityZone = 'azureAvailabilityZone541920864'; + $expectedResponse = new AzureNodePool(); + $expectedResponse->setName($name); + $expectedResponse->setVersion($version); + $expectedResponse->setSubnetId($subnetId); + $expectedResponse->setUid($uid); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setEtag($etag); + $expectedResponse->setAzureAvailabilityZone($azureAvailabilityZone); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createAzureNodePoolTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->azureClusterName('[PROJECT]', '[LOCATION]', '[AZURE_CLUSTER]'); + $azureNodePool = new AzureNodePool(); + $azureNodePoolVersion = 'azureNodePoolVersion349490987'; + $azureNodePool->setVersion($azureNodePoolVersion); + $azureNodePoolConfig = new AzureNodeConfig(); + $configSshConfig = new AzureSshConfig(); + $sshConfigAuthorizedKey = 'sshConfigAuthorizedKey1626409850'; + $configSshConfig->setAuthorizedKey($sshConfigAuthorizedKey); + $azureNodePoolConfig->setSshConfig($configSshConfig); + $azureNodePool->setConfig($azureNodePoolConfig); + $azureNodePoolSubnetId = 'azureNodePoolSubnetId-2131787419'; + $azureNodePool->setSubnetId($azureNodePoolSubnetId); + $azureNodePoolAutoscaling = new AzureNodePoolAutoscaling(); + $autoscalingMinNodeCount = 1464441581; + $azureNodePoolAutoscaling->setMinNodeCount($autoscalingMinNodeCount); + $autoscalingMaxNodeCount = 1938867647; + $azureNodePoolAutoscaling->setMaxNodeCount($autoscalingMaxNodeCount); + $azureNodePool->setAutoscaling($azureNodePoolAutoscaling); + $azureNodePoolMaxPodsConstraint = new MaxPodsConstraint(); + $maxPodsConstraintMaxPodsPerNode = 1072618940; + $azureNodePoolMaxPodsConstraint->setMaxPodsPerNode($maxPodsConstraintMaxPodsPerNode); + $azureNodePool->setMaxPodsConstraint($azureNodePoolMaxPodsConstraint); + $azureNodePoolId = 'azureNodePoolId-454365551'; + $request = (new CreateAzureNodePoolRequest()) + ->setParent($formattedParent) + ->setAzureNodePool($azureNodePool) + ->setAzureNodePoolId($azureNodePoolId); + $response = $gapicClient->createAzureNodePool($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AzureClusters/CreateAzureNodePool', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getAzureNodePool(); + $this->assertProtobufEquals($azureNodePool, $actualValue); + $actualValue = $actualApiRequestObject->getAzureNodePoolId(); + $this->assertProtobufEquals($azureNodePoolId, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createAzureNodePoolTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createAzureNodePoolExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createAzureNodePoolTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->azureClusterName('[PROJECT]', '[LOCATION]', '[AZURE_CLUSTER]'); + $azureNodePool = new AzureNodePool(); + $azureNodePoolVersion = 'azureNodePoolVersion349490987'; + $azureNodePool->setVersion($azureNodePoolVersion); + $azureNodePoolConfig = new AzureNodeConfig(); + $configSshConfig = new AzureSshConfig(); + $sshConfigAuthorizedKey = 'sshConfigAuthorizedKey1626409850'; + $configSshConfig->setAuthorizedKey($sshConfigAuthorizedKey); + $azureNodePoolConfig->setSshConfig($configSshConfig); + $azureNodePool->setConfig($azureNodePoolConfig); + $azureNodePoolSubnetId = 'azureNodePoolSubnetId-2131787419'; + $azureNodePool->setSubnetId($azureNodePoolSubnetId); + $azureNodePoolAutoscaling = new AzureNodePoolAutoscaling(); + $autoscalingMinNodeCount = 1464441581; + $azureNodePoolAutoscaling->setMinNodeCount($autoscalingMinNodeCount); + $autoscalingMaxNodeCount = 1938867647; + $azureNodePoolAutoscaling->setMaxNodeCount($autoscalingMaxNodeCount); + $azureNodePool->setAutoscaling($azureNodePoolAutoscaling); + $azureNodePoolMaxPodsConstraint = new MaxPodsConstraint(); + $maxPodsConstraintMaxPodsPerNode = 1072618940; + $azureNodePoolMaxPodsConstraint->setMaxPodsPerNode($maxPodsConstraintMaxPodsPerNode); + $azureNodePool->setMaxPodsConstraint($azureNodePoolMaxPodsConstraint); + $azureNodePoolId = 'azureNodePoolId-454365551'; + $request = (new CreateAzureNodePoolRequest()) + ->setParent($formattedParent) + ->setAzureNodePool($azureNodePool) + ->setAzureNodePoolId($azureNodePoolId); + $response = $gapicClient->createAzureNodePool($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createAzureNodePoolTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteAzureClientTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteAzureClientTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new GPBEmpty(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/deleteAzureClientTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedName = $gapicClient->azureClientName('[PROJECT]', '[LOCATION]', '[AZURE_CLIENT]'); + $request = (new DeleteAzureClientRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteAzureClient($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AzureClusters/DeleteAzureClient', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteAzureClientTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteAzureClientExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteAzureClientTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->azureClientName('[PROJECT]', '[LOCATION]', '[AZURE_CLIENT]'); + $request = (new DeleteAzureClientRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteAzureClient($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteAzureClientTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteAzureClusterTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteAzureClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new GPBEmpty(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/deleteAzureClusterTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedName = $gapicClient->azureClusterName('[PROJECT]', '[LOCATION]', '[AZURE_CLUSTER]'); + $request = (new DeleteAzureClusterRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteAzureCluster($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AzureClusters/DeleteAzureCluster', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteAzureClusterTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteAzureClusterExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteAzureClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->azureClusterName('[PROJECT]', '[LOCATION]', '[AZURE_CLUSTER]'); + $request = (new DeleteAzureClusterRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteAzureCluster($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteAzureClusterTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteAzureNodePoolTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteAzureNodePoolTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new GPBEmpty(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/deleteAzureNodePoolTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedName = $gapicClient->azureNodePoolName('[PROJECT]', '[LOCATION]', '[AZURE_CLUSTER]', '[AZURE_NODE_POOL]'); + $request = (new DeleteAzureNodePoolRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteAzureNodePool($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AzureClusters/DeleteAzureNodePool', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteAzureNodePoolTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteAzureNodePoolExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteAzureNodePoolTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->azureNodePoolName('[PROJECT]', '[LOCATION]', '[AZURE_CLUSTER]', '[AZURE_NODE_POOL]'); + $request = (new DeleteAzureNodePoolRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteAzureNodePool($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteAzureNodePoolTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function generateAzureAccessTokenTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $accessToken = 'accessToken-1938933922'; + $expectedResponse = new GenerateAzureAccessTokenResponse(); + $expectedResponse->setAccessToken($accessToken); + $transport->addResponse($expectedResponse); + // Mock request + $formattedAzureCluster = $gapicClient->azureClusterName('[PROJECT]', '[LOCATION]', '[AZURE_CLUSTER]'); + $request = (new GenerateAzureAccessTokenRequest()) + ->setAzureCluster($formattedAzureCluster); + $response = $gapicClient->generateAzureAccessToken($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AzureClusters/GenerateAzureAccessToken', $actualFuncCall); + $actualValue = $actualRequestObject->getAzureCluster(); + $this->assertProtobufEquals($formattedAzureCluster, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function generateAzureAccessTokenExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedAzureCluster = $gapicClient->azureClusterName('[PROJECT]', '[LOCATION]', '[AZURE_CLUSTER]'); + $request = (new GenerateAzureAccessTokenRequest()) + ->setAzureCluster($formattedAzureCluster); + try { + $gapicClient->generateAzureAccessToken($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getAzureClientTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $tenantId = 'tenantId-1852780336'; + $applicationId = 'applicationId-1287148950'; + $reconciling = false; + $pemCertificate = 'pemCertificate1234463984'; + $uid = 'uid115792'; + $expectedResponse = new AzureClient(); + $expectedResponse->setName($name2); + $expectedResponse->setTenantId($tenantId); + $expectedResponse->setApplicationId($applicationId); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setPemCertificate($pemCertificate); + $expectedResponse->setUid($uid); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->azureClientName('[PROJECT]', '[LOCATION]', '[AZURE_CLIENT]'); + $request = (new GetAzureClientRequest()) + ->setName($formattedName); + $response = $gapicClient->getAzureClient($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureClient', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getAzureClientExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->azureClientName('[PROJECT]', '[LOCATION]', '[AZURE_CLIENT]'); + $request = (new GetAzureClientRequest()) + ->setName($formattedName); + try { + $gapicClient->getAzureClient($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getAzureClusterTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $description = 'description-1724546052'; + $azureRegion = 'azureRegion-253373788'; + $resourceGroupId = 'resourceGroupId-1092054036'; + $azureClient = 'azureClient-676290693'; + $endpoint = 'endpoint1741102485'; + $uid = 'uid115792'; + $reconciling = false; + $etag = 'etag3123477'; + $clusterCaCertificate = 'clusterCaCertificate1324742683'; + $expectedResponse = new AzureCluster(); + $expectedResponse->setName($name2); + $expectedResponse->setDescription($description); + $expectedResponse->setAzureRegion($azureRegion); + $expectedResponse->setResourceGroupId($resourceGroupId); + $expectedResponse->setAzureClient($azureClient); + $expectedResponse->setEndpoint($endpoint); + $expectedResponse->setUid($uid); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setEtag($etag); + $expectedResponse->setClusterCaCertificate($clusterCaCertificate); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->azureClusterName('[PROJECT]', '[LOCATION]', '[AZURE_CLUSTER]'); + $request = (new GetAzureClusterRequest()) + ->setName($formattedName); + $response = $gapicClient->getAzureCluster($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureCluster', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getAzureClusterExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->azureClusterName('[PROJECT]', '[LOCATION]', '[AZURE_CLUSTER]'); + $request = (new GetAzureClusterRequest()) + ->setName($formattedName); + try { + $gapicClient->getAzureCluster($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getAzureNodePoolTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $version = 'version351608024'; + $subnetId = 'subnetId373593405'; + $uid = 'uid115792'; + $reconciling = false; + $etag = 'etag3123477'; + $azureAvailabilityZone = 'azureAvailabilityZone541920864'; + $expectedResponse = new AzureNodePool(); + $expectedResponse->setName($name2); + $expectedResponse->setVersion($version); + $expectedResponse->setSubnetId($subnetId); + $expectedResponse->setUid($uid); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setEtag($etag); + $expectedResponse->setAzureAvailabilityZone($azureAvailabilityZone); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->azureNodePoolName('[PROJECT]', '[LOCATION]', '[AZURE_CLUSTER]', '[AZURE_NODE_POOL]'); + $request = (new GetAzureNodePoolRequest()) + ->setName($formattedName); + $response = $gapicClient->getAzureNodePool($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureNodePool', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getAzureNodePoolExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->azureNodePoolName('[PROJECT]', '[LOCATION]', '[AZURE_CLUSTER]', '[AZURE_NODE_POOL]'); + $request = (new GetAzureNodePoolRequest()) + ->setName($formattedName); + try { + $gapicClient->getAzureNodePool($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getAzureServerConfigTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $expectedResponse = new AzureServerConfig(); + $expectedResponse->setName($name2); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->azureServerConfigName('[PROJECT]', '[LOCATION]'); + $request = (new GetAzureServerConfigRequest()) + ->setName($formattedName); + $response = $gapicClient->getAzureServerConfig($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AzureClusters/GetAzureServerConfig', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getAzureServerConfigExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->azureServerConfigName('[PROJECT]', '[LOCATION]'); + $request = (new GetAzureServerConfigRequest()) + ->setName($formattedName); + try { + $gapicClient->getAzureServerConfig($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listAzureClientsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $azureClientsElement = new AzureClient(); + $azureClients = [ + $azureClientsElement, + ]; + $expectedResponse = new ListAzureClientsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setAzureClients($azureClients); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListAzureClientsRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listAzureClients($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getAzureClients()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AzureClusters/ListAzureClients', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listAzureClientsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListAzureClientsRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listAzureClients($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listAzureClustersTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $azureClustersElement = new AzureCluster(); + $azureClusters = [ + $azureClustersElement, + ]; + $expectedResponse = new ListAzureClustersResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setAzureClusters($azureClusters); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListAzureClustersRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listAzureClusters($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getAzureClusters()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AzureClusters/ListAzureClusters', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listAzureClustersExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListAzureClustersRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listAzureClusters($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listAzureNodePoolsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $azureNodePoolsElement = new AzureNodePool(); + $azureNodePools = [ + $azureNodePoolsElement, + ]; + $expectedResponse = new ListAzureNodePoolsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setAzureNodePools($azureNodePools); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->azureClusterName('[PROJECT]', '[LOCATION]', '[AZURE_CLUSTER]'); + $request = (new ListAzureNodePoolsRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listAzureNodePools($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getAzureNodePools()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AzureClusters/ListAzureNodePools', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listAzureNodePoolsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->azureClusterName('[PROJECT]', '[LOCATION]', '[AZURE_CLUSTER]'); + $request = (new ListAzureNodePoolsRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listAzureNodePools($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function updateAzureClusterTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateAzureClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $description = 'description-1724546052'; + $azureRegion = 'azureRegion-253373788'; + $resourceGroupId = 'resourceGroupId-1092054036'; + $azureClient = 'azureClient-676290693'; + $endpoint = 'endpoint1741102485'; + $uid = 'uid115792'; + $reconciling = false; + $etag = 'etag3123477'; + $clusterCaCertificate = 'clusterCaCertificate1324742683'; + $expectedResponse = new AzureCluster(); + $expectedResponse->setName($name); + $expectedResponse->setDescription($description); + $expectedResponse->setAzureRegion($azureRegion); + $expectedResponse->setResourceGroupId($resourceGroupId); + $expectedResponse->setAzureClient($azureClient); + $expectedResponse->setEndpoint($endpoint); + $expectedResponse->setUid($uid); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setEtag($etag); + $expectedResponse->setClusterCaCertificate($clusterCaCertificate); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/updateAzureClusterTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $azureCluster = new AzureCluster(); + $azureClusterAzureRegion = 'azureClusterAzureRegion-1036501768'; + $azureCluster->setAzureRegion($azureClusterAzureRegion); + $azureClusterResourceGroupId = 'azureClusterResourceGroupId-1683734495'; + $azureCluster->setResourceGroupId($azureClusterResourceGroupId); + $azureClusterNetworking = new AzureClusterNetworking(); + $networkingVirtualNetworkId = 'networkingVirtualNetworkId-516550606'; + $azureClusterNetworking->setVirtualNetworkId($networkingVirtualNetworkId); + $networkingPodAddressCidrBlocks = []; + $azureClusterNetworking->setPodAddressCidrBlocks($networkingPodAddressCidrBlocks); + $networkingServiceAddressCidrBlocks = []; + $azureClusterNetworking->setServiceAddressCidrBlocks($networkingServiceAddressCidrBlocks); + $azureCluster->setNetworking($azureClusterNetworking); + $azureClusterControlPlane = new AzureControlPlane(); + $controlPlaneVersion = 'controlPlaneVersion648040665'; + $azureClusterControlPlane->setVersion($controlPlaneVersion); + $controlPlaneSshConfig = new AzureSshConfig(); + $sshConfigAuthorizedKey = 'sshConfigAuthorizedKey1626409850'; + $controlPlaneSshConfig->setAuthorizedKey($sshConfigAuthorizedKey); + $azureClusterControlPlane->setSshConfig($controlPlaneSshConfig); + $azureCluster->setControlPlane($azureClusterControlPlane); + $azureClusterAuthorization = new AzureAuthorization(); + $authorizationAdminUsers = []; + $azureClusterAuthorization->setAdminUsers($authorizationAdminUsers); + $azureCluster->setAuthorization($azureClusterAuthorization); + $azureClusterFleet = new Fleet(); + $fleetProject = 'fleetProject604893675'; + $azureClusterFleet->setProject($fleetProject); + $azureCluster->setFleet($azureClusterFleet); + $updateMask = new FieldMask(); + $request = (new UpdateAzureClusterRequest()) + ->setAzureCluster($azureCluster) + ->setUpdateMask($updateMask); + $response = $gapicClient->updateAzureCluster($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AzureClusters/UpdateAzureCluster', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getAzureCluster(); + $this->assertProtobufEquals($azureCluster, $actualValue); + $actualValue = $actualApiRequestObject->getUpdateMask(); + $this->assertProtobufEquals($updateMask, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateAzureClusterTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateAzureClusterExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateAzureClusterTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $azureCluster = new AzureCluster(); + $azureClusterAzureRegion = 'azureClusterAzureRegion-1036501768'; + $azureCluster->setAzureRegion($azureClusterAzureRegion); + $azureClusterResourceGroupId = 'azureClusterResourceGroupId-1683734495'; + $azureCluster->setResourceGroupId($azureClusterResourceGroupId); + $azureClusterNetworking = new AzureClusterNetworking(); + $networkingVirtualNetworkId = 'networkingVirtualNetworkId-516550606'; + $azureClusterNetworking->setVirtualNetworkId($networkingVirtualNetworkId); + $networkingPodAddressCidrBlocks = []; + $azureClusterNetworking->setPodAddressCidrBlocks($networkingPodAddressCidrBlocks); + $networkingServiceAddressCidrBlocks = []; + $azureClusterNetworking->setServiceAddressCidrBlocks($networkingServiceAddressCidrBlocks); + $azureCluster->setNetworking($azureClusterNetworking); + $azureClusterControlPlane = new AzureControlPlane(); + $controlPlaneVersion = 'controlPlaneVersion648040665'; + $azureClusterControlPlane->setVersion($controlPlaneVersion); + $controlPlaneSshConfig = new AzureSshConfig(); + $sshConfigAuthorizedKey = 'sshConfigAuthorizedKey1626409850'; + $controlPlaneSshConfig->setAuthorizedKey($sshConfigAuthorizedKey); + $azureClusterControlPlane->setSshConfig($controlPlaneSshConfig); + $azureCluster->setControlPlane($azureClusterControlPlane); + $azureClusterAuthorization = new AzureAuthorization(); + $authorizationAdminUsers = []; + $azureClusterAuthorization->setAdminUsers($authorizationAdminUsers); + $azureCluster->setAuthorization($azureClusterAuthorization); + $azureClusterFleet = new Fleet(); + $fleetProject = 'fleetProject604893675'; + $azureClusterFleet->setProject($fleetProject); + $azureCluster->setFleet($azureClusterFleet); + $updateMask = new FieldMask(); + $request = (new UpdateAzureClusterRequest()) + ->setAzureCluster($azureCluster) + ->setUpdateMask($updateMask); + $response = $gapicClient->updateAzureCluster($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateAzureClusterTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateAzureNodePoolTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateAzureNodePoolTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $version = 'version351608024'; + $subnetId = 'subnetId373593405'; + $uid = 'uid115792'; + $reconciling = false; + $etag = 'etag3123477'; + $azureAvailabilityZone = 'azureAvailabilityZone541920864'; + $expectedResponse = new AzureNodePool(); + $expectedResponse->setName($name); + $expectedResponse->setVersion($version); + $expectedResponse->setSubnetId($subnetId); + $expectedResponse->setUid($uid); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setEtag($etag); + $expectedResponse->setAzureAvailabilityZone($azureAvailabilityZone); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/updateAzureNodePoolTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $azureNodePool = new AzureNodePool(); + $azureNodePoolVersion = 'azureNodePoolVersion349490987'; + $azureNodePool->setVersion($azureNodePoolVersion); + $azureNodePoolConfig = new AzureNodeConfig(); + $configSshConfig = new AzureSshConfig(); + $sshConfigAuthorizedKey = 'sshConfigAuthorizedKey1626409850'; + $configSshConfig->setAuthorizedKey($sshConfigAuthorizedKey); + $azureNodePoolConfig->setSshConfig($configSshConfig); + $azureNodePool->setConfig($azureNodePoolConfig); + $azureNodePoolSubnetId = 'azureNodePoolSubnetId-2131787419'; + $azureNodePool->setSubnetId($azureNodePoolSubnetId); + $azureNodePoolAutoscaling = new AzureNodePoolAutoscaling(); + $autoscalingMinNodeCount = 1464441581; + $azureNodePoolAutoscaling->setMinNodeCount($autoscalingMinNodeCount); + $autoscalingMaxNodeCount = 1938867647; + $azureNodePoolAutoscaling->setMaxNodeCount($autoscalingMaxNodeCount); + $azureNodePool->setAutoscaling($azureNodePoolAutoscaling); + $azureNodePoolMaxPodsConstraint = new MaxPodsConstraint(); + $maxPodsConstraintMaxPodsPerNode = 1072618940; + $azureNodePoolMaxPodsConstraint->setMaxPodsPerNode($maxPodsConstraintMaxPodsPerNode); + $azureNodePool->setMaxPodsConstraint($azureNodePoolMaxPodsConstraint); + $updateMask = new FieldMask(); + $request = (new UpdateAzureNodePoolRequest()) + ->setAzureNodePool($azureNodePool) + ->setUpdateMask($updateMask); + $response = $gapicClient->updateAzureNodePool($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AzureClusters/UpdateAzureNodePool', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getAzureNodePool(); + $this->assertProtobufEquals($azureNodePool, $actualValue); + $actualValue = $actualApiRequestObject->getUpdateMask(); + $this->assertProtobufEquals($updateMask, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateAzureNodePoolTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updateAzureNodePoolExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updateAzureNodePoolTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $azureNodePool = new AzureNodePool(); + $azureNodePoolVersion = 'azureNodePoolVersion349490987'; + $azureNodePool->setVersion($azureNodePoolVersion); + $azureNodePoolConfig = new AzureNodeConfig(); + $configSshConfig = new AzureSshConfig(); + $sshConfigAuthorizedKey = 'sshConfigAuthorizedKey1626409850'; + $configSshConfig->setAuthorizedKey($sshConfigAuthorizedKey); + $azureNodePoolConfig->setSshConfig($configSshConfig); + $azureNodePool->setConfig($azureNodePoolConfig); + $azureNodePoolSubnetId = 'azureNodePoolSubnetId-2131787419'; + $azureNodePool->setSubnetId($azureNodePoolSubnetId); + $azureNodePoolAutoscaling = new AzureNodePoolAutoscaling(); + $autoscalingMinNodeCount = 1464441581; + $azureNodePoolAutoscaling->setMinNodeCount($autoscalingMinNodeCount); + $autoscalingMaxNodeCount = 1938867647; + $azureNodePoolAutoscaling->setMaxNodeCount($autoscalingMaxNodeCount); + $azureNodePool->setAutoscaling($azureNodePoolAutoscaling); + $azureNodePoolMaxPodsConstraint = new MaxPodsConstraint(); + $maxPodsConstraintMaxPodsPerNode = 1072618940; + $azureNodePoolMaxPodsConstraint->setMaxPodsPerNode($maxPodsConstraintMaxPodsPerNode); + $azureNodePool->setMaxPodsConstraint($azureNodePoolMaxPodsConstraint); + $updateMask = new FieldMask(); + $request = (new UpdateAzureNodePoolRequest()) + ->setAzureNodePool($azureNodePool) + ->setUpdateMask($updateMask); + $response = $gapicClient->updateAzureNodePool($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updateAzureNodePoolTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createAzureClientAsyncTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createAzureClientTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $tenantId = 'tenantId-1852780336'; + $applicationId = 'applicationId-1287148950'; + $reconciling = false; + $pemCertificate = 'pemCertificate1234463984'; + $uid = 'uid115792'; + $expectedResponse = new AzureClient(); + $expectedResponse->setName($name); + $expectedResponse->setTenantId($tenantId); + $expectedResponse->setApplicationId($applicationId); + $expectedResponse->setReconciling($reconciling); + $expectedResponse->setPemCertificate($pemCertificate); + $expectedResponse->setUid($uid); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createAzureClientTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $azureClient = new AzureClient(); + $azureClientTenantId = 'azureClientTenantId-567307073'; + $azureClient->setTenantId($azureClientTenantId); + $azureClientApplicationId = 'azureClientApplicationId264838513'; + $azureClient->setApplicationId($azureClientApplicationId); + $azureClientId = 'azureClientId315645023'; + $request = (new CreateAzureClientRequest()) + ->setParent($formattedParent) + ->setAzureClient($azureClient) + ->setAzureClientId($azureClientId); + $response = $gapicClient->createAzureClientAsync($request)->wait(); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.gkemulticloud.v1.AzureClusters/CreateAzureClient', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getAzureClient(); + $this->assertProtobufEquals($azureClient, $actualValue); + $actualValue = $actualApiRequestObject->getAzureClientId(); + $this->assertProtobufEquals($azureClientId, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createAzureClientTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } +} diff --git a/Grafeas/samples/V1/GrafeasClient/batch_create_notes.php b/Grafeas/samples/V1/GrafeasClient/batch_create_notes.php index 8ea604080333..f1e045a17fd7 100644 --- a/Grafeas/samples/V1/GrafeasClient/batch_create_notes.php +++ b/Grafeas/samples/V1/GrafeasClient/batch_create_notes.php @@ -24,8 +24,9 @@ // [START containeranalysis_v1_generated_Grafeas_BatchCreateNotes_sync] use Google\ApiCore\ApiException; +use Grafeas\V1\BatchCreateNotesRequest; use Grafeas\V1\BatchCreateNotesResponse; -use Grafeas\V1\GrafeasClient; +use Grafeas\V1\Client\GrafeasClient; /** * Creates new notes in batch. @@ -39,13 +40,16 @@ function batch_create_notes_sample(string $formattedParent): void // Create a client. $grafeasClient = new GrafeasClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $notes = []; + $request = (new BatchCreateNotesRequest()) + ->setParent($formattedParent) + ->setNotes($notes); // Call the API and handle any network failures. try { /** @var BatchCreateNotesResponse $response */ - $response = $grafeasClient->batchCreateNotes($formattedParent, $notes); + $response = $grafeasClient->batchCreateNotes($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Grafeas/samples/V1/GrafeasClient/batch_create_occurrences.php b/Grafeas/samples/V1/GrafeasClient/batch_create_occurrences.php index 94d3326b17f1..031b3db262e8 100644 --- a/Grafeas/samples/V1/GrafeasClient/batch_create_occurrences.php +++ b/Grafeas/samples/V1/GrafeasClient/batch_create_occurrences.php @@ -24,8 +24,9 @@ // [START containeranalysis_v1_generated_Grafeas_BatchCreateOccurrences_sync] use Google\ApiCore\ApiException; +use Grafeas\V1\BatchCreateOccurrencesRequest; use Grafeas\V1\BatchCreateOccurrencesResponse; -use Grafeas\V1\GrafeasClient; +use Grafeas\V1\Client\GrafeasClient; use Grafeas\V1\Occurrence; /** @@ -40,13 +41,16 @@ function batch_create_occurrences_sample(string $formattedParent): void // Create a client. $grafeasClient = new GrafeasClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $occurrences = [new Occurrence()]; + $request = (new BatchCreateOccurrencesRequest()) + ->setParent($formattedParent) + ->setOccurrences($occurrences); // Call the API and handle any network failures. try { /** @var BatchCreateOccurrencesResponse $response */ - $response = $grafeasClient->batchCreateOccurrences($formattedParent, $occurrences); + $response = $grafeasClient->batchCreateOccurrences($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Grafeas/samples/V1/GrafeasClient/create_note.php b/Grafeas/samples/V1/GrafeasClient/create_note.php index e486430093e5..d5af07f58eaa 100644 --- a/Grafeas/samples/V1/GrafeasClient/create_note.php +++ b/Grafeas/samples/V1/GrafeasClient/create_note.php @@ -24,7 +24,8 @@ // [START containeranalysis_v1_generated_Grafeas_CreateNote_sync] use Google\ApiCore\ApiException; -use Grafeas\V1\GrafeasClient; +use Grafeas\V1\Client\GrafeasClient; +use Grafeas\V1\CreateNoteRequest; use Grafeas\V1\Note; /** @@ -40,13 +41,17 @@ function create_note_sample(string $formattedParent, string $noteId): void // Create a client. $grafeasClient = new GrafeasClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $note = new Note(); + $request = (new CreateNoteRequest()) + ->setParent($formattedParent) + ->setNoteId($noteId) + ->setNote($note); // Call the API and handle any network failures. try { /** @var Note $response */ - $response = $grafeasClient->createNote($formattedParent, $noteId, $note); + $response = $grafeasClient->createNote($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Grafeas/samples/V1/GrafeasClient/create_occurrence.php b/Grafeas/samples/V1/GrafeasClient/create_occurrence.php index c28e5662862f..7ccbc7f2bc77 100644 --- a/Grafeas/samples/V1/GrafeasClient/create_occurrence.php +++ b/Grafeas/samples/V1/GrafeasClient/create_occurrence.php @@ -24,7 +24,8 @@ // [START containeranalysis_v1_generated_Grafeas_CreateOccurrence_sync] use Google\ApiCore\ApiException; -use Grafeas\V1\GrafeasClient; +use Grafeas\V1\Client\GrafeasClient; +use Grafeas\V1\CreateOccurrenceRequest; use Grafeas\V1\Occurrence; /** @@ -39,13 +40,16 @@ function create_occurrence_sample(string $formattedParent): void // Create a client. $grafeasClient = new GrafeasClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $occurrence = new Occurrence(); + $request = (new CreateOccurrenceRequest()) + ->setParent($formattedParent) + ->setOccurrence($occurrence); // Call the API and handle any network failures. try { /** @var Occurrence $response */ - $response = $grafeasClient->createOccurrence($formattedParent, $occurrence); + $response = $grafeasClient->createOccurrence($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Grafeas/samples/V1/GrafeasClient/delete_note.php b/Grafeas/samples/V1/GrafeasClient/delete_note.php index eeac47ff911b..f93ff01f611d 100644 --- a/Grafeas/samples/V1/GrafeasClient/delete_note.php +++ b/Grafeas/samples/V1/GrafeasClient/delete_note.php @@ -24,7 +24,8 @@ // [START containeranalysis_v1_generated_Grafeas_DeleteNote_sync] use Google\ApiCore\ApiException; -use Grafeas\V1\GrafeasClient; +use Grafeas\V1\Client\GrafeasClient; +use Grafeas\V1\DeleteNoteRequest; /** * Deletes the specified note. @@ -38,9 +39,13 @@ function delete_note_sample(string $formattedName): void // Create a client. $grafeasClient = new GrafeasClient(); + // Prepare the request message. + $request = (new DeleteNoteRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { - $grafeasClient->deleteNote($formattedName); + $grafeasClient->deleteNote($request); printf('Call completed successfully.' . PHP_EOL); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Grafeas/samples/V1/GrafeasClient/delete_occurrence.php b/Grafeas/samples/V1/GrafeasClient/delete_occurrence.php index 6c1ba9141f8f..c80f15417be3 100644 --- a/Grafeas/samples/V1/GrafeasClient/delete_occurrence.php +++ b/Grafeas/samples/V1/GrafeasClient/delete_occurrence.php @@ -24,7 +24,8 @@ // [START containeranalysis_v1_generated_Grafeas_DeleteOccurrence_sync] use Google\ApiCore\ApiException; -use Grafeas\V1\GrafeasClient; +use Grafeas\V1\Client\GrafeasClient; +use Grafeas\V1\DeleteOccurrenceRequest; /** * Deletes the specified occurrence. For example, use this method to delete an @@ -40,9 +41,13 @@ function delete_occurrence_sample(string $formattedName): void // Create a client. $grafeasClient = new GrafeasClient(); + // Prepare the request message. + $request = (new DeleteOccurrenceRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { - $grafeasClient->deleteOccurrence($formattedName); + $grafeasClient->deleteOccurrence($request); printf('Call completed successfully.' . PHP_EOL); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Grafeas/samples/V1/GrafeasClient/get_note.php b/Grafeas/samples/V1/GrafeasClient/get_note.php index 6589b7428759..f4452314faa1 100644 --- a/Grafeas/samples/V1/GrafeasClient/get_note.php +++ b/Grafeas/samples/V1/GrafeasClient/get_note.php @@ -24,7 +24,8 @@ // [START containeranalysis_v1_generated_Grafeas_GetNote_sync] use Google\ApiCore\ApiException; -use Grafeas\V1\GrafeasClient; +use Grafeas\V1\Client\GrafeasClient; +use Grafeas\V1\GetNoteRequest; use Grafeas\V1\Note; /** @@ -39,10 +40,14 @@ function get_note_sample(string $formattedName): void // Create a client. $grafeasClient = new GrafeasClient(); + // Prepare the request message. + $request = (new GetNoteRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var Note $response */ - $response = $grafeasClient->getNote($formattedName); + $response = $grafeasClient->getNote($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Grafeas/samples/V1/GrafeasClient/get_occurrence.php b/Grafeas/samples/V1/GrafeasClient/get_occurrence.php index 725407a2506e..4be521bb0a42 100644 --- a/Grafeas/samples/V1/GrafeasClient/get_occurrence.php +++ b/Grafeas/samples/V1/GrafeasClient/get_occurrence.php @@ -24,7 +24,8 @@ // [START containeranalysis_v1_generated_Grafeas_GetOccurrence_sync] use Google\ApiCore\ApiException; -use Grafeas\V1\GrafeasClient; +use Grafeas\V1\Client\GrafeasClient; +use Grafeas\V1\GetOccurrenceRequest; use Grafeas\V1\Occurrence; /** @@ -39,10 +40,14 @@ function get_occurrence_sample(string $formattedName): void // Create a client. $grafeasClient = new GrafeasClient(); + // Prepare the request message. + $request = (new GetOccurrenceRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var Occurrence $response */ - $response = $grafeasClient->getOccurrence($formattedName); + $response = $grafeasClient->getOccurrence($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Grafeas/samples/V1/GrafeasClient/get_occurrence_note.php b/Grafeas/samples/V1/GrafeasClient/get_occurrence_note.php index c83f466aaa34..d40417f381eb 100644 --- a/Grafeas/samples/V1/GrafeasClient/get_occurrence_note.php +++ b/Grafeas/samples/V1/GrafeasClient/get_occurrence_note.php @@ -24,7 +24,8 @@ // [START containeranalysis_v1_generated_Grafeas_GetOccurrenceNote_sync] use Google\ApiCore\ApiException; -use Grafeas\V1\GrafeasClient; +use Grafeas\V1\Client\GrafeasClient; +use Grafeas\V1\GetOccurrenceNoteRequest; use Grafeas\V1\Note; /** @@ -40,10 +41,14 @@ function get_occurrence_note_sample(string $formattedName): void // Create a client. $grafeasClient = new GrafeasClient(); + // Prepare the request message. + $request = (new GetOccurrenceNoteRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var Note $response */ - $response = $grafeasClient->getOccurrenceNote($formattedName); + $response = $grafeasClient->getOccurrenceNote($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Grafeas/samples/V1/GrafeasClient/list_note_occurrences.php b/Grafeas/samples/V1/GrafeasClient/list_note_occurrences.php index 2f58e97ed99a..8c14688724ee 100644 --- a/Grafeas/samples/V1/GrafeasClient/list_note_occurrences.php +++ b/Grafeas/samples/V1/GrafeasClient/list_note_occurrences.php @@ -25,7 +25,8 @@ // [START containeranalysis_v1_generated_Grafeas_ListNoteOccurrences_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Grafeas\V1\GrafeasClient; +use Grafeas\V1\Client\GrafeasClient; +use Grafeas\V1\ListNoteOccurrencesRequest; use Grafeas\V1\Occurrence; /** @@ -42,10 +43,14 @@ function list_note_occurrences_sample(string $formattedName): void // Create a client. $grafeasClient = new GrafeasClient(); + // Prepare the request message. + $request = (new ListNoteOccurrencesRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $grafeasClient->listNoteOccurrences($formattedName); + $response = $grafeasClient->listNoteOccurrences($request); /** @var Occurrence $element */ foreach ($response as $element) { diff --git a/Grafeas/samples/V1/GrafeasClient/list_notes.php b/Grafeas/samples/V1/GrafeasClient/list_notes.php index fca9e4c178f8..a63430979581 100644 --- a/Grafeas/samples/V1/GrafeasClient/list_notes.php +++ b/Grafeas/samples/V1/GrafeasClient/list_notes.php @@ -25,7 +25,8 @@ // [START containeranalysis_v1_generated_Grafeas_ListNotes_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Grafeas\V1\GrafeasClient; +use Grafeas\V1\Client\GrafeasClient; +use Grafeas\V1\ListNotesRequest; use Grafeas\V1\Note; /** @@ -40,10 +41,14 @@ function list_notes_sample(string $formattedParent): void // Create a client. $grafeasClient = new GrafeasClient(); + // Prepare the request message. + $request = (new ListNotesRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $grafeasClient->listNotes($formattedParent); + $response = $grafeasClient->listNotes($request); /** @var Note $element */ foreach ($response as $element) { diff --git a/Grafeas/samples/V1/GrafeasClient/list_occurrences.php b/Grafeas/samples/V1/GrafeasClient/list_occurrences.php index dacbe335372f..417f7a8a119c 100644 --- a/Grafeas/samples/V1/GrafeasClient/list_occurrences.php +++ b/Grafeas/samples/V1/GrafeasClient/list_occurrences.php @@ -25,7 +25,8 @@ // [START containeranalysis_v1_generated_Grafeas_ListOccurrences_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Grafeas\V1\GrafeasClient; +use Grafeas\V1\Client\GrafeasClient; +use Grafeas\V1\ListOccurrencesRequest; use Grafeas\V1\Occurrence; /** @@ -40,10 +41,14 @@ function list_occurrences_sample(string $formattedParent): void // Create a client. $grafeasClient = new GrafeasClient(); + // Prepare the request message. + $request = (new ListOccurrencesRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $grafeasClient->listOccurrences($formattedParent); + $response = $grafeasClient->listOccurrences($request); /** @var Occurrence $element */ foreach ($response as $element) { diff --git a/Grafeas/samples/V1/GrafeasClient/update_note.php b/Grafeas/samples/V1/GrafeasClient/update_note.php index b0b0c2832e02..3c6826068d22 100644 --- a/Grafeas/samples/V1/GrafeasClient/update_note.php +++ b/Grafeas/samples/V1/GrafeasClient/update_note.php @@ -24,8 +24,9 @@ // [START containeranalysis_v1_generated_Grafeas_UpdateNote_sync] use Google\ApiCore\ApiException; -use Grafeas\V1\GrafeasClient; +use Grafeas\V1\Client\GrafeasClient; use Grafeas\V1\Note; +use Grafeas\V1\UpdateNoteRequest; /** * Updates the specified note. @@ -39,13 +40,16 @@ function update_note_sample(string $formattedName): void // Create a client. $grafeasClient = new GrafeasClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $note = new Note(); + $request = (new UpdateNoteRequest()) + ->setName($formattedName) + ->setNote($note); // Call the API and handle any network failures. try { /** @var Note $response */ - $response = $grafeasClient->updateNote($formattedName, $note); + $response = $grafeasClient->updateNote($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Grafeas/samples/V1/GrafeasClient/update_occurrence.php b/Grafeas/samples/V1/GrafeasClient/update_occurrence.php index 1d2cdc0168e2..87a5600f5dfa 100644 --- a/Grafeas/samples/V1/GrafeasClient/update_occurrence.php +++ b/Grafeas/samples/V1/GrafeasClient/update_occurrence.php @@ -24,8 +24,9 @@ // [START containeranalysis_v1_generated_Grafeas_UpdateOccurrence_sync] use Google\ApiCore\ApiException; -use Grafeas\V1\GrafeasClient; +use Grafeas\V1\Client\GrafeasClient; use Grafeas\V1\Occurrence; +use Grafeas\V1\UpdateOccurrenceRequest; /** * Updates the specified occurrence. @@ -39,13 +40,16 @@ function update_occurrence_sample(string $formattedName): void // Create a client. $grafeasClient = new GrafeasClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $occurrence = new Occurrence(); + $request = (new UpdateOccurrenceRequest()) + ->setName($formattedName) + ->setOccurrence($occurrence); // Call the API and handle any network failures. try { /** @var Occurrence $response */ - $response = $grafeasClient->updateOccurrence($formattedName, $occurrence); + $response = $grafeasClient->updateOccurrence($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Grafeas/src/V1/BatchCreateNotesRequest.php b/Grafeas/src/V1/BatchCreateNotesRequest.php index bde84188a55f..134a7935cf86 100644 --- a/Grafeas/src/V1/BatchCreateNotesRequest.php +++ b/Grafeas/src/V1/BatchCreateNotesRequest.php @@ -29,6 +29,23 @@ class BatchCreateNotesRequest extends \Google\Protobuf\Internal\Message */ private $notes; + /** + * @param string $parent The name of the project in the form of `projects/[PROJECT_ID]`, under which + * the notes are to be created. Please see + * {@see GrafeasClient::projectName()} for help formatting this field. + * @param array $notes The notes to create. Max allowed length is 1000. + * + * @return \Grafeas\V1\BatchCreateNotesRequest + * + * @experimental + */ + public static function build(string $parent, array $notes): self + { + return (new self()) + ->setParent($parent) + ->setNotes($notes); + } + /** * Constructor. * diff --git a/Grafeas/src/V1/BatchCreateOccurrencesRequest.php b/Grafeas/src/V1/BatchCreateOccurrencesRequest.php index d25a3c9a67d5..93edd4fff303 100644 --- a/Grafeas/src/V1/BatchCreateOccurrencesRequest.php +++ b/Grafeas/src/V1/BatchCreateOccurrencesRequest.php @@ -29,6 +29,23 @@ class BatchCreateOccurrencesRequest extends \Google\Protobuf\Internal\Message */ private $occurrences; + /** + * @param string $parent The name of the project in the form of `projects/[PROJECT_ID]`, under which + * the occurrences are to be created. Please see + * {@see GrafeasClient::projectName()} for help formatting this field. + * @param \Grafeas\V1\Occurrence[] $occurrences The occurrences to create. Max allowed length is 1000. + * + * @return \Grafeas\V1\BatchCreateOccurrencesRequest + * + * @experimental + */ + public static function build(string $parent, array $occurrences): self + { + return (new self()) + ->setParent($parent) + ->setOccurrences($occurrences); + } + /** * Constructor. * diff --git a/Grafeas/src/V1/Client/BaseClient/GrafeasBaseClient.php b/Grafeas/src/V1/Client/BaseClient/GrafeasBaseClient.php new file mode 100644 index 000000000000..ae4c13780277 --- /dev/null +++ b/Grafeas/src/V1/Client/BaseClient/GrafeasBaseClient.php @@ -0,0 +1,622 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/grafeas_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/grafeas_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/grafeas_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/grafeas_rest_client_config.php', + ], + ], + ]; + } + + /** + * Formats a string containing the fully-qualified path to represent a note + * resource. + * + * @param string $project + * @param string $note + * + * @return string The formatted note resource. + */ + public static function noteName(string $project, string $note): string + { + return self::getPathTemplate('note')->render([ + 'project' => $project, + 'note' => $note, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a occurrence + * resource. + * + * @param string $project + * @param string $occurrence + * + * @return string The formatted occurrence resource. + */ + public static function occurrenceName(string $project, string $occurrence): string + { + return self::getPathTemplate('occurrence')->render([ + 'project' => $project, + 'occurrence' => $occurrence, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a project + * resource. + * + * @param string $project + * + * @return string The formatted project resource. + */ + public static function projectName(string $project): string + { + return self::getPathTemplate('project')->render([ + 'project' => $project, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - note: projects/{project}/notes/{note} + * - occurrence: projects/{project}/occurrences/{occurrence} + * - project: projects/{project} + * + * The optional $template argument can be supplied to specify a particular pattern, + * and must match one of the templates listed above. If no $template argument is + * provided, or if the $template argument does not match one of the templates + * listed, then parseName will check each of the supported templates, and return + * the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + */ + public static function parseName(string $formattedName, string $template = null): array + { + return self::parseFormattedName($formattedName, $template); + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'containeranalysis.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Creates new notes in batch. + * + * The async variant is {@see self::batchCreateNotesAsync()} . + * + * @param BatchCreateNotesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return BatchCreateNotesResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function batchCreateNotes(BatchCreateNotesRequest $request, array $callOptions = []): BatchCreateNotesResponse + { + return $this->startApiCall('BatchCreateNotes', $request, $callOptions)->wait(); + } + + /** + * Creates new occurrences in batch. + * + * The async variant is {@see self::batchCreateOccurrencesAsync()} . + * + * @param BatchCreateOccurrencesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return BatchCreateOccurrencesResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function batchCreateOccurrences(BatchCreateOccurrencesRequest $request, array $callOptions = []): BatchCreateOccurrencesResponse + { + return $this->startApiCall('BatchCreateOccurrences', $request, $callOptions)->wait(); + } + + /** + * Creates a new note. + * + * The async variant is {@see self::createNoteAsync()} . + * + * @param CreateNoteRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Note + * + * @throws ApiException Thrown if the API call fails. + */ + public function createNote(CreateNoteRequest $request, array $callOptions = []): Note + { + return $this->startApiCall('CreateNote', $request, $callOptions)->wait(); + } + + /** + * Creates a new occurrence. + * + * The async variant is {@see self::createOccurrenceAsync()} . + * + * @param CreateOccurrenceRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Occurrence + * + * @throws ApiException Thrown if the API call fails. + */ + public function createOccurrence(CreateOccurrenceRequest $request, array $callOptions = []): Occurrence + { + return $this->startApiCall('CreateOccurrence', $request, $callOptions)->wait(); + } + + /** + * Deletes the specified note. + * + * The async variant is {@see self::deleteNoteAsync()} . + * + * @param DeleteNoteRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteNote(DeleteNoteRequest $request, array $callOptions = []): void + { + $this->startApiCall('DeleteNote', $request, $callOptions)->wait(); + } + + /** + * Deletes the specified occurrence. For example, use this method to delete an + * occurrence when the occurrence is no longer applicable for the given + * resource. + * + * The async variant is {@see self::deleteOccurrenceAsync()} . + * + * @param DeleteOccurrenceRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteOccurrence(DeleteOccurrenceRequest $request, array $callOptions = []): void + { + $this->startApiCall('DeleteOccurrence', $request, $callOptions)->wait(); + } + + /** + * Gets the specified note. + * + * The async variant is {@see self::getNoteAsync()} . + * + * @param GetNoteRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Note + * + * @throws ApiException Thrown if the API call fails. + */ + public function getNote(GetNoteRequest $request, array $callOptions = []): Note + { + return $this->startApiCall('GetNote', $request, $callOptions)->wait(); + } + + /** + * Gets the specified occurrence. + * + * The async variant is {@see self::getOccurrenceAsync()} . + * + * @param GetOccurrenceRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Occurrence + * + * @throws ApiException Thrown if the API call fails. + */ + public function getOccurrence(GetOccurrenceRequest $request, array $callOptions = []): Occurrence + { + return $this->startApiCall('GetOccurrence', $request, $callOptions)->wait(); + } + + /** + * Gets the note attached to the specified occurrence. Consumer projects can + * use this method to get a note that belongs to a provider project. + * + * The async variant is {@see self::getOccurrenceNoteAsync()} . + * + * @param GetOccurrenceNoteRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Note + * + * @throws ApiException Thrown if the API call fails. + */ + public function getOccurrenceNote(GetOccurrenceNoteRequest $request, array $callOptions = []): Note + { + return $this->startApiCall('GetOccurrenceNote', $request, $callOptions)->wait(); + } + + /** + * Lists occurrences referencing the specified note. Provider projects can use + * this method to get all occurrences across consumer projects referencing the + * specified note. + * + * The async variant is {@see self::listNoteOccurrencesAsync()} . + * + * @param ListNoteOccurrencesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listNoteOccurrences(ListNoteOccurrencesRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListNoteOccurrences', $request, $callOptions); + } + + /** + * Lists notes for the specified project. + * + * The async variant is {@see self::listNotesAsync()} . + * + * @param ListNotesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listNotes(ListNotesRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListNotes', $request, $callOptions); + } + + /** + * Lists occurrences for the specified project. + * + * The async variant is {@see self::listOccurrencesAsync()} . + * + * @param ListOccurrencesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listOccurrences(ListOccurrencesRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListOccurrences', $request, $callOptions); + } + + /** + * Updates the specified note. + * + * The async variant is {@see self::updateNoteAsync()} . + * + * @param UpdateNoteRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Note + * + * @throws ApiException Thrown if the API call fails. + */ + public function updateNote(UpdateNoteRequest $request, array $callOptions = []): Note + { + return $this->startApiCall('UpdateNote', $request, $callOptions)->wait(); + } + + /** + * Updates the specified occurrence. + * + * The async variant is {@see self::updateOccurrenceAsync()} . + * + * @param UpdateOccurrenceRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Occurrence + * + * @throws ApiException Thrown if the API call fails. + */ + public function updateOccurrence(UpdateOccurrenceRequest $request, array $callOptions = []): Occurrence + { + return $this->startApiCall('UpdateOccurrence', $request, $callOptions)->wait(); + } +} diff --git a/Grafeas/src/V1/Client/GrafeasClient.php b/Grafeas/src/V1/Client/GrafeasClient.php new file mode 100644 index 000000000000..139f7f7da7d6 --- /dev/null +++ b/Grafeas/src/V1/Client/GrafeasClient.php @@ -0,0 +1,40 @@ +setParent($parent) + ->setNoteId($noteId) + ->setNote($note); + } + /** * Constructor. * diff --git a/Grafeas/src/V1/CreateOccurrenceRequest.php b/Grafeas/src/V1/CreateOccurrenceRequest.php index 12cb78112634..28d7bd465184 100644 --- a/Grafeas/src/V1/CreateOccurrenceRequest.php +++ b/Grafeas/src/V1/CreateOccurrenceRequest.php @@ -29,6 +29,23 @@ class CreateOccurrenceRequest extends \Google\Protobuf\Internal\Message */ private $occurrence = null; + /** + * @param string $parent The name of the project in the form of `projects/[PROJECT_ID]`, under which + * the occurrence is to be created. Please see + * {@see GrafeasClient::projectName()} for help formatting this field. + * @param \Grafeas\V1\Occurrence $occurrence The occurrence to create. + * + * @return \Grafeas\V1\CreateOccurrenceRequest + * + * @experimental + */ + public static function build(string $parent, \Grafeas\V1\Occurrence $occurrence): self + { + return (new self()) + ->setParent($parent) + ->setOccurrence($occurrence); + } + /** * Constructor. * diff --git a/Grafeas/src/V1/DeleteNoteRequest.php b/Grafeas/src/V1/DeleteNoteRequest.php index fb473460726d..6070781a64b6 100644 --- a/Grafeas/src/V1/DeleteNoteRequest.php +++ b/Grafeas/src/V1/DeleteNoteRequest.php @@ -23,6 +23,21 @@ class DeleteNoteRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name The name of the note in the form of + * `projects/[PROVIDER_ID]/notes/[NOTE_ID]`. Please see + * {@see GrafeasClient::noteName()} for help formatting this field. + * + * @return \Grafeas\V1\DeleteNoteRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Grafeas/src/V1/DeleteOccurrenceRequest.php b/Grafeas/src/V1/DeleteOccurrenceRequest.php index 30d5987b4c2e..b645304cb338 100644 --- a/Grafeas/src/V1/DeleteOccurrenceRequest.php +++ b/Grafeas/src/V1/DeleteOccurrenceRequest.php @@ -23,6 +23,21 @@ class DeleteOccurrenceRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name The name of the occurrence in the form of + * `projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]`. Please see + * {@see GrafeasClient::occurrenceName()} for help formatting this field. + * + * @return \Grafeas\V1\DeleteOccurrenceRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Grafeas/src/V1/GetNoteRequest.php b/Grafeas/src/V1/GetNoteRequest.php index 814c9726a5c6..c63ea7fab3c3 100644 --- a/Grafeas/src/V1/GetNoteRequest.php +++ b/Grafeas/src/V1/GetNoteRequest.php @@ -23,6 +23,21 @@ class GetNoteRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name The name of the note in the form of + * `projects/[PROVIDER_ID]/notes/[NOTE_ID]`. Please see + * {@see GrafeasClient::noteName()} for help formatting this field. + * + * @return \Grafeas\V1\GetNoteRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Grafeas/src/V1/GetOccurrenceNoteRequest.php b/Grafeas/src/V1/GetOccurrenceNoteRequest.php index d33ccd30b137..2f71ef8ba656 100644 --- a/Grafeas/src/V1/GetOccurrenceNoteRequest.php +++ b/Grafeas/src/V1/GetOccurrenceNoteRequest.php @@ -23,6 +23,21 @@ class GetOccurrenceNoteRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name The name of the occurrence in the form of + * `projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]`. Please see + * {@see GrafeasClient::occurrenceName()} for help formatting this field. + * + * @return \Grafeas\V1\GetOccurrenceNoteRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Grafeas/src/V1/GetOccurrenceRequest.php b/Grafeas/src/V1/GetOccurrenceRequest.php index c8024ae6ad01..cc9c6e831520 100644 --- a/Grafeas/src/V1/GetOccurrenceRequest.php +++ b/Grafeas/src/V1/GetOccurrenceRequest.php @@ -23,6 +23,21 @@ class GetOccurrenceRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name The name of the occurrence in the form of + * `projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]`. Please see + * {@see GrafeasClient::occurrenceName()} for help formatting this field. + * + * @return \Grafeas\V1\GetOccurrenceRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Grafeas/src/V1/ListNoteOccurrencesRequest.php b/Grafeas/src/V1/ListNoteOccurrencesRequest.php index 3bb5e55256de..c42be386ca01 100644 --- a/Grafeas/src/V1/ListNoteOccurrencesRequest.php +++ b/Grafeas/src/V1/ListNoteOccurrencesRequest.php @@ -41,6 +41,23 @@ class ListNoteOccurrencesRequest extends \Google\Protobuf\Internal\Message */ private $page_token = ''; + /** + * @param string $name The name of the note to list occurrences for in the form of + * `projects/[PROVIDER_ID]/notes/[NOTE_ID]`. Please see + * {@see GrafeasClient::noteName()} for help formatting this field. + * @param string $filter The filter expression. + * + * @return \Grafeas\V1\ListNoteOccurrencesRequest + * + * @experimental + */ + public static function build(string $name, string $filter): self + { + return (new self()) + ->setName($name) + ->setFilter($filter); + } + /** * Constructor. * diff --git a/Grafeas/src/V1/ListNotesRequest.php b/Grafeas/src/V1/ListNotesRequest.php index 8a1e4001e998..4e0ba77b71fc 100644 --- a/Grafeas/src/V1/ListNotesRequest.php +++ b/Grafeas/src/V1/ListNotesRequest.php @@ -42,6 +42,23 @@ class ListNotesRequest extends \Google\Protobuf\Internal\Message */ private $page_token = ''; + /** + * @param string $parent The name of the project to list notes for in the form of + * `projects/[PROJECT_ID]`. Please see + * {@see GrafeasClient::projectName()} for help formatting this field. + * @param string $filter The filter expression. + * + * @return \Grafeas\V1\ListNotesRequest + * + * @experimental + */ + public static function build(string $parent, string $filter): self + { + return (new self()) + ->setParent($parent) + ->setFilter($filter); + } + /** * Constructor. * diff --git a/Grafeas/src/V1/ListOccurrencesRequest.php b/Grafeas/src/V1/ListOccurrencesRequest.php index bf0f54355c26..a2d019b12712 100644 --- a/Grafeas/src/V1/ListOccurrencesRequest.php +++ b/Grafeas/src/V1/ListOccurrencesRequest.php @@ -42,6 +42,23 @@ class ListOccurrencesRequest extends \Google\Protobuf\Internal\Message */ private $page_token = ''; + /** + * @param string $parent The name of the project to list occurrences for in the form of + * `projects/[PROJECT_ID]`. Please see + * {@see GrafeasClient::projectName()} for help formatting this field. + * @param string $filter The filter expression. + * + * @return \Grafeas\V1\ListOccurrencesRequest + * + * @experimental + */ + public static function build(string $parent, string $filter): self + { + return (new self()) + ->setParent($parent) + ->setFilter($filter); + } + /** * Constructor. * diff --git a/Grafeas/src/V1/UpdateNoteRequest.php b/Grafeas/src/V1/UpdateNoteRequest.php index f6b829c434c7..0c0a42901152 100644 --- a/Grafeas/src/V1/UpdateNoteRequest.php +++ b/Grafeas/src/V1/UpdateNoteRequest.php @@ -35,6 +35,25 @@ class UpdateNoteRequest extends \Google\Protobuf\Internal\Message */ private $update_mask = null; + /** + * @param string $name The name of the note in the form of + * `projects/[PROVIDER_ID]/notes/[NOTE_ID]`. Please see + * {@see GrafeasClient::noteName()} for help formatting this field. + * @param \Grafeas\V1\Note $note The updated note. + * @param \Google\Protobuf\FieldMask $updateMask The fields to update. + * + * @return \Grafeas\V1\UpdateNoteRequest + * + * @experimental + */ + public static function build(string $name, \Grafeas\V1\Note $note, \Google\Protobuf\FieldMask $updateMask): self + { + return (new self()) + ->setName($name) + ->setNote($note) + ->setUpdateMask($updateMask); + } + /** * Constructor. * diff --git a/Grafeas/src/V1/UpdateOccurrenceRequest.php b/Grafeas/src/V1/UpdateOccurrenceRequest.php index 23f15660e6a1..564c4f0705ec 100644 --- a/Grafeas/src/V1/UpdateOccurrenceRequest.php +++ b/Grafeas/src/V1/UpdateOccurrenceRequest.php @@ -35,6 +35,25 @@ class UpdateOccurrenceRequest extends \Google\Protobuf\Internal\Message */ private $update_mask = null; + /** + * @param string $name The name of the occurrence in the form of + * `projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]`. Please see + * {@see GrafeasClient::occurrenceName()} for help formatting this field. + * @param \Grafeas\V1\Occurrence $occurrence The updated occurrence. + * @param \Google\Protobuf\FieldMask $updateMask The fields to update. + * + * @return \Grafeas\V1\UpdateOccurrenceRequest + * + * @experimental + */ + public static function build(string $name, \Grafeas\V1\Occurrence $occurrence, \Google\Protobuf\FieldMask $updateMask): self + { + return (new self()) + ->setName($name) + ->setOccurrence($occurrence) + ->setUpdateMask($updateMask); + } + /** * Constructor. * diff --git a/Grafeas/src/V1/resources/grafeas_descriptor_config.php b/Grafeas/src/V1/resources/grafeas_descriptor_config.php index 2660329a8897..369d068e7af9 100644 --- a/Grafeas/src/V1/resources/grafeas_descriptor_config.php +++ b/Grafeas/src/V1/resources/grafeas_descriptor_config.php @@ -3,6 +3,114 @@ return [ 'interfaces' => [ 'grafeas.v1.Grafeas' => [ + 'BatchCreateNotes' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Grafeas\V1\BatchCreateNotesResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'BatchCreateOccurrences' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Grafeas\V1\BatchCreateOccurrencesResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'CreateNote' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Grafeas\V1\Note', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'CreateOccurrence' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Grafeas\V1\Occurrence', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'DeleteNote' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Protobuf\GPBEmpty', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'DeleteOccurrence' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Protobuf\GPBEmpty', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetNote' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Grafeas\V1\Note', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetOccurrence' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Grafeas\V1\Occurrence', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetOccurrenceNote' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Grafeas\V1\Note', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], 'ListNoteOccurrences' => [ 'pageStreaming' => [ 'requestPageTokenGetMethod' => 'getPageToken', @@ -12,6 +120,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getOccurrences', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Grafeas\V1\ListNoteOccurrencesResponse', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'ListNotes' => [ 'pageStreaming' => [ @@ -22,6 +140,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getNotes', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Grafeas\V1\ListNotesResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'ListOccurrences' => [ 'pageStreaming' => [ @@ -32,6 +160,45 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getOccurrences', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Grafeas\V1\ListOccurrencesResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'UpdateNote' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Grafeas\V1\Note', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'UpdateOccurrence' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Grafeas\V1\Occurrence', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'templateMap' => [ + 'note' => 'projects/{project}/notes/{note}', + 'occurrence' => 'projects/{project}/occurrences/{occurrence}', + 'project' => 'projects/{project}', ], ], ], diff --git a/Grafeas/tests/Unit/V1/Client/GrafeasClientTest.php b/Grafeas/tests/Unit/V1/Client/GrafeasClientTest.php new file mode 100644 index 000000000000..d601fa3a0366 --- /dev/null +++ b/Grafeas/tests/Unit/V1/Client/GrafeasClientTest.php @@ -0,0 +1,1108 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return GrafeasClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new GrafeasClient($options); + } + + /** @test */ + public function batchCreateNotesTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new BatchCreateNotesResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $notesValue = new Note(); + $notes = [ + 'notesKey' => $notesValue, + ]; + $request = (new BatchCreateNotesRequest()) + ->setParent($formattedParent) + ->setNotes($notes); + $response = $gapicClient->batchCreateNotes($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/grafeas.v1.Grafeas/BatchCreateNotes', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualRequestObject->getNotes(); + $this->assertProtobufEquals($notes, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function batchCreateNotesExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $notesValue = new Note(); + $notes = [ + 'notesKey' => $notesValue, + ]; + $request = (new BatchCreateNotesRequest()) + ->setParent($formattedParent) + ->setNotes($notes); + try { + $gapicClient->batchCreateNotes($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function batchCreateOccurrencesTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new BatchCreateOccurrencesResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $occurrences = []; + $request = (new BatchCreateOccurrencesRequest()) + ->setParent($formattedParent) + ->setOccurrences($occurrences); + $response = $gapicClient->batchCreateOccurrences($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/grafeas.v1.Grafeas/BatchCreateOccurrences', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualRequestObject->getOccurrences(); + $this->assertProtobufEquals($occurrences, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function batchCreateOccurrencesExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $occurrences = []; + $request = (new BatchCreateOccurrencesRequest()) + ->setParent($formattedParent) + ->setOccurrences($occurrences); + try { + $gapicClient->batchCreateOccurrences($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createNoteTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name = 'name3373707'; + $shortDescription = 'shortDescription-235369287'; + $longDescription = 'longDescription-1747792199'; + $expectedResponse = new Note(); + $expectedResponse->setName($name); + $expectedResponse->setShortDescription($shortDescription); + $expectedResponse->setLongDescription($longDescription); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $noteId = 'noteId2129224840'; + $note = new Note(); + $request = (new CreateNoteRequest()) + ->setParent($formattedParent) + ->setNoteId($noteId) + ->setNote($note); + $response = $gapicClient->createNote($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/grafeas.v1.Grafeas/CreateNote', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualRequestObject->getNoteId(); + $this->assertProtobufEquals($noteId, $actualValue); + $actualValue = $actualRequestObject->getNote(); + $this->assertProtobufEquals($note, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createNoteExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $noteId = 'noteId2129224840'; + $note = new Note(); + $request = (new CreateNoteRequest()) + ->setParent($formattedParent) + ->setNoteId($noteId) + ->setNote($note); + try { + $gapicClient->createNote($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createOccurrenceTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name = 'name3373707'; + $resourceUri = 'resourceUri-384040517'; + $noteName = 'noteName1780787896'; + $remediation = 'remediation779381797'; + $expectedResponse = new Occurrence(); + $expectedResponse->setName($name); + $expectedResponse->setResourceUri($resourceUri); + $expectedResponse->setNoteName($noteName); + $expectedResponse->setRemediation($remediation); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $occurrence = new Occurrence(); + $request = (new CreateOccurrenceRequest()) + ->setParent($formattedParent) + ->setOccurrence($occurrence); + $response = $gapicClient->createOccurrence($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/grafeas.v1.Grafeas/CreateOccurrence', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualRequestObject->getOccurrence(); + $this->assertProtobufEquals($occurrence, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createOccurrenceExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $occurrence = new Occurrence(); + $request = (new CreateOccurrenceRequest()) + ->setParent($formattedParent) + ->setOccurrence($occurrence); + try { + $gapicClient->createOccurrence($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function deleteNoteTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new GPBEmpty(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->noteName('[PROJECT]', '[NOTE]'); + $request = (new DeleteNoteRequest()) + ->setName($formattedName); + $gapicClient->deleteNote($request); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/grafeas.v1.Grafeas/DeleteNote', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function deleteNoteExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->noteName('[PROJECT]', '[NOTE]'); + $request = (new DeleteNoteRequest()) + ->setName($formattedName); + try { + $gapicClient->deleteNote($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function deleteOccurrenceTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new GPBEmpty(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->occurrenceName('[PROJECT]', '[OCCURRENCE]'); + $request = (new DeleteOccurrenceRequest()) + ->setName($formattedName); + $gapicClient->deleteOccurrence($request); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/grafeas.v1.Grafeas/DeleteOccurrence', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function deleteOccurrenceExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->occurrenceName('[PROJECT]', '[OCCURRENCE]'); + $request = (new DeleteOccurrenceRequest()) + ->setName($formattedName); + try { + $gapicClient->deleteOccurrence($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getNoteTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $shortDescription = 'shortDescription-235369287'; + $longDescription = 'longDescription-1747792199'; + $expectedResponse = new Note(); + $expectedResponse->setName($name2); + $expectedResponse->setShortDescription($shortDescription); + $expectedResponse->setLongDescription($longDescription); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->noteName('[PROJECT]', '[NOTE]'); + $request = (new GetNoteRequest()) + ->setName($formattedName); + $response = $gapicClient->getNote($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/grafeas.v1.Grafeas/GetNote', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getNoteExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->noteName('[PROJECT]', '[NOTE]'); + $request = (new GetNoteRequest()) + ->setName($formattedName); + try { + $gapicClient->getNote($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getOccurrenceTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $resourceUri = 'resourceUri-384040517'; + $noteName = 'noteName1780787896'; + $remediation = 'remediation779381797'; + $expectedResponse = new Occurrence(); + $expectedResponse->setName($name2); + $expectedResponse->setResourceUri($resourceUri); + $expectedResponse->setNoteName($noteName); + $expectedResponse->setRemediation($remediation); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->occurrenceName('[PROJECT]', '[OCCURRENCE]'); + $request = (new GetOccurrenceRequest()) + ->setName($formattedName); + $response = $gapicClient->getOccurrence($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/grafeas.v1.Grafeas/GetOccurrence', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getOccurrenceExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->occurrenceName('[PROJECT]', '[OCCURRENCE]'); + $request = (new GetOccurrenceRequest()) + ->setName($formattedName); + try { + $gapicClient->getOccurrence($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getOccurrenceNoteTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $shortDescription = 'shortDescription-235369287'; + $longDescription = 'longDescription-1747792199'; + $expectedResponse = new Note(); + $expectedResponse->setName($name2); + $expectedResponse->setShortDescription($shortDescription); + $expectedResponse->setLongDescription($longDescription); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->occurrenceName('[PROJECT]', '[OCCURRENCE]'); + $request = (new GetOccurrenceNoteRequest()) + ->setName($formattedName); + $response = $gapicClient->getOccurrenceNote($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/grafeas.v1.Grafeas/GetOccurrenceNote', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getOccurrenceNoteExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->occurrenceName('[PROJECT]', '[OCCURRENCE]'); + $request = (new GetOccurrenceNoteRequest()) + ->setName($formattedName); + try { + $gapicClient->getOccurrenceNote($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listNoteOccurrencesTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $occurrencesElement = new Occurrence(); + $occurrences = [ + $occurrencesElement, + ]; + $expectedResponse = new ListNoteOccurrencesResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setOccurrences($occurrences); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->noteName('[PROJECT]', '[NOTE]'); + $request = (new ListNoteOccurrencesRequest()) + ->setName($formattedName); + $response = $gapicClient->listNoteOccurrences($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getOccurrences()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/grafeas.v1.Grafeas/ListNoteOccurrences', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listNoteOccurrencesExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->noteName('[PROJECT]', '[NOTE]'); + $request = (new ListNoteOccurrencesRequest()) + ->setName($formattedName); + try { + $gapicClient->listNoteOccurrences($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listNotesTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $notesElement = new Note(); + $notes = [ + $notesElement, + ]; + $expectedResponse = new ListNotesResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setNotes($notes); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $request = (new ListNotesRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listNotes($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getNotes()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/grafeas.v1.Grafeas/ListNotes', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listNotesExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $request = (new ListNotesRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listNotes($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listOccurrencesTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $occurrencesElement = new Occurrence(); + $occurrences = [ + $occurrencesElement, + ]; + $expectedResponse = new ListOccurrencesResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setOccurrences($occurrences); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $request = (new ListOccurrencesRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listOccurrences($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getOccurrences()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/grafeas.v1.Grafeas/ListOccurrences', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listOccurrencesExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $request = (new ListOccurrencesRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listOccurrences($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function updateNoteTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $shortDescription = 'shortDescription-235369287'; + $longDescription = 'longDescription-1747792199'; + $expectedResponse = new Note(); + $expectedResponse->setName($name2); + $expectedResponse->setShortDescription($shortDescription); + $expectedResponse->setLongDescription($longDescription); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->noteName('[PROJECT]', '[NOTE]'); + $note = new Note(); + $request = (new UpdateNoteRequest()) + ->setName($formattedName) + ->setNote($note); + $response = $gapicClient->updateNote($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/grafeas.v1.Grafeas/UpdateNote', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $actualValue = $actualRequestObject->getNote(); + $this->assertProtobufEquals($note, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function updateNoteExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->noteName('[PROJECT]', '[NOTE]'); + $note = new Note(); + $request = (new UpdateNoteRequest()) + ->setName($formattedName) + ->setNote($note); + try { + $gapicClient->updateNote($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function updateOccurrenceTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $resourceUri = 'resourceUri-384040517'; + $noteName = 'noteName1780787896'; + $remediation = 'remediation779381797'; + $expectedResponse = new Occurrence(); + $expectedResponse->setName($name2); + $expectedResponse->setResourceUri($resourceUri); + $expectedResponse->setNoteName($noteName); + $expectedResponse->setRemediation($remediation); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->occurrenceName('[PROJECT]', '[OCCURRENCE]'); + $occurrence = new Occurrence(); + $request = (new UpdateOccurrenceRequest()) + ->setName($formattedName) + ->setOccurrence($occurrence); + $response = $gapicClient->updateOccurrence($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/grafeas.v1.Grafeas/UpdateOccurrence', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $actualValue = $actualRequestObject->getOccurrence(); + $this->assertProtobufEquals($occurrence, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function updateOccurrenceExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->occurrenceName('[PROJECT]', '[OCCURRENCE]'); + $occurrence = new Occurrence(); + $request = (new UpdateOccurrenceRequest()) + ->setName($formattedName) + ->setOccurrence($occurrence); + try { + $gapicClient->updateOccurrence($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function batchCreateNotesAsyncTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new BatchCreateNotesResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $notesValue = new Note(); + $notes = [ + 'notesKey' => $notesValue, + ]; + $request = (new BatchCreateNotesRequest()) + ->setParent($formattedParent) + ->setNotes($notes); + $response = $gapicClient->batchCreateNotesAsync($request)->wait(); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/grafeas.v1.Grafeas/BatchCreateNotes', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualRequestObject->getNotes(); + $this->assertProtobufEquals($notes, $actualValue); + $this->assertTrue($transport->isExhausted()); + } +} diff --git a/Iam/samples/V2/PoliciesClient/create_policy.php b/Iam/samples/V2/PoliciesClient/create_policy.php index 38c9a11e3e5f..01bcb53af48d 100644 --- a/Iam/samples/V2/PoliciesClient/create_policy.php +++ b/Iam/samples/V2/PoliciesClient/create_policy.php @@ -25,7 +25,8 @@ // [START iam_v2_generated_Policies_CreatePolicy_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Iam\V2\PoliciesClient; +use Google\Cloud\Iam\V2\Client\PoliciesClient; +use Google\Cloud\Iam\V2\CreatePolicyRequest; use Google\Cloud\Iam\V2\Policy; use Google\Rpc\Status; @@ -49,13 +50,16 @@ function create_policy_sample(string $parent): void // Create a client. $policiesClient = new PoliciesClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $policy = new Policy(); + $request = (new CreatePolicyRequest()) + ->setParent($parent) + ->setPolicy($policy); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $policiesClient->createPolicy($parent, $policy); + $response = $policiesClient->createPolicy($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/Iam/samples/V2/PoliciesClient/delete_policy.php b/Iam/samples/V2/PoliciesClient/delete_policy.php index 21fb01910d65..292f1315f96a 100644 --- a/Iam/samples/V2/PoliciesClient/delete_policy.php +++ b/Iam/samples/V2/PoliciesClient/delete_policy.php @@ -25,7 +25,8 @@ // [START iam_v2_generated_Policies_DeletePolicy_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Iam\V2\PoliciesClient; +use Google\Cloud\Iam\V2\Client\PoliciesClient; +use Google\Cloud\Iam\V2\DeletePolicyRequest; use Google\Cloud\Iam\V2\Policy; use Google\Rpc\Status; @@ -48,10 +49,14 @@ function delete_policy_sample(string $name): void // Create a client. $policiesClient = new PoliciesClient(); + // Prepare the request message. + $request = (new DeletePolicyRequest()) + ->setName($name); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $policiesClient->deletePolicy($name); + $response = $policiesClient->deletePolicy($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/Iam/samples/V2/PoliciesClient/get_policy.php b/Iam/samples/V2/PoliciesClient/get_policy.php index a5090abf05ce..e4ed2df48231 100644 --- a/Iam/samples/V2/PoliciesClient/get_policy.php +++ b/Iam/samples/V2/PoliciesClient/get_policy.php @@ -24,7 +24,8 @@ // [START iam_v2_generated_Policies_GetPolicy_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Iam\V2\PoliciesClient; +use Google\Cloud\Iam\V2\Client\PoliciesClient; +use Google\Cloud\Iam\V2\GetPolicyRequest; use Google\Cloud\Iam\V2\Policy; /** @@ -46,10 +47,14 @@ function get_policy_sample(string $name): void // Create a client. $policiesClient = new PoliciesClient(); + // Prepare the request message. + $request = (new GetPolicyRequest()) + ->setName($name); + // Call the API and handle any network failures. try { /** @var Policy $response */ - $response = $policiesClient->getPolicy($name); + $response = $policiesClient->getPolicy($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Iam/samples/V2/PoliciesClient/list_policies.php b/Iam/samples/V2/PoliciesClient/list_policies.php index 055884f125c9..2530803b0d38 100644 --- a/Iam/samples/V2/PoliciesClient/list_policies.php +++ b/Iam/samples/V2/PoliciesClient/list_policies.php @@ -25,7 +25,8 @@ // [START iam_v2_generated_Policies_ListPolicies_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\Iam\V2\PoliciesClient; +use Google\Cloud\Iam\V2\Client\PoliciesClient; +use Google\Cloud\Iam\V2\ListPoliciesRequest; use Google\Cloud\Iam\V2\Policy; /** @@ -53,10 +54,14 @@ function list_policies_sample(string $parent): void // Create a client. $policiesClient = new PoliciesClient(); + // Prepare the request message. + $request = (new ListPoliciesRequest()) + ->setParent($parent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $policiesClient->listPolicies($parent); + $response = $policiesClient->listPolicies($request); /** @var Policy $element */ foreach ($response as $element) { diff --git a/Iam/samples/V2/PoliciesClient/update_policy.php b/Iam/samples/V2/PoliciesClient/update_policy.php index 46d0ec3641d9..6f1310d294a3 100644 --- a/Iam/samples/V2/PoliciesClient/update_policy.php +++ b/Iam/samples/V2/PoliciesClient/update_policy.php @@ -25,8 +25,9 @@ // [START iam_v2_generated_Policies_UpdatePolicy_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Iam\V2\PoliciesClient; +use Google\Cloud\Iam\V2\Client\PoliciesClient; use Google\Cloud\Iam\V2\Policy; +use Google\Cloud\Iam\V2\UpdatePolicyRequest; use Google\Rpc\Status; /** @@ -53,13 +54,15 @@ function update_policy_sample(): void // Create a client. $policiesClient = new PoliciesClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $policy = new Policy(); + $request = (new UpdatePolicyRequest()) + ->setPolicy($policy); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $policiesClient->updatePolicy($policy); + $response = $policiesClient->updatePolicy($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/Iam/src/V2/Client/BaseClient/PoliciesBaseClient.php b/Iam/src/V2/Client/BaseClient/PoliciesBaseClient.php new file mode 100644 index 000000000000..a5d6916c406c --- /dev/null +++ b/Iam/src/V2/Client/BaseClient/PoliciesBaseClient.php @@ -0,0 +1,340 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/policies_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/policies_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/policies_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/policies_rest_client_config.php', + ], + ], + ]; + } + + /** + * Return an OperationsClient object with the same endpoint as $this. + * + * @return OperationsClient + */ + public function getOperationsClient() + { + return $this->operationsClient; + } + + /** + * Resume an existing long running operation that was previously started by a long + * running API method. If $methodName is not provided, or does not match a long + * running API method, then the operation can still be resumed, but the + * OperationResponse object will not deserialize the final response. + * + * @param string $operationName The name of the long running operation + * @param string $methodName The name of the method used to start the operation + * + * @return OperationResponse + */ + public function resumeOperation($operationName, $methodName = null) + { + $options = isset($this->descriptors[$methodName]['longRunning']) ? $this->descriptors[$methodName]['longRunning'] : []; + $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); + $operation->reload(); + return $operation; + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'iam.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + $this->operationsClient = $this->createOperationsClient($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Creates a policy. + * + * The async variant is {@see self::createPolicyAsync()} . + * + * @param CreatePolicyRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createPolicy(CreatePolicyRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreatePolicy', $request, $callOptions)->wait(); + } + + /** + * Deletes a policy. This action is permanent. + * + * The async variant is {@see self::deletePolicyAsync()} . + * + * @param DeletePolicyRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function deletePolicy(DeletePolicyRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('DeletePolicy', $request, $callOptions)->wait(); + } + + /** + * Gets a policy. + * + * The async variant is {@see self::getPolicyAsync()} . + * + * @param GetPolicyRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Policy + * + * @throws ApiException Thrown if the API call fails. + */ + public function getPolicy(GetPolicyRequest $request, array $callOptions = []): Policy + { + return $this->startApiCall('GetPolicy', $request, $callOptions)->wait(); + } + + /** + * Retrieves the policies of the specified kind that are attached to a + * resource. + * + * The response lists only policy metadata. In particular, policy rules are + * omitted. + * + * The async variant is {@see self::listPoliciesAsync()} . + * + * @param ListPoliciesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listPolicies(ListPoliciesRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListPolicies', $request, $callOptions); + } + + /** + * Updates the specified policy. + * + * You can update only the rules and the display name for the policy. + * + * To update a policy, you should use a read-modify-write loop: + * + * 1. Use [GetPolicy][google.iam.v2.Policies.GetPolicy] to read the current version of the policy. + * 2. Modify the policy as needed. + * 3. Use `UpdatePolicy` to write the updated policy. + * + * This pattern helps prevent conflicts between concurrent updates. + * + * The async variant is {@see self::updatePolicyAsync()} . + * + * @param UpdatePolicyRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function updatePolicy(UpdatePolicyRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('UpdatePolicy', $request, $callOptions)->wait(); + } +} diff --git a/Iam/src/V2/Client/PoliciesClient.php b/Iam/src/V2/Client/PoliciesClient.php new file mode 100644 index 000000000000..c32e6d26b538 --- /dev/null +++ b/Iam/src/V2/Client/PoliciesClient.php @@ -0,0 +1,40 @@ +setParent($parent) + ->setPolicy($policy) + ->setPolicyId($policyId); + } + /** * Constructor. * diff --git a/Iam/src/V2/DeletePolicyRequest.php b/Iam/src/V2/DeletePolicyRequest.php index 49ab9326f63d..18112de1a189 100644 --- a/Iam/src/V2/DeletePolicyRequest.php +++ b/Iam/src/V2/DeletePolicyRequest.php @@ -38,6 +38,28 @@ class DeletePolicyRequest extends \Google\Protobuf\Internal\Message */ private $etag = ''; + /** + * @param string $name Required. The resource name of the policy to delete. Format: + * `policies/{attachment_point}/denypolicies/{policy_id}` + * + * + * Use the URL-encoded full resource name, which means that the forward-slash + * character, `/`, must be written as `%2F`. For example, + * `policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies/my-policy`. + * + * For organizations and folders, use the numeric ID in the full resource + * name. For projects, you can use the alphanumeric or the numeric ID. + * + * @return \Google\Cloud\Iam\V2\DeletePolicyRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Iam/src/V2/GetPolicyRequest.php b/Iam/src/V2/GetPolicyRequest.php index 9befd910987f..13d790f444c4 100644 --- a/Iam/src/V2/GetPolicyRequest.php +++ b/Iam/src/V2/GetPolicyRequest.php @@ -28,6 +28,28 @@ class GetPolicyRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The resource name of the policy to retrieve. Format: + * `policies/{attachment_point}/denypolicies/{policy_id}` + * + * + * Use the URL-encoded full resource name, which means that the forward-slash + * character, `/`, must be written as `%2F`. For example, + * `policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies/my-policy`. + * + * For organizations and folders, use the numeric ID in the full resource + * name. For projects, you can use the alphanumeric or the numeric ID. + * + * @return \Google\Cloud\Iam\V2\GetPolicyRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Iam/src/V2/ListPoliciesRequest.php b/Iam/src/V2/ListPoliciesRequest.php index b3053be7e375..71630dcad67c 100644 --- a/Iam/src/V2/ListPoliciesRequest.php +++ b/Iam/src/V2/ListPoliciesRequest.php @@ -44,6 +44,30 @@ class ListPoliciesRequest extends \Google\Protobuf\Internal\Message */ private $page_token = ''; + /** + * @param string $parent Required. The resource that the policy is attached to, along with the kind of policy + * to list. Format: + * `policies/{attachment_point}/denypolicies` + * + * + * The attachment point is identified by its URL-encoded full resource name, + * which means that the forward-slash character, `/`, must be written as + * `%2F`. For example, + * `policies/cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project/denypolicies`. + * + * For organizations and folders, use the numeric ID in the full resource + * name. For projects, you can use the alphanumeric or the numeric ID. + * + * @return \Google\Cloud\Iam\V2\ListPoliciesRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/Iam/src/V2/resources/policies_descriptor_config.php b/Iam/src/V2/resources/policies_descriptor_config.php index 96fb84ac0dd9..35249a924525 100644 --- a/Iam/src/V2/resources/policies_descriptor_config.php +++ b/Iam/src/V2/resources/policies_descriptor_config.php @@ -12,6 +12,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'DeletePolicy' => [ 'longRunning' => [ @@ -22,6 +31,15 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'UpdatePolicy' => [ 'longRunning' => [ @@ -32,6 +50,28 @@ 'maxPollDelayMillis' => '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'policy.name', + 'fieldAccessors' => [ + 'getPolicy', + 'getName', + ], + ], + ], + ], + 'GetPolicy' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Iam\V2\Policy', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'ListPolicies' => [ 'pageStreaming' => [ @@ -42,6 +82,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getPolicies', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Iam\V2\ListPoliciesResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], ], ], diff --git a/Iam/tests/Unit/V2/Client/PoliciesClientTest.php b/Iam/tests/Unit/V2/Client/PoliciesClientTest.php new file mode 100644 index 000000000000..7168f54bc3ed --- /dev/null +++ b/Iam/tests/Unit/V2/Client/PoliciesClientTest.php @@ -0,0 +1,702 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return PoliciesClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new PoliciesClient($options); + } + + /** @test */ + public function createPolicyTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createPolicyTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $uid = 'uid115792'; + $kind = 'kind3292052'; + $displayName = 'displayName1615086568'; + $etag = 'etag3123477'; + $managingAuthority = 'managingAuthority617792550'; + $expectedResponse = new Policy(); + $expectedResponse->setName($name); + $expectedResponse->setUid($uid); + $expectedResponse->setKind($kind); + $expectedResponse->setDisplayName($displayName); + $expectedResponse->setEtag($etag); + $expectedResponse->setManagingAuthority($managingAuthority); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createPolicyTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $parent = 'parent-995424086'; + $policy = new Policy(); + $request = (new CreatePolicyRequest()) + ->setParent($parent) + ->setPolicy($policy); + $response = $gapicClient->createPolicy($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.iam.v2.Policies/CreatePolicy', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($parent, $actualValue); + $actualValue = $actualApiRequestObject->getPolicy(); + $this->assertProtobufEquals($policy, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createPolicyTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createPolicyExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createPolicyTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $parent = 'parent-995424086'; + $policy = new Policy(); + $request = (new CreatePolicyRequest()) + ->setParent($parent) + ->setPolicy($policy); + $response = $gapicClient->createPolicy($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createPolicyTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deletePolicyTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deletePolicyTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name2 = 'name2-1052831874'; + $uid = 'uid115792'; + $kind = 'kind3292052'; + $displayName = 'displayName1615086568'; + $etag2 = 'etag2-1293302904'; + $managingAuthority = 'managingAuthority617792550'; + $expectedResponse = new Policy(); + $expectedResponse->setName($name2); + $expectedResponse->setUid($uid); + $expectedResponse->setKind($kind); + $expectedResponse->setDisplayName($displayName); + $expectedResponse->setEtag($etag2); + $expectedResponse->setManagingAuthority($managingAuthority); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/deletePolicyTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $name = 'name3373707'; + $request = (new DeletePolicyRequest()) + ->setName($name); + $response = $gapicClient->deletePolicy($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.iam.v2.Policies/DeletePolicy', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getName(); + $this->assertProtobufEquals($name, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deletePolicyTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deletePolicyExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deletePolicyTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $name = 'name3373707'; + $request = (new DeletePolicyRequest()) + ->setName($name); + $response = $gapicClient->deletePolicy($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deletePolicyTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function getPolicyTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $uid = 'uid115792'; + $kind = 'kind3292052'; + $displayName = 'displayName1615086568'; + $etag = 'etag3123477'; + $managingAuthority = 'managingAuthority617792550'; + $expectedResponse = new Policy(); + $expectedResponse->setName($name2); + $expectedResponse->setUid($uid); + $expectedResponse->setKind($kind); + $expectedResponse->setDisplayName($displayName); + $expectedResponse->setEtag($etag); + $expectedResponse->setManagingAuthority($managingAuthority); + $transport->addResponse($expectedResponse); + // Mock request + $name = 'name3373707'; + $request = (new GetPolicyRequest()) + ->setName($name); + $response = $gapicClient->getPolicy($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.iam.v2.Policies/GetPolicy', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($name, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getPolicyExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $name = 'name3373707'; + $request = (new GetPolicyRequest()) + ->setName($name); + try { + $gapicClient->getPolicy($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listPoliciesTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $policiesElement = new Policy(); + $policies = [ + $policiesElement, + ]; + $expectedResponse = new ListPoliciesResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setPolicies($policies); + $transport->addResponse($expectedResponse); + // Mock request + $parent = 'parent-995424086'; + $request = (new ListPoliciesRequest()) + ->setParent($parent); + $response = $gapicClient->listPolicies($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getPolicies()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.iam.v2.Policies/ListPolicies', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($parent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listPoliciesExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $parent = 'parent-995424086'; + $request = (new ListPoliciesRequest()) + ->setParent($parent); + try { + $gapicClient->listPolicies($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function updatePolicyTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updatePolicyTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $uid = 'uid115792'; + $kind = 'kind3292052'; + $displayName = 'displayName1615086568'; + $etag = 'etag3123477'; + $managingAuthority = 'managingAuthority617792550'; + $expectedResponse = new Policy(); + $expectedResponse->setName($name); + $expectedResponse->setUid($uid); + $expectedResponse->setKind($kind); + $expectedResponse->setDisplayName($displayName); + $expectedResponse->setEtag($etag); + $expectedResponse->setManagingAuthority($managingAuthority); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/updatePolicyTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $policy = new Policy(); + $request = (new UpdatePolicyRequest()) + ->setPolicy($policy); + $response = $gapicClient->updatePolicy($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.iam.v2.Policies/UpdatePolicy', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getPolicy(); + $this->assertProtobufEquals($policy, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updatePolicyTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function updatePolicyExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/updatePolicyTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $policy = new Policy(); + $request = (new UpdatePolicyRequest()) + ->setPolicy($policy); + $response = $gapicClient->updatePolicy($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/updatePolicyTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createPolicyAsyncTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createPolicyTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $uid = 'uid115792'; + $kind = 'kind3292052'; + $displayName = 'displayName1615086568'; + $etag = 'etag3123477'; + $managingAuthority = 'managingAuthority617792550'; + $expectedResponse = new Policy(); + $expectedResponse->setName($name); + $expectedResponse->setUid($uid); + $expectedResponse->setKind($kind); + $expectedResponse->setDisplayName($displayName); + $expectedResponse->setEtag($etag); + $expectedResponse->setManagingAuthority($managingAuthority); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createPolicyTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $parent = 'parent-995424086'; + $policy = new Policy(); + $request = (new CreatePolicyRequest()) + ->setParent($parent) + ->setPolicy($policy); + $response = $gapicClient->createPolicyAsync($request)->wait(); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.iam.v2.Policies/CreatePolicy', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($parent, $actualValue); + $actualValue = $actualApiRequestObject->getPolicy(); + $this->assertProtobufEquals($policy, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createPolicyTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } +} diff --git a/Ids/samples/V1/IDSClient/create_endpoint.php b/Ids/samples/V1/IDSClient/create_endpoint.php index d1a07dd21e8b..5c7df10895dd 100644 --- a/Ids/samples/V1/IDSClient/create_endpoint.php +++ b/Ids/samples/V1/IDSClient/create_endpoint.php @@ -25,9 +25,10 @@ // [START ids_v1_generated_IDS_CreateEndpoint_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; +use Google\Cloud\Ids\V1\Client\IDSClient; +use Google\Cloud\Ids\V1\CreateEndpointRequest; use Google\Cloud\Ids\V1\Endpoint; use Google\Cloud\Ids\V1\Endpoint\Severity; -use Google\Cloud\Ids\V1\IDSClient; use Google\Rpc\Status; /** @@ -54,15 +55,19 @@ function create_endpoint_sample( // Create a client. $iDSClient = new IDSClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $endpoint = (new Endpoint()) ->setNetwork($endpointNetwork) ->setSeverity($endpointSeverity); + $request = (new CreateEndpointRequest()) + ->setParent($formattedParent) + ->setEndpointId($endpointId) + ->setEndpoint($endpoint); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $iDSClient->createEndpoint($formattedParent, $endpointId, $endpoint); + $response = $iDSClient->createEndpoint($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/Ids/samples/V1/IDSClient/delete_endpoint.php b/Ids/samples/V1/IDSClient/delete_endpoint.php index 1187b0c7de44..9e72367ad28d 100644 --- a/Ids/samples/V1/IDSClient/delete_endpoint.php +++ b/Ids/samples/V1/IDSClient/delete_endpoint.php @@ -25,7 +25,8 @@ // [START ids_v1_generated_IDS_DeleteEndpoint_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; -use Google\Cloud\Ids\V1\IDSClient; +use Google\Cloud\Ids\V1\Client\IDSClient; +use Google\Cloud\Ids\V1\DeleteEndpointRequest; use Google\Rpc\Status; /** @@ -39,10 +40,14 @@ function delete_endpoint_sample(string $formattedName): void // Create a client. $iDSClient = new IDSClient(); + // Prepare the request message. + $request = (new DeleteEndpointRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $iDSClient->deleteEndpoint($formattedName); + $response = $iDSClient->deleteEndpoint($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/Ids/samples/V1/IDSClient/get_endpoint.php b/Ids/samples/V1/IDSClient/get_endpoint.php index 44492e4ee4a9..69e7e29e1089 100644 --- a/Ids/samples/V1/IDSClient/get_endpoint.php +++ b/Ids/samples/V1/IDSClient/get_endpoint.php @@ -24,8 +24,9 @@ // [START ids_v1_generated_IDS_GetEndpoint_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Ids\V1\Client\IDSClient; use Google\Cloud\Ids\V1\Endpoint; -use Google\Cloud\Ids\V1\IDSClient; +use Google\Cloud\Ids\V1\GetEndpointRequest; /** * Gets details of a single Endpoint. @@ -39,10 +40,14 @@ function get_endpoint_sample(string $formattedName): void // Create a client. $iDSClient = new IDSClient(); + // Prepare the request message. + $request = (new GetEndpointRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var Endpoint $response */ - $response = $iDSClient->getEndpoint($formattedName); + $response = $iDSClient->getEndpoint($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Ids/samples/V1/IDSClient/list_endpoints.php b/Ids/samples/V1/IDSClient/list_endpoints.php index 775120615489..539b8879bbce 100644 --- a/Ids/samples/V1/IDSClient/list_endpoints.php +++ b/Ids/samples/V1/IDSClient/list_endpoints.php @@ -25,8 +25,9 @@ // [START ids_v1_generated_IDS_ListEndpoints_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; +use Google\Cloud\Ids\V1\Client\IDSClient; use Google\Cloud\Ids\V1\Endpoint; -use Google\Cloud\Ids\V1\IDSClient; +use Google\Cloud\Ids\V1\ListEndpointsRequest; /** * Lists Endpoints in a given project and location. @@ -39,10 +40,14 @@ function list_endpoints_sample(string $formattedParent): void // Create a client. $iDSClient = new IDSClient(); + // Prepare the request message. + $request = (new ListEndpointsRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $iDSClient->listEndpoints($formattedParent); + $response = $iDSClient->listEndpoints($request); /** @var Endpoint $element */ foreach ($response as $element) { diff --git a/Ids/src/V1/Client/BaseClient/IDSBaseClient.php b/Ids/src/V1/Client/BaseClient/IDSBaseClient.php new file mode 100644 index 000000000000..77bc41b4e216 --- /dev/null +++ b/Ids/src/V1/Client/BaseClient/IDSBaseClient.php @@ -0,0 +1,368 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/ids_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/ids_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/ids_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/ids_rest_client_config.php', + ], + ], + ]; + } + + /** + * Return an OperationsClient object with the same endpoint as $this. + * + * @return OperationsClient + */ + public function getOperationsClient() + { + return $this->operationsClient; + } + + /** + * Resume an existing long running operation that was previously started by a long + * running API method. If $methodName is not provided, or does not match a long + * running API method, then the operation can still be resumed, but the + * OperationResponse object will not deserialize the final response. + * + * @param string $operationName The name of the long running operation + * @param string $methodName The name of the method used to start the operation + * + * @return OperationResponse + */ + public function resumeOperation($operationName, $methodName = null) + { + $options = isset($this->descriptors[$methodName]['longRunning']) ? $this->descriptors[$methodName]['longRunning'] : []; + $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); + $operation->reload(); + return $operation; + } + + /** + * Formats a string containing the fully-qualified path to represent a endpoint + * resource. + * + * @param string $project + * @param string $location + * @param string $endpoint + * + * @return string The formatted endpoint resource. + */ + public static function endpointName(string $project, string $location, string $endpoint): string + { + return self::getPathTemplate('endpoint')->render([ + 'project' => $project, + 'location' => $location, + 'endpoint' => $endpoint, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a location + * resource. + * + * @param string $project + * @param string $location + * + * @return string The formatted location resource. + */ + public static function locationName(string $project, string $location): string + { + return self::getPathTemplate('location')->render([ + 'project' => $project, + 'location' => $location, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - endpoint: projects/{project}/locations/{location}/endpoints/{endpoint} + * - location: projects/{project}/locations/{location} + * + * The optional $template argument can be supplied to specify a particular pattern, + * and must match one of the templates listed above. If no $template argument is + * provided, or if the $template argument does not match one of the templates + * listed, then parseName will check each of the supported templates, and return + * the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + */ + public static function parseName(string $formattedName, string $template = null): array + { + return self::parseFormattedName($formattedName, $template); + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'ids.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + $this->operationsClient = $this->createOperationsClient($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Creates a new Endpoint in a given project and location. + * + * The async variant is {@see self::createEndpointAsync()} . + * + * @param CreateEndpointRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function createEndpoint(CreateEndpointRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('CreateEndpoint', $request, $callOptions)->wait(); + } + + /** + * Deletes a single Endpoint. + * + * The async variant is {@see self::deleteEndpointAsync()} . + * + * @param DeleteEndpointRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function deleteEndpoint(DeleteEndpointRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('DeleteEndpoint', $request, $callOptions)->wait(); + } + + /** + * Gets details of a single Endpoint. + * + * The async variant is {@see self::getEndpointAsync()} . + * + * @param GetEndpointRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Endpoint + * + * @throws ApiException Thrown if the API call fails. + */ + public function getEndpoint(GetEndpointRequest $request, array $callOptions = []): Endpoint + { + return $this->startApiCall('GetEndpoint', $request, $callOptions)->wait(); + } + + /** + * Lists Endpoints in a given project and location. + * + * The async variant is {@see self::listEndpointsAsync()} . + * + * @param ListEndpointsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listEndpoints(ListEndpointsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListEndpoints', $request, $callOptions); + } +} diff --git a/Ids/src/V1/Client/IDSClient.php b/Ids/src/V1/Client/IDSClient.php new file mode 100644 index 000000000000..3d4df2debdaf --- /dev/null +++ b/Ids/src/V1/Client/IDSClient.php @@ -0,0 +1,40 @@ +setParent($parent) + ->setEndpoint($endpoint) + ->setEndpointId($endpointId); + } + /** * Constructor. * diff --git a/Ids/src/V1/DeleteEndpointRequest.php b/Ids/src/V1/DeleteEndpointRequest.php index df52678fcaa8..b2e4ea6e9be8 100644 --- a/Ids/src/V1/DeleteEndpointRequest.php +++ b/Ids/src/V1/DeleteEndpointRequest.php @@ -36,6 +36,20 @@ class DeleteEndpointRequest extends \Google\Protobuf\Internal\Message */ private $request_id = ''; + /** + * @param string $name Required. The name of the endpoint to delete. Please see + * {@see IDSClient::endpointName()} for help formatting this field. + * + * @return \Google\Cloud\Ids\V1\DeleteEndpointRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Ids/src/V1/GetEndpointRequest.php b/Ids/src/V1/GetEndpointRequest.php index 0d10fc2518e1..95095044e893 100644 --- a/Ids/src/V1/GetEndpointRequest.php +++ b/Ids/src/V1/GetEndpointRequest.php @@ -21,6 +21,21 @@ class GetEndpointRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The name of the endpoint to retrieve. + * Format: `projects/{project}/locations/{location}/endpoints/{endpoint}` + * Please see {@see IDSClient::endpointName()} for help formatting this field. + * + * @return \Google\Cloud\Ids\V1\GetEndpointRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/Ids/src/V1/ListEndpointsRequest.php b/Ids/src/V1/ListEndpointsRequest.php index 22e4bc3c0b2b..577524d5a60e 100644 --- a/Ids/src/V1/ListEndpointsRequest.php +++ b/Ids/src/V1/ListEndpointsRequest.php @@ -50,6 +50,20 @@ class ListEndpointsRequest extends \Google\Protobuf\Internal\Message */ private $order_by = ''; + /** + * @param string $parent Required. The parent, which owns this collection of endpoints. Please see + * {@see IDSClient::locationName()} for help formatting this field. + * + * @return \Google\Cloud\Ids\V1\ListEndpointsRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/Ids/src/V1/resources/ids_descriptor_config.php b/Ids/src/V1/resources/ids_descriptor_config.php index ba73e09485b5..d5d1d3ca9a98 100644 --- a/Ids/src/V1/resources/ids_descriptor_config.php +++ b/Ids/src/V1/resources/ids_descriptor_config.php @@ -12,6 +12,15 @@ 'maxPollDelayMillis' => '45000', 'totalPollTimeoutMillis' => '3600000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'DeleteEndpoint' => [ 'longRunning' => [ @@ -22,6 +31,27 @@ 'maxPollDelayMillis' => '45000', 'totalPollTimeoutMillis' => '3600000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetEndpoint' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Ids\V1\Endpoint', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], ], 'ListEndpoints' => [ 'pageStreaming' => [ @@ -32,6 +62,20 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getEndpoints', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Ids\V1\ListEndpointsResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'templateMap' => [ + 'endpoint' => 'projects/{project}/locations/{location}/endpoints/{endpoint}', + 'location' => 'projects/{project}/locations/{location}', ], ], ], diff --git a/Ids/tests/Unit/V1/Client/IDSClientTest.php b/Ids/tests/Unit/V1/Client/IDSClientTest.php new file mode 100644 index 000000000000..15d1d4cd2a76 --- /dev/null +++ b/Ids/tests/Unit/V1/Client/IDSClientTest.php @@ -0,0 +1,580 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return IDSClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new IDSClient($options); + } + + /** @test */ + public function createEndpointTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createEndpointTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $network = 'network1843485230'; + $endpointForwardingRule = 'endpointForwardingRule-1878786988'; + $endpointIp = 'endpointIp-1135808495'; + $description = 'description-1724546052'; + $trafficLogs = false; + $expectedResponse = new Endpoint(); + $expectedResponse->setName($name); + $expectedResponse->setNetwork($network); + $expectedResponse->setEndpointForwardingRule($endpointForwardingRule); + $expectedResponse->setEndpointIp($endpointIp); + $expectedResponse->setDescription($description); + $expectedResponse->setTrafficLogs($trafficLogs); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createEndpointTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $endpointId = 'endpointId-1135808507'; + $endpoint = new Endpoint(); + $endpointNetwork = 'endpointNetwork1670861529'; + $endpoint->setNetwork($endpointNetwork); + $endpointSeverity = Severity::SEVERITY_UNSPECIFIED; + $endpoint->setSeverity($endpointSeverity); + $request = (new CreateEndpointRequest()) + ->setParent($formattedParent) + ->setEndpointId($endpointId) + ->setEndpoint($endpoint); + $response = $gapicClient->createEndpoint($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.ids.v1.IDS/CreateEndpoint', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getEndpointId(); + $this->assertProtobufEquals($endpointId, $actualValue); + $actualValue = $actualApiRequestObject->getEndpoint(); + $this->assertProtobufEquals($endpoint, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createEndpointTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function createEndpointExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createEndpointTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $endpointId = 'endpointId-1135808507'; + $endpoint = new Endpoint(); + $endpointNetwork = 'endpointNetwork1670861529'; + $endpoint->setNetwork($endpointNetwork); + $endpointSeverity = Severity::SEVERITY_UNSPECIFIED; + $endpoint->setSeverity($endpointSeverity); + $request = (new CreateEndpointRequest()) + ->setParent($formattedParent) + ->setEndpointId($endpointId) + ->setEndpoint($endpoint); + $response = $gapicClient->createEndpoint($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createEndpointTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteEndpointTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteEndpointTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new GPBEmpty(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/deleteEndpointTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedName = $gapicClient->endpointName('[PROJECT]', '[LOCATION]', '[ENDPOINT]'); + $request = (new DeleteEndpointRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteEndpoint($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.ids.v1.IDS/DeleteEndpoint', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteEndpointTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function deleteEndpointExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/deleteEndpointTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->endpointName('[PROJECT]', '[LOCATION]', '[ENDPOINT]'); + $request = (new DeleteEndpointRequest()) + ->setName($formattedName); + $response = $gapicClient->deleteEndpoint($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/deleteEndpointTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function getEndpointTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $network = 'network1843485230'; + $endpointForwardingRule = 'endpointForwardingRule-1878786988'; + $endpointIp = 'endpointIp-1135808495'; + $description = 'description-1724546052'; + $trafficLogs = false; + $expectedResponse = new Endpoint(); + $expectedResponse->setName($name2); + $expectedResponse->setNetwork($network); + $expectedResponse->setEndpointForwardingRule($endpointForwardingRule); + $expectedResponse->setEndpointIp($endpointIp); + $expectedResponse->setDescription($description); + $expectedResponse->setTrafficLogs($trafficLogs); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->endpointName('[PROJECT]', '[LOCATION]', '[ENDPOINT]'); + $request = (new GetEndpointRequest()) + ->setName($formattedName); + $response = $gapicClient->getEndpoint($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.ids.v1.IDS/GetEndpoint', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getEndpointExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->endpointName('[PROJECT]', '[LOCATION]', '[ENDPOINT]'); + $request = (new GetEndpointRequest()) + ->setName($formattedName); + try { + $gapicClient->getEndpoint($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listEndpointsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $endpointsElement = new Endpoint(); + $endpoints = [ + $endpointsElement, + ]; + $expectedResponse = new ListEndpointsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setEndpoints($endpoints); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListEndpointsRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listEndpoints($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getEndpoints()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.ids.v1.IDS/ListEndpoints', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listEndpointsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $request = (new ListEndpointsRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listEndpoints($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createEndpointAsyncTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/createEndpointTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $name = 'name3373707'; + $network = 'network1843485230'; + $endpointForwardingRule = 'endpointForwardingRule-1878786988'; + $endpointIp = 'endpointIp-1135808495'; + $description = 'description-1724546052'; + $trafficLogs = false; + $expectedResponse = new Endpoint(); + $expectedResponse->setName($name); + $expectedResponse->setNetwork($network); + $expectedResponse->setEndpointForwardingRule($endpointForwardingRule); + $expectedResponse->setEndpointIp($endpointIp); + $expectedResponse->setDescription($description); + $expectedResponse->setTrafficLogs($trafficLogs); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/createEndpointTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $formattedParent = $gapicClient->locationName('[PROJECT]', '[LOCATION]'); + $endpointId = 'endpointId-1135808507'; + $endpoint = new Endpoint(); + $endpointNetwork = 'endpointNetwork1670861529'; + $endpoint->setNetwork($endpointNetwork); + $endpointSeverity = Severity::SEVERITY_UNSPECIFIED; + $endpoint->setSeverity($endpointSeverity); + $request = (new CreateEndpointRequest()) + ->setParent($formattedParent) + ->setEndpointId($endpointId) + ->setEndpoint($endpoint); + $response = $gapicClient->createEndpointAsync($request)->wait(); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.ids.v1.IDS/CreateEndpoint', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualApiRequestObject->getEndpointId(); + $this->assertProtobufEquals($endpointId, $actualValue); + $actualValue = $actualApiRequestObject->getEndpoint(); + $this->assertProtobufEquals($endpoint, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/createEndpointTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } +} diff --git a/KmsInventory/samples/V1/KeyDashboardServiceClient/list_crypto_keys.php b/KmsInventory/samples/V1/KeyDashboardServiceClient/list_crypto_keys.php index 5364bcf4f42f..5a132d445883 100644 --- a/KmsInventory/samples/V1/KeyDashboardServiceClient/list_crypto_keys.php +++ b/KmsInventory/samples/V1/KeyDashboardServiceClient/list_crypto_keys.php @@ -25,7 +25,8 @@ // [START kmsinventory_v1_generated_KeyDashboardService_ListCryptoKeys_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\Kms\Inventory\V1\KeyDashboardServiceClient; +use Google\Cloud\Kms\Inventory\V1\Client\KeyDashboardServiceClient; +use Google\Cloud\Kms\Inventory\V1\ListCryptoKeysRequest; use Google\Cloud\Kms\V1\CryptoKey; /** @@ -42,10 +43,14 @@ function list_crypto_keys_sample(string $formattedParent): void // Create a client. $keyDashboardServiceClient = new KeyDashboardServiceClient(); + // Prepare the request message. + $request = (new ListCryptoKeysRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $keyDashboardServiceClient->listCryptoKeys($formattedParent); + $response = $keyDashboardServiceClient->listCryptoKeys($request); /** @var CryptoKey $element */ foreach ($response as $element) { diff --git a/KmsInventory/samples/V1/KeyTrackingServiceClient/get_protected_resources_summary.php b/KmsInventory/samples/V1/KeyTrackingServiceClient/get_protected_resources_summary.php index 3c3249fe16a2..5e75b04511e6 100644 --- a/KmsInventory/samples/V1/KeyTrackingServiceClient/get_protected_resources_summary.php +++ b/KmsInventory/samples/V1/KeyTrackingServiceClient/get_protected_resources_summary.php @@ -24,7 +24,8 @@ // [START kmsinventory_v1_generated_KeyTrackingService_GetProtectedResourcesSummary_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Kms\Inventory\V1\KeyTrackingServiceClient; +use Google\Cloud\Kms\Inventory\V1\Client\KeyTrackingServiceClient; +use Google\Cloud\Kms\Inventory\V1\GetProtectedResourcesSummaryRequest; use Google\Cloud\Kms\Inventory\V1\ProtectedResourcesSummary; /** @@ -43,10 +44,14 @@ function get_protected_resources_summary_sample(string $formattedName): void // Create a client. $keyTrackingServiceClient = new KeyTrackingServiceClient(); + // Prepare the request message. + $request = (new GetProtectedResourcesSummaryRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var ProtectedResourcesSummary $response */ - $response = $keyTrackingServiceClient->getProtectedResourcesSummary($formattedName); + $response = $keyTrackingServiceClient->getProtectedResourcesSummary($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/KmsInventory/samples/V1/KeyTrackingServiceClient/search_protected_resources.php b/KmsInventory/samples/V1/KeyTrackingServiceClient/search_protected_resources.php index 218ff3cedb6f..66730ec42a67 100644 --- a/KmsInventory/samples/V1/KeyTrackingServiceClient/search_protected_resources.php +++ b/KmsInventory/samples/V1/KeyTrackingServiceClient/search_protected_resources.php @@ -25,8 +25,9 @@ // [START kmsinventory_v1_generated_KeyTrackingService_SearchProtectedResources_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\Kms\Inventory\V1\KeyTrackingServiceClient; +use Google\Cloud\Kms\Inventory\V1\Client\KeyTrackingServiceClient; use Google\Cloud\Kms\Inventory\V1\ProtectedResource; +use Google\Cloud\Kms\Inventory\V1\SearchProtectedResourcesRequest; /** * Returns metadata about the resources protected by the given Cloud KMS @@ -43,10 +44,15 @@ function search_protected_resources_sample(string $formattedScope, string $crypt // Create a client. $keyTrackingServiceClient = new KeyTrackingServiceClient(); + // Prepare the request message. + $request = (new SearchProtectedResourcesRequest()) + ->setScope($formattedScope) + ->setCryptoKey($cryptoKey); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $keyTrackingServiceClient->searchProtectedResources($formattedScope, $cryptoKey); + $response = $keyTrackingServiceClient->searchProtectedResources($request); /** @var ProtectedResource $element */ foreach ($response as $element) { diff --git a/KmsInventory/src/V1/Client/BaseClient/KeyDashboardServiceBaseClient.php b/KmsInventory/src/V1/Client/BaseClient/KeyDashboardServiceBaseClient.php new file mode 100644 index 000000000000..dca227419416 --- /dev/null +++ b/KmsInventory/src/V1/Client/BaseClient/KeyDashboardServiceBaseClient.php @@ -0,0 +1,234 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/key_dashboard_service_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/key_dashboard_service_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/key_dashboard_service_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/key_dashboard_service_rest_client_config.php', + ], + ], + ]; + } + + /** + * Formats a string containing the fully-qualified path to represent a project + * resource. + * + * @param string $project + * + * @return string The formatted project resource. + */ + public static function projectName(string $project): string + { + return self::getPathTemplate('project')->render([ + 'project' => $project, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - project: projects/{project} + * + * The optional $template argument can be supplied to specify a particular pattern, + * and must match one of the templates listed above. If no $template argument is + * provided, or if the $template argument does not match one of the templates + * listed, then parseName will check each of the supported templates, and return + * the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + */ + public static function parseName(string $formattedName, string $template = null): array + { + return self::parseFormattedName($formattedName, $template); + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'kmsinventory.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Returns cryptographic keys managed by Cloud KMS in a given Cloud project. + * Note that this data is sourced from snapshots, meaning it may not + * completely reflect the actual state of key metadata at call time. + * + * The async variant is {@see self::listCryptoKeysAsync()} . + * + * @param ListCryptoKeysRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listCryptoKeys(ListCryptoKeysRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListCryptoKeys', $request, $callOptions); + } +} diff --git a/KmsInventory/src/V1/Client/BaseClient/KeyTrackingServiceBaseClient.php b/KmsInventory/src/V1/Client/BaseClient/KeyTrackingServiceBaseClient.php new file mode 100644 index 000000000000..639241f51a3f --- /dev/null +++ b/KmsInventory/src/V1/Client/BaseClient/KeyTrackingServiceBaseClient.php @@ -0,0 +1,334 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/key_tracking_service_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/key_tracking_service_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/key_tracking_service_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/key_tracking_service_rest_client_config.php', + ], + ], + ]; + } + + /** + * Formats a string containing the fully-qualified path to represent a organization + * resource. + * + * @param string $organization + * + * @return string The formatted organization resource. + */ + public static function organizationName(string $organization): string + { + return self::getPathTemplate('organization')->render([ + 'organization' => $organization, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * project_location_key_ring_crypto_key_crypto_key_version_protectedResourcesSummary + * resource. + * + * @param string $project + * @param string $location + * @param string $keyRing + * @param string $cryptoKey + * @param string $cryptoKeyVersion + * + * @return string The formatted project_location_key_ring_crypto_key_crypto_key_version_protectedResourcesSummary resource. + */ + public static function projectLocationKeyRingCryptoKeyCryptoKeyVersionProtectedResourcesSummaryName(string $project, string $location, string $keyRing, string $cryptoKey, string $cryptoKeyVersion): string + { + return self::getPathTemplate('projectLocationKeyRingCryptoKeyCryptoKeyVersionProtectedResourcesSummary')->render([ + 'project' => $project, + 'location' => $location, + 'key_ring' => $keyRing, + 'crypto_key' => $cryptoKey, + 'crypto_key_version' => $cryptoKeyVersion, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * project_location_key_ring_crypto_key_protectedResourcesSummary resource. + * + * @param string $project + * @param string $location + * @param string $keyRing + * @param string $cryptoKey + * + * @return string The formatted project_location_key_ring_crypto_key_protectedResourcesSummary resource. + */ + public static function projectLocationKeyRingCryptoKeyProtectedResourcesSummaryName(string $project, string $location, string $keyRing, string $cryptoKey): string + { + return self::getPathTemplate('projectLocationKeyRingCryptoKeyProtectedResourcesSummary')->render([ + 'project' => $project, + 'location' => $location, + 'key_ring' => $keyRing, + 'crypto_key' => $cryptoKey, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * protected_resources_summary resource. + * + * @param string $project + * @param string $location + * @param string $keyRing + * @param string $cryptoKey + * + * @return string The formatted protected_resources_summary resource. + */ + public static function protectedResourcesSummaryName(string $project, string $location, string $keyRing, string $cryptoKey): string + { + return self::getPathTemplate('protectedResourcesSummary')->render([ + 'project' => $project, + 'location' => $location, + 'key_ring' => $keyRing, + 'crypto_key' => $cryptoKey, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - organization: organizations/{organization} + * - projectLocationKeyRingCryptoKeyCryptoKeyVersionProtectedResourcesSummary: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}/protectedResourcesSummary + * - projectLocationKeyRingCryptoKeyProtectedResourcesSummary: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/protectedResourcesSummary + * - protectedResourcesSummary: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/protectedResourcesSummary + * + * The optional $template argument can be supplied to specify a particular pattern, + * and must match one of the templates listed above. If no $template argument is + * provided, or if the $template argument does not match one of the templates + * listed, then parseName will check each of the supported templates, and return + * the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + */ + public static function parseName(string $formattedName, string $template = null): array + { + return self::parseFormattedName($formattedName, $template); + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'kmsinventory.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Returns aggregate information about the resources protected by the given + * Cloud KMS [CryptoKey][google.cloud.kms.v1.CryptoKey]. Only resources within + * the same Cloud organization as the key will be returned. The project that + * holds the key must be part of an organization in order for this call to + * succeed. + * + * The async variant is {@see self::getProtectedResourcesSummaryAsync()} . + * + * @param GetProtectedResourcesSummaryRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return ProtectedResourcesSummary + * + * @throws ApiException Thrown if the API call fails. + */ + public function getProtectedResourcesSummary(GetProtectedResourcesSummaryRequest $request, array $callOptions = []): ProtectedResourcesSummary + { + return $this->startApiCall('GetProtectedResourcesSummary', $request, $callOptions)->wait(); + } + + /** + * Returns metadata about the resources protected by the given Cloud KMS + * [CryptoKey][google.cloud.kms.v1.CryptoKey] in the given Cloud organization. + * + * The async variant is {@see self::searchProtectedResourcesAsync()} . + * + * @param SearchProtectedResourcesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function searchProtectedResources(SearchProtectedResourcesRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('SearchProtectedResources', $request, $callOptions); + } +} diff --git a/KmsInventory/src/V1/Client/KeyDashboardServiceClient.php b/KmsInventory/src/V1/Client/KeyDashboardServiceClient.php new file mode 100644 index 000000000000..c13e04007ebd --- /dev/null +++ b/KmsInventory/src/V1/Client/KeyDashboardServiceClient.php @@ -0,0 +1,40 @@ +setName($name); + } + /** * Constructor. * diff --git a/KmsInventory/src/V1/ListCryptoKeysRequest.php b/KmsInventory/src/V1/ListCryptoKeysRequest.php index 26f650a136de..005fec032720 100644 --- a/KmsInventory/src/V1/ListCryptoKeysRequest.php +++ b/KmsInventory/src/V1/ListCryptoKeysRequest.php @@ -39,6 +39,21 @@ class ListCryptoKeysRequest extends \Google\Protobuf\Internal\Message */ protected $page_token = ''; + /** + * @param string $parent Required. The Google Cloud project for which to retrieve key metadata, in + * the format `projects/*` + * Please see {@see KeyDashboardServiceClient::projectName()} for help formatting this field. + * + * @return \Google\Cloud\Kms\Inventory\V1\ListCryptoKeysRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/KmsInventory/src/V1/SearchProtectedResourcesRequest.php b/KmsInventory/src/V1/SearchProtectedResourcesRequest.php index a1551c276e98..9ef9326de649 100644 --- a/KmsInventory/src/V1/SearchProtectedResourcesRequest.php +++ b/KmsInventory/src/V1/SearchProtectedResourcesRequest.php @@ -51,6 +51,24 @@ class SearchProtectedResourcesRequest extends \Google\Protobuf\Internal\Message */ protected $page_token = ''; + /** + * @param string $scope Required. Resource name of the organization. + * Example: organizations/123 + * Please see {@see KeyTrackingServiceClient::organizationName()} for help formatting this field. + * @param string $cryptoKey Required. The resource name of the + * [CryptoKey][google.cloud.kms.v1.CryptoKey]. + * + * @return \Google\Cloud\Kms\Inventory\V1\SearchProtectedResourcesRequest + * + * @experimental + */ + public static function build(string $scope, string $cryptoKey): self + { + return (new self()) + ->setScope($scope) + ->setCryptoKey($cryptoKey); + } + /** * Constructor. * diff --git a/KmsInventory/src/V1/resources/key_dashboard_service_descriptor_config.php b/KmsInventory/src/V1/resources/key_dashboard_service_descriptor_config.php index bd54ec77467c..ffe421a44094 100644 --- a/KmsInventory/src/V1/resources/key_dashboard_service_descriptor_config.php +++ b/KmsInventory/src/V1/resources/key_dashboard_service_descriptor_config.php @@ -12,6 +12,19 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getCryptoKeys', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Kms\Inventory\V1\ListCryptoKeysResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'templateMap' => [ + 'project' => 'projects/{project}', ], ], ], diff --git a/KmsInventory/src/V1/resources/key_tracking_service_descriptor_config.php b/KmsInventory/src/V1/resources/key_tracking_service_descriptor_config.php index da48dd3490e5..307849943e35 100644 --- a/KmsInventory/src/V1/resources/key_tracking_service_descriptor_config.php +++ b/KmsInventory/src/V1/resources/key_tracking_service_descriptor_config.php @@ -3,6 +3,18 @@ return [ 'interfaces' => [ 'google.cloud.kms.inventory.v1.KeyTrackingService' => [ + 'GetProtectedResourcesSummary' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Kms\Inventory\V1\ProtectedResourcesSummary', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], 'SearchProtectedResources' => [ 'pageStreaming' => [ 'requestPageTokenGetMethod' => 'getPageToken', @@ -12,6 +24,22 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getProtectedResources', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Kms\Inventory\V1\SearchProtectedResourcesResponse', + 'headerParams' => [ + [ + 'keyName' => 'scope', + 'fieldAccessors' => [ + 'getScope', + ], + ], + ], + ], + 'templateMap' => [ + 'organization' => 'organizations/{organization}', + 'projectLocationKeyRingCryptoKeyCryptoKeyVersionProtectedResourcesSummary' => 'projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}/protectedResourcesSummary', + 'projectLocationKeyRingCryptoKeyProtectedResourcesSummary' => 'projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/protectedResourcesSummary', + 'protectedResourcesSummary' => 'projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/protectedResourcesSummary', ], ], ], diff --git a/KmsInventory/tests/Unit/V1/Client/KeyDashboardServiceClientTest.php b/KmsInventory/tests/Unit/V1/Client/KeyDashboardServiceClientTest.php new file mode 100644 index 000000000000..c1b4c2ffd2f4 --- /dev/null +++ b/KmsInventory/tests/Unit/V1/Client/KeyDashboardServiceClientTest.php @@ -0,0 +1,172 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return KeyDashboardServiceClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new KeyDashboardServiceClient($options); + } + + /** @test */ + public function listCryptoKeysTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $cryptoKeysElement = new CryptoKey(); + $cryptoKeys = [ + $cryptoKeysElement, + ]; + $expectedResponse = new ListCryptoKeysResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setCryptoKeys($cryptoKeys); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $request = (new ListCryptoKeysRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listCryptoKeys($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getCryptoKeys()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.kms.inventory.v1.KeyDashboardService/ListCryptoKeys', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listCryptoKeysExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $request = (new ListCryptoKeysRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listCryptoKeys($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listCryptoKeysAsyncTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $cryptoKeysElement = new CryptoKey(); + $cryptoKeys = [ + $cryptoKeysElement, + ]; + $expectedResponse = new ListCryptoKeysResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setCryptoKeys($cryptoKeys); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $request = (new ListCryptoKeysRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listCryptoKeysAsync($request)->wait(); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getCryptoKeys()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.kms.inventory.v1.KeyDashboardService/ListCryptoKeys', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } +} diff --git a/KmsInventory/tests/Unit/V1/Client/KeyTrackingServiceClientTest.php b/KmsInventory/tests/Unit/V1/Client/KeyTrackingServiceClientTest.php new file mode 100644 index 000000000000..56eaa775fc50 --- /dev/null +++ b/KmsInventory/tests/Unit/V1/Client/KeyTrackingServiceClientTest.php @@ -0,0 +1,244 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return KeyTrackingServiceClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new KeyTrackingServiceClient($options); + } + + /** @test */ + public function getProtectedResourcesSummaryTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $resourceCount = 287552926; + $projectCount = 953448343; + $expectedResponse = new ProtectedResourcesSummary(); + $expectedResponse->setName($name2); + $expectedResponse->setResourceCount($resourceCount); + $expectedResponse->setProjectCount($projectCount); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->protectedResourcesSummaryName('[PROJECT]', '[LOCATION]', '[KEY_RING]', '[CRYPTO_KEY]'); + $request = (new GetProtectedResourcesSummaryRequest()) + ->setName($formattedName); + $response = $gapicClient->getProtectedResourcesSummary($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.kms.inventory.v1.KeyTrackingService/GetProtectedResourcesSummary', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getProtectedResourcesSummaryExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->protectedResourcesSummaryName('[PROJECT]', '[LOCATION]', '[KEY_RING]', '[CRYPTO_KEY]'); + $request = (new GetProtectedResourcesSummaryRequest()) + ->setName($formattedName); + try { + $gapicClient->getProtectedResourcesSummary($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function searchProtectedResourcesTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $protectedResourcesElement = new ProtectedResource(); + $protectedResources = [ + $protectedResourcesElement, + ]; + $expectedResponse = new SearchProtectedResourcesResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setProtectedResources($protectedResources); + $transport->addResponse($expectedResponse); + // Mock request + $formattedScope = $gapicClient->organizationName('[ORGANIZATION]'); + $cryptoKey = 'cryptoKey-1992067615'; + $request = (new SearchProtectedResourcesRequest()) + ->setScope($formattedScope) + ->setCryptoKey($cryptoKey); + $response = $gapicClient->searchProtectedResources($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getProtectedResources()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.kms.inventory.v1.KeyTrackingService/SearchProtectedResources', $actualFuncCall); + $actualValue = $actualRequestObject->getScope(); + $this->assertProtobufEquals($formattedScope, $actualValue); + $actualValue = $actualRequestObject->getCryptoKey(); + $this->assertProtobufEquals($cryptoKey, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function searchProtectedResourcesExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedScope = $gapicClient->organizationName('[ORGANIZATION]'); + $cryptoKey = 'cryptoKey-1992067615'; + $request = (new SearchProtectedResourcesRequest()) + ->setScope($formattedScope) + ->setCryptoKey($cryptoKey); + try { + $gapicClient->searchProtectedResources($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getProtectedResourcesSummaryAsyncTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $resourceCount = 287552926; + $projectCount = 953448343; + $expectedResponse = new ProtectedResourcesSummary(); + $expectedResponse->setName($name2); + $expectedResponse->setResourceCount($resourceCount); + $expectedResponse->setProjectCount($projectCount); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->protectedResourcesSummaryName('[PROJECT]', '[LOCATION]', '[KEY_RING]', '[CRYPTO_KEY]'); + $request = (new GetProtectedResourcesSummaryRequest()) + ->setName($formattedName); + $response = $gapicClient->getProtectedResourcesSummaryAsync($request)->wait(); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.kms.inventory.v1.KeyTrackingService/GetProtectedResourcesSummary', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } +} diff --git a/Language/samples/V1/LanguageServiceClient/analyze_entities.php b/Language/samples/V1/LanguageServiceClient/analyze_entities.php index b1aab53f803e..adad59cffe84 100644 --- a/Language/samples/V1/LanguageServiceClient/analyze_entities.php +++ b/Language/samples/V1/LanguageServiceClient/analyze_entities.php @@ -24,9 +24,10 @@ // [START language_v1_generated_LanguageService_AnalyzeEntities_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Language\V1\AnalyzeEntitiesRequest; use Google\Cloud\Language\V1\AnalyzeEntitiesResponse; +use Google\Cloud\Language\V1\Client\LanguageServiceClient; use Google\Cloud\Language\V1\Document; -use Google\Cloud\Language\V1\LanguageServiceClient; /** * Finds named entities (currently proper names and common nouns) in the text @@ -44,13 +45,15 @@ function analyze_entities_sample(): void // Create a client. $languageServiceClient = new LanguageServiceClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $document = new Document(); + $request = (new AnalyzeEntitiesRequest()) + ->setDocument($document); // Call the API and handle any network failures. try { /** @var AnalyzeEntitiesResponse $response */ - $response = $languageServiceClient->analyzeEntities($document); + $response = $languageServiceClient->analyzeEntities($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Language/samples/V1/LanguageServiceClient/analyze_entity_sentiment.php b/Language/samples/V1/LanguageServiceClient/analyze_entity_sentiment.php index e7cccf918791..babc1a3c6cd8 100644 --- a/Language/samples/V1/LanguageServiceClient/analyze_entity_sentiment.php +++ b/Language/samples/V1/LanguageServiceClient/analyze_entity_sentiment.php @@ -24,9 +24,10 @@ // [START language_v1_generated_LanguageService_AnalyzeEntitySentiment_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Language\V1\AnalyzeEntitySentimentRequest; use Google\Cloud\Language\V1\AnalyzeEntitySentimentResponse; +use Google\Cloud\Language\V1\Client\LanguageServiceClient; use Google\Cloud\Language\V1\Document; -use Google\Cloud\Language\V1\LanguageServiceClient; /** * Finds entities, similar to @@ -45,13 +46,15 @@ function analyze_entity_sentiment_sample(): void // Create a client. $languageServiceClient = new LanguageServiceClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $document = new Document(); + $request = (new AnalyzeEntitySentimentRequest()) + ->setDocument($document); // Call the API and handle any network failures. try { /** @var AnalyzeEntitySentimentResponse $response */ - $response = $languageServiceClient->analyzeEntitySentiment($document); + $response = $languageServiceClient->analyzeEntitySentiment($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Language/samples/V1/LanguageServiceClient/analyze_sentiment.php b/Language/samples/V1/LanguageServiceClient/analyze_sentiment.php index a62fdaa54f6c..186806b17caa 100644 --- a/Language/samples/V1/LanguageServiceClient/analyze_sentiment.php +++ b/Language/samples/V1/LanguageServiceClient/analyze_sentiment.php @@ -24,9 +24,10 @@ // [START language_v1_generated_LanguageService_AnalyzeSentiment_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Language\V1\AnalyzeSentimentRequest; use Google\Cloud\Language\V1\AnalyzeSentimentResponse; +use Google\Cloud\Language\V1\Client\LanguageServiceClient; use Google\Cloud\Language\V1\Document; -use Google\Cloud\Language\V1\LanguageServiceClient; /** * Analyzes the sentiment of the provided text. @@ -42,13 +43,15 @@ function analyze_sentiment_sample(): void // Create a client. $languageServiceClient = new LanguageServiceClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $document = new Document(); + $request = (new AnalyzeSentimentRequest()) + ->setDocument($document); // Call the API and handle any network failures. try { /** @var AnalyzeSentimentResponse $response */ - $response = $languageServiceClient->analyzeSentiment($document); + $response = $languageServiceClient->analyzeSentiment($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Language/samples/V1/LanguageServiceClient/analyze_syntax.php b/Language/samples/V1/LanguageServiceClient/analyze_syntax.php index cc9bc76da4ff..e11ec205ae49 100644 --- a/Language/samples/V1/LanguageServiceClient/analyze_syntax.php +++ b/Language/samples/V1/LanguageServiceClient/analyze_syntax.php @@ -24,9 +24,10 @@ // [START language_v1_generated_LanguageService_AnalyzeSyntax_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Language\V1\AnalyzeSyntaxRequest; use Google\Cloud\Language\V1\AnalyzeSyntaxResponse; +use Google\Cloud\Language\V1\Client\LanguageServiceClient; use Google\Cloud\Language\V1\Document; -use Google\Cloud\Language\V1\LanguageServiceClient; /** * Analyzes the syntax of the text and provides sentence boundaries and @@ -44,13 +45,15 @@ function analyze_syntax_sample(): void // Create a client. $languageServiceClient = new LanguageServiceClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $document = new Document(); + $request = (new AnalyzeSyntaxRequest()) + ->setDocument($document); // Call the API and handle any network failures. try { /** @var AnalyzeSyntaxResponse $response */ - $response = $languageServiceClient->analyzeSyntax($document); + $response = $languageServiceClient->analyzeSyntax($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Language/samples/V1/LanguageServiceClient/annotate_text.php b/Language/samples/V1/LanguageServiceClient/annotate_text.php index 91f9bb65df58..dff990c52226 100644 --- a/Language/samples/V1/LanguageServiceClient/annotate_text.php +++ b/Language/samples/V1/LanguageServiceClient/annotate_text.php @@ -24,10 +24,11 @@ // [START language_v1_generated_LanguageService_AnnotateText_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Language\V1\AnnotateTextRequest; use Google\Cloud\Language\V1\AnnotateTextRequest\Features; use Google\Cloud\Language\V1\AnnotateTextResponse; +use Google\Cloud\Language\V1\Client\LanguageServiceClient; use Google\Cloud\Language\V1\Document; -use Google\Cloud\Language\V1\LanguageServiceClient; /** * A convenience method that provides all the features that analyzeSentiment, @@ -44,14 +45,17 @@ function annotate_text_sample(): void // Create a client. $languageServiceClient = new LanguageServiceClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $document = new Document(); $features = new Features(); + $request = (new AnnotateTextRequest()) + ->setDocument($document) + ->setFeatures($features); // Call the API and handle any network failures. try { /** @var AnnotateTextResponse $response */ - $response = $languageServiceClient->annotateText($document, $features); + $response = $languageServiceClient->annotateText($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Language/samples/V1/LanguageServiceClient/classify_text.php b/Language/samples/V1/LanguageServiceClient/classify_text.php index b6dc15a20958..a0214a34f870 100644 --- a/Language/samples/V1/LanguageServiceClient/classify_text.php +++ b/Language/samples/V1/LanguageServiceClient/classify_text.php @@ -24,9 +24,10 @@ // [START language_v1_generated_LanguageService_ClassifyText_sync] use Google\ApiCore\ApiException; +use Google\Cloud\Language\V1\ClassifyTextRequest; use Google\Cloud\Language\V1\ClassifyTextResponse; +use Google\Cloud\Language\V1\Client\LanguageServiceClient; use Google\Cloud\Language\V1\Document; -use Google\Cloud\Language\V1\LanguageServiceClient; /** * Classifies a document into categories. @@ -42,13 +43,15 @@ function classify_text_sample(): void // Create a client. $languageServiceClient = new LanguageServiceClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $document = new Document(); + $request = (new ClassifyTextRequest()) + ->setDocument($document); // Call the API and handle any network failures. try { /** @var ClassifyTextResponse $response */ - $response = $languageServiceClient->classifyText($document); + $response = $languageServiceClient->classifyText($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Language/src/V1/AnalyzeEntitiesRequest.php b/Language/src/V1/AnalyzeEntitiesRequest.php index 0e091735303f..38fe99beaf36 100644 --- a/Language/src/V1/AnalyzeEntitiesRequest.php +++ b/Language/src/V1/AnalyzeEntitiesRequest.php @@ -28,6 +28,35 @@ class AnalyzeEntitiesRequest extends \Google\Protobuf\Internal\Message */ private $encoding_type = 0; + /** + * @param \Google\Cloud\Language\V1\Document $document Required. Input document. + * @param int $encodingType The encoding type used by the API to calculate offsets. + * For allowed values, use constants defined on {@see \Google\Cloud\Language\V1\EncodingType} + * + * @return \Google\Cloud\Language\V1\AnalyzeEntitiesRequest + * + * @experimental + */ + public static function build(\Google\Cloud\Language\V1\Document $document, int $encodingType): self + { + return (new self()) + ->setDocument($document) + ->setEncodingType($encodingType); + } + + /** + * @param \Google\Cloud\Language\V1\Document $document Required. Input document. + * + * @return \Google\Cloud\Language\V1\AnalyzeEntitiesRequest + * + * @experimental + */ + public static function buildFromDocument(\Google\Cloud\Language\V1\Document $document): self + { + return (new self()) + ->setDocument($document); + } + /** * Constructor. * diff --git a/Language/src/V1/AnalyzeEntitySentimentRequest.php b/Language/src/V1/AnalyzeEntitySentimentRequest.php index e2395f339b6b..b5868d29d2ab 100644 --- a/Language/src/V1/AnalyzeEntitySentimentRequest.php +++ b/Language/src/V1/AnalyzeEntitySentimentRequest.php @@ -28,6 +28,35 @@ class AnalyzeEntitySentimentRequest extends \Google\Protobuf\Internal\Message */ private $encoding_type = 0; + /** + * @param \Google\Cloud\Language\V1\Document $document Required. Input document. + * @param int $encodingType The encoding type used by the API to calculate offsets. + * For allowed values, use constants defined on {@see \Google\Cloud\Language\V1\EncodingType} + * + * @return \Google\Cloud\Language\V1\AnalyzeEntitySentimentRequest + * + * @experimental + */ + public static function build(\Google\Cloud\Language\V1\Document $document, int $encodingType): self + { + return (new self()) + ->setDocument($document) + ->setEncodingType($encodingType); + } + + /** + * @param \Google\Cloud\Language\V1\Document $document Required. Input document. + * + * @return \Google\Cloud\Language\V1\AnalyzeEntitySentimentRequest + * + * @experimental + */ + public static function buildFromDocument(\Google\Cloud\Language\V1\Document $document): self + { + return (new self()) + ->setDocument($document); + } + /** * Constructor. * diff --git a/Language/src/V1/AnalyzeSentimentRequest.php b/Language/src/V1/AnalyzeSentimentRequest.php index 38a0e8faa831..26a87207c737 100644 --- a/Language/src/V1/AnalyzeSentimentRequest.php +++ b/Language/src/V1/AnalyzeSentimentRequest.php @@ -28,6 +28,35 @@ class AnalyzeSentimentRequest extends \Google\Protobuf\Internal\Message */ private $encoding_type = 0; + /** + * @param \Google\Cloud\Language\V1\Document $document Required. Input document. + * @param int $encodingType The encoding type used by the API to calculate sentence offsets. + * For allowed values, use constants defined on {@see \Google\Cloud\Language\V1\EncodingType} + * + * @return \Google\Cloud\Language\V1\AnalyzeSentimentRequest + * + * @experimental + */ + public static function build(\Google\Cloud\Language\V1\Document $document, int $encodingType): self + { + return (new self()) + ->setDocument($document) + ->setEncodingType($encodingType); + } + + /** + * @param \Google\Cloud\Language\V1\Document $document Required. Input document. + * + * @return \Google\Cloud\Language\V1\AnalyzeSentimentRequest + * + * @experimental + */ + public static function buildFromDocument(\Google\Cloud\Language\V1\Document $document): self + { + return (new self()) + ->setDocument($document); + } + /** * Constructor. * diff --git a/Language/src/V1/AnalyzeSyntaxRequest.php b/Language/src/V1/AnalyzeSyntaxRequest.php index 03dfd43fa03a..f71d91236001 100644 --- a/Language/src/V1/AnalyzeSyntaxRequest.php +++ b/Language/src/V1/AnalyzeSyntaxRequest.php @@ -28,6 +28,35 @@ class AnalyzeSyntaxRequest extends \Google\Protobuf\Internal\Message */ private $encoding_type = 0; + /** + * @param \Google\Cloud\Language\V1\Document $document Required. Input document. + * @param int $encodingType The encoding type used by the API to calculate offsets. + * For allowed values, use constants defined on {@see \Google\Cloud\Language\V1\EncodingType} + * + * @return \Google\Cloud\Language\V1\AnalyzeSyntaxRequest + * + * @experimental + */ + public static function build(\Google\Cloud\Language\V1\Document $document, int $encodingType): self + { + return (new self()) + ->setDocument($document) + ->setEncodingType($encodingType); + } + + /** + * @param \Google\Cloud\Language\V1\Document $document Required. Input document. + * + * @return \Google\Cloud\Language\V1\AnalyzeSyntaxRequest + * + * @experimental + */ + public static function buildFromDocument(\Google\Cloud\Language\V1\Document $document): self + { + return (new self()) + ->setDocument($document); + } + /** * Constructor. * diff --git a/Language/src/V1/AnnotateTextRequest.php b/Language/src/V1/AnnotateTextRequest.php index 8ab9e3416486..2a8822f7b2d5 100644 --- a/Language/src/V1/AnnotateTextRequest.php +++ b/Language/src/V1/AnnotateTextRequest.php @@ -35,6 +35,39 @@ class AnnotateTextRequest extends \Google\Protobuf\Internal\Message */ private $encoding_type = 0; + /** + * @param \Google\Cloud\Language\V1\Document $document Required. Input document. + * @param \Google\Cloud\Language\V1\AnnotateTextRequest\Features $features Required. The enabled features. + * @param int $encodingType The encoding type used by the API to calculate offsets. + * For allowed values, use constants defined on {@see \Google\Cloud\Language\V1\EncodingType} + * + * @return \Google\Cloud\Language\V1\AnnotateTextRequest + * + * @experimental + */ + public static function build(\Google\Cloud\Language\V1\Document $document, \Google\Cloud\Language\V1\AnnotateTextRequest\Features $features, int $encodingType): self + { + return (new self()) + ->setDocument($document) + ->setFeatures($features) + ->setEncodingType($encodingType); + } + + /** + * @param \Google\Cloud\Language\V1\Document $document Required. Input document. + * @param \Google\Cloud\Language\V1\AnnotateTextRequest\Features $features Required. The enabled features. + * + * @return \Google\Cloud\Language\V1\AnnotateTextRequest + * + * @experimental + */ + public static function buildFromDocumentFeatures(\Google\Cloud\Language\V1\Document $document, \Google\Cloud\Language\V1\AnnotateTextRequest\Features $features): self + { + return (new self()) + ->setDocument($document) + ->setFeatures($features); + } + /** * Constructor. * diff --git a/Language/src/V1/ClassifyTextRequest.php b/Language/src/V1/ClassifyTextRequest.php index 539eae89f78f..0cf3a88675b8 100644 --- a/Language/src/V1/ClassifyTextRequest.php +++ b/Language/src/V1/ClassifyTextRequest.php @@ -29,6 +29,19 @@ class ClassifyTextRequest extends \Google\Protobuf\Internal\Message */ private $classification_model_options = null; + /** + * @param \Google\Cloud\Language\V1\Document $document Required. Input document. + * + * @return \Google\Cloud\Language\V1\ClassifyTextRequest + * + * @experimental + */ + public static function build(\Google\Cloud\Language\V1\Document $document): self + { + return (new self()) + ->setDocument($document); + } + /** * Constructor. * diff --git a/Language/src/V1/Client/BaseClient/LanguageServiceBaseClient.php b/Language/src/V1/Client/BaseClient/LanguageServiceBaseClient.php new file mode 100644 index 000000000000..e3eaabbe8f9a --- /dev/null +++ b/Language/src/V1/Client/BaseClient/LanguageServiceBaseClient.php @@ -0,0 +1,331 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/language_service_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/language_service_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/language_service_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/language_service_rest_client_config.php', + ], + ], + ]; + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'language.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Finds named entities (currently proper names and common nouns) in the text + * along with entity types, salience, mentions for each entity, and + * other properties. + * + * The async variant is {@see self::analyzeEntitiesAsync()} . + * + * @param AnalyzeEntitiesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return AnalyzeEntitiesResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function analyzeEntities(AnalyzeEntitiesRequest $request, array $callOptions = []): AnalyzeEntitiesResponse + { + return $this->startApiCall('AnalyzeEntities', $request, $callOptions)->wait(); + } + + /** + * Finds entities, similar to + * [AnalyzeEntities][google.cloud.language.v1.LanguageService.AnalyzeEntities] + * in the text and analyzes sentiment associated with each entity and its + * mentions. + * + * The async variant is {@see self::analyzeEntitySentimentAsync()} . + * + * @param AnalyzeEntitySentimentRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return AnalyzeEntitySentimentResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function analyzeEntitySentiment(AnalyzeEntitySentimentRequest $request, array $callOptions = []): AnalyzeEntitySentimentResponse + { + return $this->startApiCall('AnalyzeEntitySentiment', $request, $callOptions)->wait(); + } + + /** + * Analyzes the sentiment of the provided text. + * + * The async variant is {@see self::analyzeSentimentAsync()} . + * + * @param AnalyzeSentimentRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return AnalyzeSentimentResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function analyzeSentiment(AnalyzeSentimentRequest $request, array $callOptions = []): AnalyzeSentimentResponse + { + return $this->startApiCall('AnalyzeSentiment', $request, $callOptions)->wait(); + } + + /** + * Analyzes the syntax of the text and provides sentence boundaries and + * tokenization along with part of speech tags, dependency trees, and other + * properties. + * + * The async variant is {@see self::analyzeSyntaxAsync()} . + * + * @param AnalyzeSyntaxRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return AnalyzeSyntaxResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function analyzeSyntax(AnalyzeSyntaxRequest $request, array $callOptions = []): AnalyzeSyntaxResponse + { + return $this->startApiCall('AnalyzeSyntax', $request, $callOptions)->wait(); + } + + /** + * A convenience method that provides all the features that analyzeSentiment, + * analyzeEntities, and analyzeSyntax provide in one call. + * + * The async variant is {@see self::annotateTextAsync()} . + * + * @param AnnotateTextRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return AnnotateTextResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function annotateText(AnnotateTextRequest $request, array $callOptions = []): AnnotateTextResponse + { + return $this->startApiCall('AnnotateText', $request, $callOptions)->wait(); + } + + /** + * Classifies a document into categories. + * + * The async variant is {@see self::classifyTextAsync()} . + * + * @param ClassifyTextRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return ClassifyTextResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function classifyText(ClassifyTextRequest $request, array $callOptions = []): ClassifyTextResponse + { + return $this->startApiCall('ClassifyText', $request, $callOptions)->wait(); + } +} diff --git a/Language/src/V1/Client/LanguageServiceClient.php b/Language/src/V1/Client/LanguageServiceClient.php new file mode 100644 index 000000000000..ea36ac6cff22 --- /dev/null +++ b/Language/src/V1/Client/LanguageServiceClient.php @@ -0,0 +1,40 @@ + [ - 'google.cloud.language.v1.LanguageService' => [], + 'google.cloud.language.v1.LanguageService' => [ + 'AnalyzeEntities' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Language\V1\AnalyzeEntitiesResponse', + ], + 'AnalyzeEntitySentiment' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Language\V1\AnalyzeEntitySentimentResponse', + ], + 'AnalyzeSentiment' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Language\V1\AnalyzeSentimentResponse', + ], + 'AnalyzeSyntax' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Language\V1\AnalyzeSyntaxResponse', + ], + 'AnnotateText' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Language\V1\AnnotateTextResponse', + ], + 'ClassifyText' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Language\V1\ClassifyTextResponse', + ], + ], ], ]; diff --git a/Language/tests/Unit/V1/Client/LanguageServiceClientTest.php b/Language/tests/Unit/V1/Client/LanguageServiceClientTest.php new file mode 100644 index 000000000000..07424c1372b4 --- /dev/null +++ b/Language/tests/Unit/V1/Client/LanguageServiceClientTest.php @@ -0,0 +1,491 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return LanguageServiceClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new LanguageServiceClient($options); + } + + /** @test */ + public function analyzeEntitiesTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $language = 'language-1613589672'; + $expectedResponse = new AnalyzeEntitiesResponse(); + $expectedResponse->setLanguage($language); + $transport->addResponse($expectedResponse); + // Mock request + $document = new Document(); + $request = (new AnalyzeEntitiesRequest()) + ->setDocument($document); + $response = $gapicClient->analyzeEntities($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.language.v1.LanguageService/AnalyzeEntities', $actualFuncCall); + $actualValue = $actualRequestObject->getDocument(); + $this->assertProtobufEquals($document, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function analyzeEntitiesExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $document = new Document(); + $request = (new AnalyzeEntitiesRequest()) + ->setDocument($document); + try { + $gapicClient->analyzeEntities($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function analyzeEntitySentimentTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $language = 'language-1613589672'; + $expectedResponse = new AnalyzeEntitySentimentResponse(); + $expectedResponse->setLanguage($language); + $transport->addResponse($expectedResponse); + // Mock request + $document = new Document(); + $request = (new AnalyzeEntitySentimentRequest()) + ->setDocument($document); + $response = $gapicClient->analyzeEntitySentiment($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.language.v1.LanguageService/AnalyzeEntitySentiment', $actualFuncCall); + $actualValue = $actualRequestObject->getDocument(); + $this->assertProtobufEquals($document, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function analyzeEntitySentimentExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $document = new Document(); + $request = (new AnalyzeEntitySentimentRequest()) + ->setDocument($document); + try { + $gapicClient->analyzeEntitySentiment($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function analyzeSentimentTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $language = 'language-1613589672'; + $expectedResponse = new AnalyzeSentimentResponse(); + $expectedResponse->setLanguage($language); + $transport->addResponse($expectedResponse); + // Mock request + $document = new Document(); + $request = (new AnalyzeSentimentRequest()) + ->setDocument($document); + $response = $gapicClient->analyzeSentiment($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.language.v1.LanguageService/AnalyzeSentiment', $actualFuncCall); + $actualValue = $actualRequestObject->getDocument(); + $this->assertProtobufEquals($document, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function analyzeSentimentExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $document = new Document(); + $request = (new AnalyzeSentimentRequest()) + ->setDocument($document); + try { + $gapicClient->analyzeSentiment($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function analyzeSyntaxTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $language = 'language-1613589672'; + $expectedResponse = new AnalyzeSyntaxResponse(); + $expectedResponse->setLanguage($language); + $transport->addResponse($expectedResponse); + // Mock request + $document = new Document(); + $request = (new AnalyzeSyntaxRequest()) + ->setDocument($document); + $response = $gapicClient->analyzeSyntax($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.language.v1.LanguageService/AnalyzeSyntax', $actualFuncCall); + $actualValue = $actualRequestObject->getDocument(); + $this->assertProtobufEquals($document, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function analyzeSyntaxExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $document = new Document(); + $request = (new AnalyzeSyntaxRequest()) + ->setDocument($document); + try { + $gapicClient->analyzeSyntax($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function annotateTextTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $language = 'language-1613589672'; + $expectedResponse = new AnnotateTextResponse(); + $expectedResponse->setLanguage($language); + $transport->addResponse($expectedResponse); + // Mock request + $document = new Document(); + $features = new Features(); + $request = (new AnnotateTextRequest()) + ->setDocument($document) + ->setFeatures($features); + $response = $gapicClient->annotateText($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.language.v1.LanguageService/AnnotateText', $actualFuncCall); + $actualValue = $actualRequestObject->getDocument(); + $this->assertProtobufEquals($document, $actualValue); + $actualValue = $actualRequestObject->getFeatures(); + $this->assertProtobufEquals($features, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function annotateTextExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $document = new Document(); + $features = new Features(); + $request = (new AnnotateTextRequest()) + ->setDocument($document) + ->setFeatures($features); + try { + $gapicClient->annotateText($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function classifyTextTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new ClassifyTextResponse(); + $transport->addResponse($expectedResponse); + // Mock request + $document = new Document(); + $request = (new ClassifyTextRequest()) + ->setDocument($document); + $response = $gapicClient->classifyText($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.language.v1.LanguageService/ClassifyText', $actualFuncCall); + $actualValue = $actualRequestObject->getDocument(); + $this->assertProtobufEquals($document, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function classifyTextExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $document = new Document(); + $request = (new ClassifyTextRequest()) + ->setDocument($document); + try { + $gapicClient->classifyText($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function analyzeEntitiesAsyncTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $language = 'language-1613589672'; + $expectedResponse = new AnalyzeEntitiesResponse(); + $expectedResponse->setLanguage($language); + $transport->addResponse($expectedResponse); + // Mock request + $document = new Document(); + $request = (new AnalyzeEntitiesRequest()) + ->setDocument($document); + $response = $gapicClient->analyzeEntitiesAsync($request)->wait(); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.language.v1.LanguageService/AnalyzeEntities', $actualFuncCall); + $actualValue = $actualRequestObject->getDocument(); + $this->assertProtobufEquals($document, $actualValue); + $this->assertTrue($transport->isExhausted()); + } +} diff --git a/LifeSciences/samples/V2beta/WorkflowsServiceV2BetaClient/get_location.php b/LifeSciences/samples/V2beta/WorkflowsServiceV2BetaClient/get_location.php index 991eb7500099..fe41bb72801d 100644 --- a/LifeSciences/samples/V2beta/WorkflowsServiceV2BetaClient/get_location.php +++ b/LifeSciences/samples/V2beta/WorkflowsServiceV2BetaClient/get_location.php @@ -24,7 +24,8 @@ // [START lifesciences_v2beta_generated_WorkflowsServiceV2Beta_GetLocation_sync] use Google\ApiCore\ApiException; -use Google\Cloud\LifeSciences\V2beta\WorkflowsServiceV2BetaClient; +use Google\Cloud\LifeSciences\V2beta\Client\WorkflowsServiceV2BetaClient; +use Google\Cloud\Location\GetLocationRequest; use Google\Cloud\Location\Location; /** @@ -41,10 +42,13 @@ function get_location_sample(): void // Create a client. $workflowsServiceV2BetaClient = new WorkflowsServiceV2BetaClient(); + // Prepare the request message. + $request = new GetLocationRequest(); + // Call the API and handle any network failures. try { /** @var Location $response */ - $response = $workflowsServiceV2BetaClient->getLocation(); + $response = $workflowsServiceV2BetaClient->getLocation($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/LifeSciences/samples/V2beta/WorkflowsServiceV2BetaClient/list_locations.php b/LifeSciences/samples/V2beta/WorkflowsServiceV2BetaClient/list_locations.php index 2862b070e5f2..7140dfe0d1d7 100644 --- a/LifeSciences/samples/V2beta/WorkflowsServiceV2BetaClient/list_locations.php +++ b/LifeSciences/samples/V2beta/WorkflowsServiceV2BetaClient/list_locations.php @@ -25,7 +25,8 @@ // [START lifesciences_v2beta_generated_WorkflowsServiceV2Beta_ListLocations_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\LifeSciences\V2beta\WorkflowsServiceV2BetaClient; +use Google\Cloud\LifeSciences\V2beta\Client\WorkflowsServiceV2BetaClient; +use Google\Cloud\Location\ListLocationsRequest; use Google\Cloud\Location\Location; /** @@ -42,10 +43,13 @@ function list_locations_sample(): void // Create a client. $workflowsServiceV2BetaClient = new WorkflowsServiceV2BetaClient(); + // Prepare the request message. + $request = new ListLocationsRequest(); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $workflowsServiceV2BetaClient->listLocations(); + $response = $workflowsServiceV2BetaClient->listLocations($request); /** @var Location $element */ foreach ($response as $element) { diff --git a/LifeSciences/samples/V2beta/WorkflowsServiceV2BetaClient/run_pipeline.php b/LifeSciences/samples/V2beta/WorkflowsServiceV2BetaClient/run_pipeline.php index 61cfea4d786a..a7542f85ced6 100644 --- a/LifeSciences/samples/V2beta/WorkflowsServiceV2BetaClient/run_pipeline.php +++ b/LifeSciences/samples/V2beta/WorkflowsServiceV2BetaClient/run_pipeline.php @@ -25,9 +25,10 @@ // [START lifesciences_v2beta_generated_WorkflowsServiceV2Beta_RunPipeline_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; +use Google\Cloud\LifeSciences\V2beta\Client\WorkflowsServiceV2BetaClient; use Google\Cloud\LifeSciences\V2beta\Pipeline; +use Google\Cloud\LifeSciences\V2beta\RunPipelineRequest; use Google\Cloud\LifeSciences\V2beta\RunPipelineResponse; -use Google\Cloud\LifeSciences\V2beta\WorkflowsServiceV2BetaClient; use Google\Rpc\Status; /** @@ -60,13 +61,15 @@ function run_pipeline_sample(): void // Create a client. $workflowsServiceV2BetaClient = new WorkflowsServiceV2BetaClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $pipeline = new Pipeline(); + $request = (new RunPipelineRequest()) + ->setPipeline($pipeline); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $workflowsServiceV2BetaClient->runPipeline($pipeline); + $response = $workflowsServiceV2BetaClient->runPipeline($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/LifeSciences/src/V2beta/Client/BaseClient/WorkflowsServiceV2BetaBaseClient.php b/LifeSciences/src/V2beta/Client/BaseClient/WorkflowsServiceV2BetaBaseClient.php new file mode 100644 index 000000000000..27659f47fbd3 --- /dev/null +++ b/LifeSciences/src/V2beta/Client/BaseClient/WorkflowsServiceV2BetaBaseClient.php @@ -0,0 +1,307 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/workflows_service_v2_beta_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/workflows_service_v2_beta_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/workflows_service_v2_beta_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/workflows_service_v2_beta_rest_client_config.php', + ], + ], + ]; + } + + /** + * Return an OperationsClient object with the same endpoint as $this. + * + * @return OperationsClient + * + * @experimental + */ + public function getOperationsClient() + { + return $this->operationsClient; + } + + /** + * Resume an existing long running operation that was previously started by a long + * running API method. If $methodName is not provided, or does not match a long + * running API method, then the operation can still be resumed, but the + * OperationResponse object will not deserialize the final response. + * + * @param string $operationName The name of the long running operation + * @param string $methodName The name of the method used to start the operation + * + * @return OperationResponse + * + * @experimental + */ + public function resumeOperation($operationName, $methodName = null) + { + $options = isset($this->descriptors[$methodName]['longRunning']) ? $this->descriptors[$methodName]['longRunning'] : []; + $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); + $operation->reload(); + return $operation; + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'lifesciences.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + * + * @experimental + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + $this->operationsClient = $this->createOperationsClient($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Runs a pipeline. The returned Operation's [metadata] + * [google.longrunning.Operation.metadata] field will contain a + * [google.cloud.lifesciences.v2beta.Metadata][google.cloud.lifesciences.v2beta.Metadata] + * object describing the status of the pipeline execution. The + * [response][google.longrunning.Operation.response] field will contain a + * [google.cloud.lifesciences.v2beta.RunPipelineResponse][google.cloud.lifesciences.v2beta.RunPipelineResponse] + * object if the pipeline completes successfully. + * + * **Note:** Before you can use this method, the *Life Sciences Service Agent* + * must have access to your project. This is done automatically when the + * Cloud Life Sciences API is first enabled, but if you delete this permission + * you must disable and re-enable the API to grant the Life Sciences + * Service Agent the required permissions. + * Authorization requires the following [Google + * IAM](https://cloud.google.com/iam/) permission: + * + * * `lifesciences.workflows.run` + * + * The async variant is {@see self::runPipelineAsync()} . + * + * @param RunPipelineRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function runPipeline(RunPipelineRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('RunPipeline', $request, $callOptions)->wait(); + } + + /** + * Gets information about a location. + * + * The async variant is {@see self::getLocationAsync()} . + * + * @param GetLocationRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Location + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function getLocation(GetLocationRequest $request, array $callOptions = []): Location + { + return $this->startApiCall('GetLocation', $request, $callOptions)->wait(); + } + + /** + * Lists information about the supported locations for this service. + * + * The async variant is {@see self::listLocationsAsync()} . + * + * @param ListLocationsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function listLocations(ListLocationsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListLocations', $request, $callOptions); + } +} diff --git a/LifeSciences/src/V2beta/Client/WorkflowsServiceV2BetaClient.php b/LifeSciences/src/V2beta/Client/WorkflowsServiceV2BetaClient.php new file mode 100644 index 000000000000..6183192b0cfa --- /dev/null +++ b/LifeSciences/src/V2beta/Client/WorkflowsServiceV2BetaClient.php @@ -0,0 +1,42 @@ + '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'GetLocation' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Location\Location', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], 'interfaceOverride' => 'google.cloud.location.Locations', ], 'ListLocations' => [ @@ -25,6 +44,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getLocations', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\Location\ListLocationsResponse', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], 'interfaceOverride' => 'google.cloud.location.Locations', ], ], diff --git a/LifeSciences/tests/Unit/V2beta/Client/WorkflowsServiceV2BetaClientTest.php b/LifeSciences/tests/Unit/V2beta/Client/WorkflowsServiceV2BetaClientTest.php new file mode 100644 index 000000000000..c37de65ffa7f --- /dev/null +++ b/LifeSciences/tests/Unit/V2beta/Client/WorkflowsServiceV2BetaClientTest.php @@ -0,0 +1,380 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return WorkflowsServiceV2BetaClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new WorkflowsServiceV2BetaClient($options); + } + + /** @test */ + public function runPipelineTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/runPipelineTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new RunPipelineResponse(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/runPipelineTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $pipeline = new Pipeline(); + $request = (new RunPipelineRequest()) + ->setPipeline($pipeline); + $response = $gapicClient->runPipeline($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.lifesciences.v2beta.WorkflowsServiceV2Beta/RunPipeline', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getPipeline(); + $this->assertProtobufEquals($pipeline, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/runPipelineTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function runPipelineExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/runPipelineTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $pipeline = new Pipeline(); + $request = (new RunPipelineRequest()) + ->setPipeline($pipeline); + $response = $gapicClient->runPipeline($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/runPipelineTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function getLocationTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $locationId = 'locationId552319461'; + $displayName = 'displayName1615086568'; + $expectedResponse = new Location(); + $expectedResponse->setName($name2); + $expectedResponse->setLocationId($locationId); + $expectedResponse->setDisplayName($displayName); + $transport->addResponse($expectedResponse); + $request = new GetLocationRequest(); + $response = $gapicClient->getLocation($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.location.Locations/GetLocation', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getLocationExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + $request = new GetLocationRequest(); + try { + $gapicClient->getLocation($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listLocationsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $locationsElement = new Location(); + $locations = [ + $locationsElement, + ]; + $expectedResponse = new ListLocationsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setLocations($locations); + $transport->addResponse($expectedResponse); + $request = new ListLocationsRequest(); + $response = $gapicClient->listLocations($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getLocations()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.location.Locations/ListLocations', $actualFuncCall); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listLocationsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + $request = new ListLocationsRequest(); + try { + $gapicClient->listLocations($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function runPipelineAsyncTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/runPipelineTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new RunPipelineResponse(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/runPipelineTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $pipeline = new Pipeline(); + $request = (new RunPipelineRequest()) + ->setPipeline($pipeline); + $response = $gapicClient->runPipelineAsync($request)->wait(); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.lifesciences.v2beta.WorkflowsServiceV2Beta/RunPipeline', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getPipeline(); + $this->assertProtobufEquals($pipeline, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/runPipelineTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } +} diff --git a/MediaTranslation/samples/V1beta1/SpeechTranslationServiceClient/streaming_translate_speech.php b/MediaTranslation/samples/V1beta1/SpeechTranslationServiceClient/streaming_translate_speech.php index 77ad8cbd667d..258da961b50a 100644 --- a/MediaTranslation/samples/V1beta1/SpeechTranslationServiceClient/streaming_translate_speech.php +++ b/MediaTranslation/samples/V1beta1/SpeechTranslationServiceClient/streaming_translate_speech.php @@ -25,7 +25,7 @@ // [START mediatranslation_v1beta1_generated_SpeechTranslationService_StreamingTranslateSpeech_sync] use Google\ApiCore\ApiException; use Google\ApiCore\BidiStream; -use Google\Cloud\MediaTranslation\V1beta1\SpeechTranslationServiceClient; +use Google\Cloud\MediaTranslation\V1beta1\Client\SpeechTranslationServiceClient; use Google\Cloud\MediaTranslation\V1beta1\StreamingTranslateSpeechRequest; use Google\Cloud\MediaTranslation\V1beta1\StreamingTranslateSpeechResponse; @@ -44,7 +44,7 @@ function streaming_translate_speech_sample(): void // Create a client. $speechTranslationServiceClient = new SpeechTranslationServiceClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $request = new StreamingTranslateSpeechRequest(); // Call the API and handle any network failures. diff --git a/MediaTranslation/src/V1beta1/Client/BaseClient/SpeechTranslationServiceBaseClient.php b/MediaTranslation/src/V1beta1/Client/BaseClient/SpeechTranslationServiceBaseClient.php new file mode 100644 index 000000000000..8905d1be1b50 --- /dev/null +++ b/MediaTranslation/src/V1beta1/Client/BaseClient/SpeechTranslationServiceBaseClient.php @@ -0,0 +1,172 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/speech_translation_service_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/speech_translation_service_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/speech_translation_service_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/speech_translation_service_rest_client_config.php', + ], + ], + ]; + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'mediatranslation.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + * + * @experimental + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + } + + /** + * Performs bidirectional streaming speech translation: receive results while + * sending audio. This method is only available via the gRPC API (not REST). + * + * @param array $callOptions { + * Optional. + * + * @type int $timeoutMillis + * Timeout to use for this call. + * } + * + * @return BidiStream + * + * @throws ApiException Thrown if the API call fails. + * + * @experimental + */ + public function streamingTranslateSpeech(array $callOptions = []): BidiStream + { + return $this->startApiCall('StreamingTranslateSpeech', null, $callOptions); + } +} diff --git a/MediaTranslation/src/V1beta1/Client/SpeechTranslationServiceClient.php b/MediaTranslation/src/V1beta1/Client/SpeechTranslationServiceClient.php new file mode 100644 index 000000000000..c15d958ba103 --- /dev/null +++ b/MediaTranslation/src/V1beta1/Client/SpeechTranslationServiceClient.php @@ -0,0 +1,42 @@ + [ 'grpcStreamingType' => 'BidiStreaming', ], + 'callType' => \Google\ApiCore\Call::BIDI_STREAMING_CALL, + 'responseType' => 'Google\Cloud\MediaTranslation\V1beta1\StreamingTranslateSpeechResponse', ], ], ], diff --git a/MediaTranslation/tests/Unit/V1beta1/Client/SpeechTranslationServiceClientTest.php b/MediaTranslation/tests/Unit/V1beta1/Client/SpeechTranslationServiceClientTest.php new file mode 100644 index 000000000000..9713533addc6 --- /dev/null +++ b/MediaTranslation/tests/Unit/V1beta1/Client/SpeechTranslationServiceClientTest.php @@ -0,0 +1,151 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return SpeechTranslationServiceClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new SpeechTranslationServiceClient($options); + } + + /** @test */ + public function streamingTranslateSpeechTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new StreamingTranslateSpeechResponse(); + $transport->addResponse($expectedResponse); + $expectedResponse2 = new StreamingTranslateSpeechResponse(); + $transport->addResponse($expectedResponse2); + $expectedResponse3 = new StreamingTranslateSpeechResponse(); + $transport->addResponse($expectedResponse3); + // Mock request + $request = new StreamingTranslateSpeechRequest(); + $request2 = new StreamingTranslateSpeechRequest(); + $request3 = new StreamingTranslateSpeechRequest(); + $bidi = $gapicClient->streamingTranslateSpeech(); + $this->assertInstanceOf(BidiStream::class, $bidi); + $bidi->write($request); + $responses = []; + $responses[] = $bidi->read(); + $bidi->writeAll([ + $request2, + $request3, + ]); + foreach ($bidi->closeWriteAndReadAll() as $response) { + $responses[] = $response; + } + + $expectedResponses = []; + $expectedResponses[] = $expectedResponse; + $expectedResponses[] = $expectedResponse2; + $expectedResponses[] = $expectedResponse3; + $this->assertEquals($expectedResponses, $responses); + $createStreamRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($createStreamRequests)); + $streamFuncCall = $createStreamRequests[0]->getFuncCall(); + $streamRequestObject = $createStreamRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.mediatranslation.v1beta1.SpeechTranslationService/StreamingTranslateSpeech', $streamFuncCall); + $this->assertNull($streamRequestObject); + $callObjects = $transport->popCallObjects(); + $this->assertSame(1, count($callObjects)); + $bidiCall = $callObjects[0]; + $writeRequests = $bidiCall->popReceivedCalls(); + $expectedRequests = []; + $expectedRequests[] = $request; + $expectedRequests[] = $request2; + $expectedRequests[] = $request3; + $this->assertEquals($expectedRequests, $writeRequests); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function streamingTranslateSpeechExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->setStreamingStatus($status); + $this->assertTrue($transport->isExhausted()); + $bidi = $gapicClient->streamingTranslateSpeech(); + $results = $bidi->closeWriteAndReadAll(); + try { + iterator_to_array($results); + // If the close stream method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } +} diff --git a/Optimization/samples/V1/FleetRoutingClient/batch_optimize_tours.php b/Optimization/samples/V1/FleetRoutingClient/batch_optimize_tours.php index 3f84e665f5d8..5ad13369b4f3 100644 --- a/Optimization/samples/V1/FleetRoutingClient/batch_optimize_tours.php +++ b/Optimization/samples/V1/FleetRoutingClient/batch_optimize_tours.php @@ -25,9 +25,10 @@ // [START cloudoptimization_v1_generated_FleetRouting_BatchOptimizeTours_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; +use Google\Cloud\Optimization\V1\BatchOptimizeToursRequest; use Google\Cloud\Optimization\V1\BatchOptimizeToursRequest\AsyncModelConfig; use Google\Cloud\Optimization\V1\BatchOptimizeToursResponse; -use Google\Cloud\Optimization\V1\FleetRoutingClient; +use Google\Cloud\Optimization\V1\Client\FleetRoutingClient; use Google\Cloud\Optimization\V1\InputConfig; use Google\Cloud\Optimization\V1\OutputConfig; use Google\Rpc\Status; @@ -55,18 +56,21 @@ function batch_optimize_tours_sample(string $parent): void // Create a client. $fleetRoutingClient = new FleetRoutingClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $modelConfigsInputConfig = new InputConfig(); $modelConfigsOutputConfig = new OutputConfig(); $asyncModelConfig = (new AsyncModelConfig()) ->setInputConfig($modelConfigsInputConfig) ->setOutputConfig($modelConfigsOutputConfig); $modelConfigs = [$asyncModelConfig,]; + $request = (new BatchOptimizeToursRequest()) + ->setParent($parent) + ->setModelConfigs($modelConfigs); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ - $response = $fleetRoutingClient->batchOptimizeTours($parent, $modelConfigs); + $response = $fleetRoutingClient->batchOptimizeTours($request); $response->pollUntilComplete(); if ($response->operationSucceeded()) { diff --git a/Optimization/samples/V1/FleetRoutingClient/optimize_tours.php b/Optimization/samples/V1/FleetRoutingClient/optimize_tours.php index 1933b2004efe..ce9cb93ff455 100644 --- a/Optimization/samples/V1/FleetRoutingClient/optimize_tours.php +++ b/Optimization/samples/V1/FleetRoutingClient/optimize_tours.php @@ -24,7 +24,8 @@ // [START cloudoptimization_v1_generated_FleetRouting_OptimizeTours_sync] use Google\ApiCore\ApiException; -use Google\Cloud\Optimization\V1\FleetRoutingClient; +use Google\Cloud\Optimization\V1\Client\FleetRoutingClient; +use Google\Cloud\Optimization\V1\OptimizeToursRequest; use Google\Cloud\Optimization\V1\OptimizeToursResponse; /** @@ -54,10 +55,14 @@ function optimize_tours_sample(string $parent): void // Create a client. $fleetRoutingClient = new FleetRoutingClient(); + // Prepare the request message. + $request = (new OptimizeToursRequest()) + ->setParent($parent); + // Call the API and handle any network failures. try { /** @var OptimizeToursResponse $response */ - $response = $fleetRoutingClient->optimizeTours($parent); + $response = $fleetRoutingClient->optimizeTours($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/Optimization/src/V1/Client/BaseClient/FleetRoutingBaseClient.php b/Optimization/src/V1/Client/BaseClient/FleetRoutingBaseClient.php new file mode 100644 index 000000000000..1d0e85151b6c --- /dev/null +++ b/Optimization/src/V1/Client/BaseClient/FleetRoutingBaseClient.php @@ -0,0 +1,286 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/fleet_routing_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/fleet_routing_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/fleet_routing_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/fleet_routing_rest_client_config.php', + ], + ], + ]; + } + + /** + * Return an OperationsClient object with the same endpoint as $this. + * + * @return OperationsClient + */ + public function getOperationsClient() + { + return $this->operationsClient; + } + + /** + * Resume an existing long running operation that was previously started by a long + * running API method. If $methodName is not provided, or does not match a long + * running API method, then the operation can still be resumed, but the + * OperationResponse object will not deserialize the final response. + * + * @param string $operationName The name of the long running operation + * @param string $methodName The name of the method used to start the operation + * + * @return OperationResponse + */ + public function resumeOperation($operationName, $methodName = null) + { + $options = isset($this->descriptors[$methodName]['longRunning']) ? $this->descriptors[$methodName]['longRunning'] : []; + $operation = new OperationResponse($operationName, $this->getOperationsClient(), $options); + $operation->reload(); + return $operation; + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'cloudoptimization.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + $this->operationsClient = $this->createOperationsClient($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Optimizes vehicle tours for one or more `OptimizeToursRequest` + * messages as a batch. + * + * This method is a Long Running Operation (LRO). The inputs for optimization + * (`OptimizeToursRequest` messages) and outputs (`OptimizeToursResponse` + * messages) are read/written from/to Cloud Storage in user-specified + * format. Like the `OptimizeTours` method, each `OptimizeToursRequest` + * contains a `ShipmentModel` and returns an `OptimizeToursResponse` + * containing `ShipmentRoute`s, which are a set of routes to be performed by + * vehicles minimizing the overall cost. + * + * The async variant is {@see self::batchOptimizeToursAsync()} . + * + * @param BatchOptimizeToursRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OperationResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function batchOptimizeTours(BatchOptimizeToursRequest $request, array $callOptions = []): OperationResponse + { + return $this->startApiCall('BatchOptimizeTours', $request, $callOptions)->wait(); + } + + /** + * Sends an `OptimizeToursRequest` containing a `ShipmentModel` and returns an + * `OptimizeToursResponse` containing `ShipmentRoute`s, which are a set of + * routes to be performed by vehicles minimizing the overall cost. + * + * A `ShipmentModel` model consists mainly of `Shipment`s that need to be + * carried out and `Vehicle`s that can be used to transport the `Shipment`s. + * The `ShipmentRoute`s assign `Shipment`s to `Vehicle`s. More specifically, + * they assign a series of `Visit`s to each vehicle, where a `Visit` + * corresponds to a `VisitRequest`, which is a pickup or delivery for a + * `Shipment`. + * + * The goal is to provide an assignment of `ShipmentRoute`s to `Vehicle`s that + * minimizes the total cost where cost has many components defined in the + * `ShipmentModel`. + * + * The async variant is {@see self::optimizeToursAsync()} . + * + * @param OptimizeToursRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return OptimizeToursResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function optimizeTours(OptimizeToursRequest $request, array $callOptions = []): OptimizeToursResponse + { + return $this->startApiCall('OptimizeTours', $request, $callOptions)->wait(); + } +} diff --git a/Optimization/src/V1/Client/FleetRoutingClient.php b/Optimization/src/V1/Client/FleetRoutingClient.php new file mode 100644 index 000000000000..c830867e8ca7 --- /dev/null +++ b/Optimization/src/V1/Client/FleetRoutingClient.php @@ -0,0 +1,40 @@ + '5000', 'totalPollTimeoutMillis' => '300000', ], + 'callType' => \Google\ApiCore\Call::LONGRUNNING_CALL, + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'OptimizeTours' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\Optimization\V1\OptimizeToursResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], ], ], diff --git a/Optimization/tests/Unit/V1/Client/FleetRoutingClientTest.php b/Optimization/tests/Unit/V1/Client/FleetRoutingClientTest.php new file mode 100644 index 000000000000..1b87ad9a0077 --- /dev/null +++ b/Optimization/tests/Unit/V1/Client/FleetRoutingClientTest.php @@ -0,0 +1,329 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return FleetRoutingClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new FleetRoutingClient($options); + } + + /** @test */ + public function batchOptimizeToursTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/batchOptimizeToursTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new BatchOptimizeToursResponse(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/batchOptimizeToursTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $parent = 'parent-995424086'; + $modelConfigs = []; + $request = (new BatchOptimizeToursRequest()) + ->setParent($parent) + ->setModelConfigs($modelConfigs); + $response = $gapicClient->batchOptimizeTours($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.optimization.v1.FleetRouting/BatchOptimizeTours', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($parent, $actualValue); + $actualValue = $actualApiRequestObject->getModelConfigs(); + $this->assertProtobufEquals($modelConfigs, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/batchOptimizeToursTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function batchOptimizeToursExceptionTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/batchOptimizeToursTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $operationsTransport->addResponse(null, $status); + // Mock request + $parent = 'parent-995424086'; + $modelConfigs = []; + $request = (new BatchOptimizeToursRequest()) + ->setParent($parent) + ->setModelConfigs($modelConfigs); + $response = $gapicClient->batchOptimizeTours($request); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/batchOptimizeToursTest'); + try { + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + // If the pollUntilComplete() method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stubs are exhausted + $transport->popReceivedCalls(); + $operationsTransport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } + + /** @test */ + public function optimizeToursTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $requestLabel = 'requestLabel1739091268'; + $totalCost = -7.0589032E7; + $expectedResponse = new OptimizeToursResponse(); + $expectedResponse->setRequestLabel($requestLabel); + $expectedResponse->setTotalCost($totalCost); + $transport->addResponse($expectedResponse); + // Mock request + $parent = 'parent-995424086'; + $request = (new OptimizeToursRequest()) + ->setParent($parent); + $response = $gapicClient->optimizeTours($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.optimization.v1.FleetRouting/OptimizeTours', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($parent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function optimizeToursExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $parent = 'parent-995424086'; + $request = (new OptimizeToursRequest()) + ->setParent($parent); + try { + $gapicClient->optimizeTours($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function batchOptimizeToursAsyncTest() + { + $operationsTransport = $this->createTransport(); + $operationsClient = new OperationsClient([ + 'apiEndpoint' => '', + 'transport' => $operationsTransport, + 'credentials' => $this->createCredentials(), + ]); + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + 'operationsClient' => $operationsClient, + ]); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + // Mock response + $incompleteOperation = new Operation(); + $incompleteOperation->setName('operations/batchOptimizeToursTest'); + $incompleteOperation->setDone(false); + $transport->addResponse($incompleteOperation); + $expectedResponse = new BatchOptimizeToursResponse(); + $anyResponse = new Any(); + $anyResponse->setValue($expectedResponse->serializeToString()); + $completeOperation = new Operation(); + $completeOperation->setName('operations/batchOptimizeToursTest'); + $completeOperation->setDone(true); + $completeOperation->setResponse($anyResponse); + $operationsTransport->addResponse($completeOperation); + // Mock request + $parent = 'parent-995424086'; + $modelConfigs = []; + $request = (new BatchOptimizeToursRequest()) + ->setParent($parent) + ->setModelConfigs($modelConfigs); + $response = $gapicClient->batchOptimizeToursAsync($request)->wait(); + $this->assertFalse($response->isDone()); + $this->assertNull($response->getResult()); + $apiRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($apiRequests)); + $operationsRequestsEmpty = $operationsTransport->popReceivedCalls(); + $this->assertSame(0, count($operationsRequestsEmpty)); + $actualApiFuncCall = $apiRequests[0]->getFuncCall(); + $actualApiRequestObject = $apiRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.optimization.v1.FleetRouting/BatchOptimizeTours', $actualApiFuncCall); + $actualValue = $actualApiRequestObject->getParent(); + $this->assertProtobufEquals($parent, $actualValue); + $actualValue = $actualApiRequestObject->getModelConfigs(); + $this->assertProtobufEquals($modelConfigs, $actualValue); + $expectedOperationsRequestObject = new GetOperationRequest(); + $expectedOperationsRequestObject->setName('operations/batchOptimizeToursTest'); + $response->pollUntilComplete([ + 'initialPollDelayMillis' => 1, + ]); + $this->assertTrue($response->isDone()); + $this->assertEquals($expectedResponse, $response->getResult()); + $apiRequestsEmpty = $transport->popReceivedCalls(); + $this->assertSame(0, count($apiRequestsEmpty)); + $operationsRequests = $operationsTransport->popReceivedCalls(); + $this->assertSame(1, count($operationsRequests)); + $actualOperationsFuncCall = $operationsRequests[0]->getFuncCall(); + $actualOperationsRequestObject = $operationsRequests[0]->getRequestObject(); + $this->assertSame('/google.longrunning.Operations/GetOperation', $actualOperationsFuncCall); + $this->assertEquals($expectedOperationsRequestObject, $actualOperationsRequestObject); + $this->assertTrue($transport->isExhausted()); + $this->assertTrue($operationsTransport->isExhausted()); + } +} diff --git a/OrgPolicy/samples/V2/OrgPolicyClient/create_policy.php b/OrgPolicy/samples/V2/OrgPolicyClient/create_policy.php index f430b288276b..6e55ef210812 100644 --- a/OrgPolicy/samples/V2/OrgPolicyClient/create_policy.php +++ b/OrgPolicy/samples/V2/OrgPolicyClient/create_policy.php @@ -24,7 +24,8 @@ // [START orgpolicy_v2_generated_OrgPolicy_CreatePolicy_sync] use Google\ApiCore\ApiException; -use Google\Cloud\OrgPolicy\V2\OrgPolicyClient; +use Google\Cloud\OrgPolicy\V2\Client\OrgPolicyClient; +use Google\Cloud\OrgPolicy\V2\CreatePolicyRequest; use Google\Cloud\OrgPolicy\V2\Policy; /** @@ -48,13 +49,16 @@ function create_policy_sample(string $formattedParent): void // Create a client. $orgPolicyClient = new OrgPolicyClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $policy = new Policy(); + $request = (new CreatePolicyRequest()) + ->setParent($formattedParent) + ->setPolicy($policy); // Call the API and handle any network failures. try { /** @var Policy $response */ - $response = $orgPolicyClient->createPolicy($formattedParent, $policy); + $response = $orgPolicyClient->createPolicy($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/OrgPolicy/samples/V2/OrgPolicyClient/delete_policy.php b/OrgPolicy/samples/V2/OrgPolicyClient/delete_policy.php index b734326e48c4..a09a98ae0092 100644 --- a/OrgPolicy/samples/V2/OrgPolicyClient/delete_policy.php +++ b/OrgPolicy/samples/V2/OrgPolicyClient/delete_policy.php @@ -24,7 +24,8 @@ // [START orgpolicy_v2_generated_OrgPolicy_DeletePolicy_sync] use Google\ApiCore\ApiException; -use Google\Cloud\OrgPolicy\V2\OrgPolicyClient; +use Google\Cloud\OrgPolicy\V2\Client\OrgPolicyClient; +use Google\Cloud\OrgPolicy\V2\DeletePolicyRequest; /** * Deletes a Policy. @@ -41,9 +42,13 @@ function delete_policy_sample(string $formattedName): void // Create a client. $orgPolicyClient = new OrgPolicyClient(); + // Prepare the request message. + $request = (new DeletePolicyRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { - $orgPolicyClient->deletePolicy($formattedName); + $orgPolicyClient->deletePolicy($request); printf('Call completed successfully.' . PHP_EOL); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/OrgPolicy/samples/V2/OrgPolicyClient/get_effective_policy.php b/OrgPolicy/samples/V2/OrgPolicyClient/get_effective_policy.php index df1e94d112ca..4925e4114f96 100644 --- a/OrgPolicy/samples/V2/OrgPolicyClient/get_effective_policy.php +++ b/OrgPolicy/samples/V2/OrgPolicyClient/get_effective_policy.php @@ -24,7 +24,8 @@ // [START orgpolicy_v2_generated_OrgPolicy_GetEffectivePolicy_sync] use Google\ApiCore\ApiException; -use Google\Cloud\OrgPolicy\V2\OrgPolicyClient; +use Google\Cloud\OrgPolicy\V2\Client\OrgPolicyClient; +use Google\Cloud\OrgPolicy\V2\GetEffectivePolicyRequest; use Google\Cloud\OrgPolicy\V2\Policy; /** @@ -43,10 +44,14 @@ function get_effective_policy_sample(string $formattedName): void // Create a client. $orgPolicyClient = new OrgPolicyClient(); + // Prepare the request message. + $request = (new GetEffectivePolicyRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var Policy $response */ - $response = $orgPolicyClient->getEffectivePolicy($formattedName); + $response = $orgPolicyClient->getEffectivePolicy($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/OrgPolicy/samples/V2/OrgPolicyClient/get_policy.php b/OrgPolicy/samples/V2/OrgPolicyClient/get_policy.php index 44bd33c2c17a..bc0550fb0efe 100644 --- a/OrgPolicy/samples/V2/OrgPolicyClient/get_policy.php +++ b/OrgPolicy/samples/V2/OrgPolicyClient/get_policy.php @@ -24,7 +24,8 @@ // [START orgpolicy_v2_generated_OrgPolicy_GetPolicy_sync] use Google\ApiCore\ApiException; -use Google\Cloud\OrgPolicy\V2\OrgPolicyClient; +use Google\Cloud\OrgPolicy\V2\Client\OrgPolicyClient; +use Google\Cloud\OrgPolicy\V2\GetPolicyRequest; use Google\Cloud\OrgPolicy\V2\Policy; /** @@ -43,10 +44,14 @@ function get_policy_sample(string $formattedName): void // Create a client. $orgPolicyClient = new OrgPolicyClient(); + // Prepare the request message. + $request = (new GetPolicyRequest()) + ->setName($formattedName); + // Call the API and handle any network failures. try { /** @var Policy $response */ - $response = $orgPolicyClient->getPolicy($formattedName); + $response = $orgPolicyClient->getPolicy($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/OrgPolicy/samples/V2/OrgPolicyClient/list_constraints.php b/OrgPolicy/samples/V2/OrgPolicyClient/list_constraints.php index f966447ea0e8..af3e07627aea 100644 --- a/OrgPolicy/samples/V2/OrgPolicyClient/list_constraints.php +++ b/OrgPolicy/samples/V2/OrgPolicyClient/list_constraints.php @@ -25,8 +25,9 @@ // [START orgpolicy_v2_generated_OrgPolicy_ListConstraints_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; +use Google\Cloud\OrgPolicy\V2\Client\OrgPolicyClient; use Google\Cloud\OrgPolicy\V2\Constraint; -use Google\Cloud\OrgPolicy\V2\OrgPolicyClient; +use Google\Cloud\OrgPolicy\V2\ListConstraintsRequest; /** * Lists `Constraints` that could be applied on the specified resource. @@ -44,10 +45,14 @@ function list_constraints_sample(string $formattedParent): void // Create a client. $orgPolicyClient = new OrgPolicyClient(); + // Prepare the request message. + $request = (new ListConstraintsRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $orgPolicyClient->listConstraints($formattedParent); + $response = $orgPolicyClient->listConstraints($request); /** @var Constraint $element */ foreach ($response as $element) { diff --git a/OrgPolicy/samples/V2/OrgPolicyClient/list_policies.php b/OrgPolicy/samples/V2/OrgPolicyClient/list_policies.php index 9ecbaeb7c438..42ab3a5f079e 100644 --- a/OrgPolicy/samples/V2/OrgPolicyClient/list_policies.php +++ b/OrgPolicy/samples/V2/OrgPolicyClient/list_policies.php @@ -25,7 +25,8 @@ // [START orgpolicy_v2_generated_OrgPolicy_ListPolicies_sync] use Google\ApiCore\ApiException; use Google\ApiCore\PagedListResponse; -use Google\Cloud\OrgPolicy\V2\OrgPolicyClient; +use Google\Cloud\OrgPolicy\V2\Client\OrgPolicyClient; +use Google\Cloud\OrgPolicy\V2\ListPoliciesRequest; use Google\Cloud\OrgPolicy\V2\Policy; /** @@ -45,10 +46,14 @@ function list_policies_sample(string $formattedParent): void // Create a client. $orgPolicyClient = new OrgPolicyClient(); + // Prepare the request message. + $request = (new ListPoliciesRequest()) + ->setParent($formattedParent); + // Call the API and handle any network failures. try { /** @var PagedListResponse $response */ - $response = $orgPolicyClient->listPolicies($formattedParent); + $response = $orgPolicyClient->listPolicies($request); /** @var Policy $element */ foreach ($response as $element) { diff --git a/OrgPolicy/samples/V2/OrgPolicyClient/update_policy.php b/OrgPolicy/samples/V2/OrgPolicyClient/update_policy.php index 73330374579c..9a8033d36502 100644 --- a/OrgPolicy/samples/V2/OrgPolicyClient/update_policy.php +++ b/OrgPolicy/samples/V2/OrgPolicyClient/update_policy.php @@ -24,8 +24,9 @@ // [START orgpolicy_v2_generated_OrgPolicy_UpdatePolicy_sync] use Google\ApiCore\ApiException; -use Google\Cloud\OrgPolicy\V2\OrgPolicyClient; +use Google\Cloud\OrgPolicy\V2\Client\OrgPolicyClient; use Google\Cloud\OrgPolicy\V2\Policy; +use Google\Cloud\OrgPolicy\V2\UpdatePolicyRequest; /** * Updates a Policy. @@ -49,13 +50,15 @@ function update_policy_sample(): void // Create a client. $orgPolicyClient = new OrgPolicyClient(); - // Prepare any non-scalar elements to be passed along with the request. + // Prepare the request message. $policy = new Policy(); + $request = (new UpdatePolicyRequest()) + ->setPolicy($policy); // Call the API and handle any network failures. try { /** @var Policy $response */ - $response = $orgPolicyClient->updatePolicy($policy); + $response = $orgPolicyClient->updatePolicy($request); printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString()); } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); diff --git a/OrgPolicy/src/V2/Client/BaseClient/OrgPolicyBaseClient.php b/OrgPolicy/src/V2/Client/BaseClient/OrgPolicyBaseClient.php new file mode 100644 index 000000000000..c2eee64f092c --- /dev/null +++ b/OrgPolicy/src/V2/Client/BaseClient/OrgPolicyBaseClient.php @@ -0,0 +1,535 @@ + self::SERVICE_NAME, + 'apiEndpoint' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT, + 'clientConfig' => __DIR__ . '/../../resources/org_policy_client_config.json', + 'descriptorsConfigPath' => __DIR__ . '/../../resources/org_policy_descriptor_config.php', + 'gcpApiConfigPath' => __DIR__ . '/../../resources/org_policy_grpc_config.json', + 'credentialsConfig' => [ + 'defaultScopes' => self::$serviceScopes, + ], + 'transportConfig' => [ + 'rest' => [ + 'restClientConfigPath' => __DIR__ . '/../../resources/org_policy_rest_client_config.php', + ], + ], + ]; + } + + /** + * Formats a string containing the fully-qualified path to represent a folder + * resource. + * + * @param string $folder + * + * @return string The formatted folder resource. + */ + public static function folderName(string $folder): string + { + return self::getPathTemplate('folder')->render([ + 'folder' => $folder, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * folder_policy resource. + * + * @param string $folder + * @param string $policy + * + * @return string The formatted folder_policy resource. + */ + public static function folderPolicyName(string $folder, string $policy): string + { + return self::getPathTemplate('folderPolicy')->render([ + 'folder' => $folder, + 'policy' => $policy, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a organization + * resource. + * + * @param string $organization + * + * @return string The formatted organization resource. + */ + public static function organizationName(string $organization): string + { + return self::getPathTemplate('organization')->render([ + 'organization' => $organization, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * organization_policy resource. + * + * @param string $organization + * @param string $policy + * + * @return string The formatted organization_policy resource. + */ + public static function organizationPolicyName(string $organization, string $policy): string + { + return self::getPathTemplate('organizationPolicy')->render([ + 'organization' => $organization, + 'policy' => $policy, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a policy + * resource. + * + * @param string $project + * @param string $policy + * + * @return string The formatted policy resource. + */ + public static function policyName(string $project, string $policy): string + { + return self::getPathTemplate('policy')->render([ + 'project' => $project, + 'policy' => $policy, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a project + * resource. + * + * @param string $project + * + * @return string The formatted project resource. + */ + public static function projectName(string $project): string + { + return self::getPathTemplate('project')->render([ + 'project' => $project, + ]); + } + + /** + * Formats a string containing the fully-qualified path to represent a + * project_policy resource. + * + * @param string $project + * @param string $policy + * + * @return string The formatted project_policy resource. + */ + public static function projectPolicyName(string $project, string $policy): string + { + return self::getPathTemplate('projectPolicy')->render([ + 'project' => $project, + 'policy' => $policy, + ]); + } + + /** + * Parses a formatted name string and returns an associative array of the components in the name. + * The following name formats are supported: + * Template: Pattern + * - folder: folders/{folder} + * - folderPolicy: folders/{folder}/policies/{policy} + * - organization: organizations/{organization} + * - organizationPolicy: organizations/{organization}/policies/{policy} + * - policy: projects/{project}/policies/{policy} + * - project: projects/{project} + * - projectPolicy: projects/{project}/policies/{policy} + * + * The optional $template argument can be supplied to specify a particular pattern, + * and must match one of the templates listed above. If no $template argument is + * provided, or if the $template argument does not match one of the templates + * listed, then parseName will check each of the supported templates, and return + * the first match. + * + * @param string $formattedName The formatted name string + * @param string $template Optional name of template to match + * + * @return array An associative array from name component IDs to component values. + * + * @throws ValidationException If $formattedName could not be matched. + */ + public static function parseName(string $formattedName, string $template = null): array + { + return self::parseFormattedName($formattedName, $template); + } + + /** + * Constructor. + * + * @param array $options { + * Optional. Options for configuring the service API wrapper. + * + * @type string $apiEndpoint + * The address of the API remote host. May optionally include the port, formatted + * as ":". Default 'orgpolicy.googleapis.com:443'. + * @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials + * The credentials to be used by the client to authorize API calls. This option + * accepts either a path to a credentials file, or a decoded credentials file as a + * PHP array. + * *Advanced usage*: In addition, this option can also accept a pre-constructed + * {@see \Google\Auth\FetchAuthTokenInterface} object or + * {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these + * objects are provided, any settings in $credentialsConfig will be ignored. + * @type array $credentialsConfig + * Options used to configure credentials, including auth token caching, for the + * client. For a full list of supporting configuration options, see + * {@see \Google\ApiCore\CredentialsWrapper::build()} . + * @type bool $disableRetries + * Determines whether or not retries defined by the client configuration should be + * disabled. Defaults to `false`. + * @type string|array $clientConfig + * Client method configuration, including retry settings. This option can be either + * a path to a JSON file, or a PHP array containing the decoded JSON data. By + * default this settings points to the default client config file, which is + * provided in the resources folder. + * @type string|TransportInterface $transport + * The transport used for executing network requests. May be either the string + * `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system. + * *Advanced usage*: Additionally, it is possible to pass in an already + * instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note + * that when this object is provided, any settings in $transportConfig, and any + * $apiEndpoint setting, will be ignored. + * @type array $transportConfig + * Configuration options that will be used to construct the transport. Options for + * each supported transport type should be passed in a key for that transport. For + * example: + * $transportConfig = [ + * 'grpc' => [...], + * 'rest' => [...], + * ]; + * See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and + * {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the + * supported options. + * @type callable $clientCertSource + * A callable which returns the client cert as a string. This can be used to + * provide a certificate and private key to the transport layer for mTLS. + * } + * + * @throws ValidationException + */ + public function __construct(array $options = []) + { + $clientOptions = $this->buildClientOptions($options); + $this->setClientOptions($clientOptions); + } + + /** Handles execution of the async variants for each documented method. */ + public function __call($method, $args) + { + if (substr($method, -5) !== 'Async') { + trigger_error('Call to undefined method ' . __CLASS__ . "::$method()", E_USER_ERROR); + } + + array_unshift($args, substr($method, 0, -5)); + return call_user_func_array([$this, 'startAsyncCall'], $args); + } + + /** + * Creates a Policy. + * + * Returns a `google.rpc.Status` with `google.rpc.Code.NOT_FOUND` if the + * constraint does not exist. + * Returns a `google.rpc.Status` with `google.rpc.Code.ALREADY_EXISTS` if the + * policy already exists on the given Cloud resource. + * + * The async variant is {@see self::createPolicyAsync()} . + * + * @param CreatePolicyRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Policy + * + * @throws ApiException Thrown if the API call fails. + */ + public function createPolicy(CreatePolicyRequest $request, array $callOptions = []): Policy + { + return $this->startApiCall('CreatePolicy', $request, $callOptions)->wait(); + } + + /** + * Deletes a Policy. + * + * Returns a `google.rpc.Status` with `google.rpc.Code.NOT_FOUND` if the + * constraint or Org Policy does not exist. + * + * The async variant is {@see self::deletePolicyAsync()} . + * + * @param DeletePolicyRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @throws ApiException Thrown if the API call fails. + */ + public function deletePolicy(DeletePolicyRequest $request, array $callOptions = []): void + { + $this->startApiCall('DeletePolicy', $request, $callOptions)->wait(); + } + + /** + * Gets the effective `Policy` on a resource. This is the result of merging + * `Policies` in the resource hierarchy and evaluating conditions. The + * returned `Policy` will not have an `etag` or `condition` set because it is + * a computed `Policy` across multiple resources. + * Subtrees of Resource Manager resource hierarchy with 'under:' prefix will + * not be expanded. + * + * The async variant is {@see self::getEffectivePolicyAsync()} . + * + * @param GetEffectivePolicyRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Policy + * + * @throws ApiException Thrown if the API call fails. + */ + public function getEffectivePolicy(GetEffectivePolicyRequest $request, array $callOptions = []): Policy + { + return $this->startApiCall('GetEffectivePolicy', $request, $callOptions)->wait(); + } + + /** + * Gets a `Policy` on a resource. + * + * If no `Policy` is set on the resource, NOT_FOUND is returned. The + * `etag` value can be used with `UpdatePolicy()` to update a + * `Policy` during read-modify-write. + * + * The async variant is {@see self::getPolicyAsync()} . + * + * @param GetPolicyRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Policy + * + * @throws ApiException Thrown if the API call fails. + */ + public function getPolicy(GetPolicyRequest $request, array $callOptions = []): Policy + { + return $this->startApiCall('GetPolicy', $request, $callOptions)->wait(); + } + + /** + * Lists `Constraints` that could be applied on the specified resource. + * + * The async variant is {@see self::listConstraintsAsync()} . + * + * @param ListConstraintsRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listConstraints(ListConstraintsRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListConstraints', $request, $callOptions); + } + + /** + * Retrieves all of the `Policies` that exist on a particular resource. + * + * The async variant is {@see self::listPoliciesAsync()} . + * + * @param ListPoliciesRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return PagedListResponse + * + * @throws ApiException Thrown if the API call fails. + */ + public function listPolicies(ListPoliciesRequest $request, array $callOptions = []): PagedListResponse + { + return $this->startApiCall('ListPolicies', $request, $callOptions); + } + + /** + * Updates a Policy. + * + * Returns a `google.rpc.Status` with `google.rpc.Code.NOT_FOUND` if the + * constraint or the policy do not exist. + * Returns a `google.rpc.Status` with `google.rpc.Code.ABORTED` if the etag + * supplied in the request does not match the persisted etag of the policy + * + * Note: the supplied policy will perform a full overwrite of all + * fields. + * + * The async variant is {@see self::updatePolicyAsync()} . + * + * @param UpdatePolicyRequest $request A request to house fields associated with the call. + * @param array $callOptions { + * Optional. + * + * @type RetrySettings|array $retrySettings + * Retry settings to use for this call. Can be a {@see RetrySettings} object, or an + * associative array of retry settings parameters. See the documentation on + * {@see RetrySettings} for example usage. + * } + * + * @return Policy + * + * @throws ApiException Thrown if the API call fails. + */ + public function updatePolicy(UpdatePolicyRequest $request, array $callOptions = []): Policy + { + return $this->startApiCall('UpdatePolicy', $request, $callOptions)->wait(); + } +} diff --git a/OrgPolicy/src/V2/Client/OrgPolicyClient.php b/OrgPolicy/src/V2/Client/OrgPolicyClient.php new file mode 100644 index 000000000000..a23a2cdf9f96 --- /dev/null +++ b/OrgPolicy/src/V2/Client/OrgPolicyClient.php @@ -0,0 +1,40 @@ +setParent($parent) + ->setPolicy($policy); + } + /** * Constructor. * diff --git a/OrgPolicy/src/V2/DeletePolicyRequest.php b/OrgPolicy/src/V2/DeletePolicyRequest.php index 47de5eec28d3..d1646ee85034 100644 --- a/OrgPolicy/src/V2/DeletePolicyRequest.php +++ b/OrgPolicy/src/V2/DeletePolicyRequest.php @@ -24,6 +24,21 @@ class DeletePolicyRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. Name of the policy to delete. + * See `Policy` for naming rules. Please see + * {@see OrgPolicyClient::policyName()} for help formatting this field. + * + * @return \Google\Cloud\OrgPolicy\V2\DeletePolicyRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/OrgPolicy/src/V2/GetEffectivePolicyRequest.php b/OrgPolicy/src/V2/GetEffectivePolicyRequest.php index ad232266f755..1a4ab8c966be 100644 --- a/OrgPolicy/src/V2/GetEffectivePolicyRequest.php +++ b/OrgPolicy/src/V2/GetEffectivePolicyRequest.php @@ -23,6 +23,20 @@ class GetEffectivePolicyRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. The effective policy to compute. See `Policy` for naming rules. Please see + * {@see OrgPolicyClient::policyName()} for help formatting this field. + * + * @return \Google\Cloud\OrgPolicy\V2\GetEffectivePolicyRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/OrgPolicy/src/V2/GetPolicyRequest.php b/OrgPolicy/src/V2/GetPolicyRequest.php index a13495c6f297..0c88a30d4306 100644 --- a/OrgPolicy/src/V2/GetPolicyRequest.php +++ b/OrgPolicy/src/V2/GetPolicyRequest.php @@ -24,6 +24,21 @@ class GetPolicyRequest extends \Google\Protobuf\Internal\Message */ private $name = ''; + /** + * @param string $name Required. Resource name of the policy. See `Policy` for naming + * requirements. Please see + * {@see OrgPolicyClient::policyName()} for help formatting this field. + * + * @return \Google\Cloud\OrgPolicy\V2\GetPolicyRequest + * + * @experimental + */ + public static function build(string $name): self + { + return (new self()) + ->setName($name); + } + /** * Constructor. * diff --git a/OrgPolicy/src/V2/ListConstraintsRequest.php b/OrgPolicy/src/V2/ListConstraintsRequest.php index 52b51c1ef1ef..1890089f99b7 100644 --- a/OrgPolicy/src/V2/ListConstraintsRequest.php +++ b/OrgPolicy/src/V2/ListConstraintsRequest.php @@ -43,6 +43,25 @@ class ListConstraintsRequest extends \Google\Protobuf\Internal\Message */ private $page_token = ''; + /** + * @param string $parent Required. The Cloud resource that parents the constraint. Must be in one of + * the following forms: + * * `projects/{project_number}` + * * `projects/{project_id}` + * * `folders/{folder_id}` + * * `organizations/{organization_id}` + * Please see {@see OrgPolicyClient::projectName()} for help formatting this field. + * + * @return \Google\Cloud\OrgPolicy\V2\ListConstraintsRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/OrgPolicy/src/V2/ListPoliciesRequest.php b/OrgPolicy/src/V2/ListPoliciesRequest.php index 236d82a38af1..52bee3d9971b 100644 --- a/OrgPolicy/src/V2/ListPoliciesRequest.php +++ b/OrgPolicy/src/V2/ListPoliciesRequest.php @@ -44,6 +44,26 @@ class ListPoliciesRequest extends \Google\Protobuf\Internal\Message */ private $page_token = ''; + /** + * @param string $parent Required. The target Cloud resource that parents the set of constraints and + * policies that will be returned from this call. Must be in one of the + * following forms: + * * `projects/{project_number}` + * * `projects/{project_id}` + * * `folders/{folder_id}` + * * `organizations/{organization_id}` + * Please see {@see OrgPolicyClient::projectName()} for help formatting this field. + * + * @return \Google\Cloud\OrgPolicy\V2\ListPoliciesRequest + * + * @experimental + */ + public static function build(string $parent): self + { + return (new self()) + ->setParent($parent); + } + /** * Constructor. * diff --git a/OrgPolicy/src/V2/UpdatePolicyRequest.php b/OrgPolicy/src/V2/UpdatePolicyRequest.php index 0125f02d6c1e..b6dbfc44efc4 100644 --- a/OrgPolicy/src/V2/UpdatePolicyRequest.php +++ b/OrgPolicy/src/V2/UpdatePolicyRequest.php @@ -31,6 +31,19 @@ class UpdatePolicyRequest extends \Google\Protobuf\Internal\Message */ private $update_mask = null; + /** + * @param \Google\Cloud\OrgPolicy\V2\Policy $policy Required. `Policy` to update. + * + * @return \Google\Cloud\OrgPolicy\V2\UpdatePolicyRequest + * + * @experimental + */ + public static function build(\Google\Cloud\OrgPolicy\V2\Policy $policy): self + { + return (new self()) + ->setPolicy($policy); + } + /** * Constructor. * diff --git a/OrgPolicy/src/V2/resources/org_policy_descriptor_config.php b/OrgPolicy/src/V2/resources/org_policy_descriptor_config.php index 599ef46233c2..dd905f50efbb 100644 --- a/OrgPolicy/src/V2/resources/org_policy_descriptor_config.php +++ b/OrgPolicy/src/V2/resources/org_policy_descriptor_config.php @@ -3,6 +3,54 @@ return [ 'interfaces' => [ 'google.cloud.orgpolicy.v2.OrgPolicy' => [ + 'CreatePolicy' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\OrgPolicy\V2\Policy', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'DeletePolicy' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Protobuf\GPBEmpty', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetEffectivePolicy' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\OrgPolicy\V2\Policy', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], + 'GetPolicy' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\OrgPolicy\V2\Policy', + 'headerParams' => [ + [ + 'keyName' => 'name', + 'fieldAccessors' => [ + 'getName', + ], + ], + ], + ], 'ListConstraints' => [ 'pageStreaming' => [ 'requestPageTokenGetMethod' => 'getPageToken', @@ -12,6 +60,16 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getConstraints', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\OrgPolicy\V2\ListConstraintsResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], ], 'ListPolicies' => [ 'pageStreaming' => [ @@ -22,6 +80,38 @@ 'responsePageTokenGetMethod' => 'getNextPageToken', 'resourcesGetMethod' => 'getPolicies', ], + 'callType' => \Google\ApiCore\Call::PAGINATED_CALL, + 'responseType' => 'Google\Cloud\OrgPolicy\V2\ListPoliciesResponse', + 'headerParams' => [ + [ + 'keyName' => 'parent', + 'fieldAccessors' => [ + 'getParent', + ], + ], + ], + ], + 'UpdatePolicy' => [ + 'callType' => \Google\ApiCore\Call::UNARY_CALL, + 'responseType' => 'Google\Cloud\OrgPolicy\V2\Policy', + 'headerParams' => [ + [ + 'keyName' => 'policy.name', + 'fieldAccessors' => [ + 'getPolicy', + 'getName', + ], + ], + ], + ], + 'templateMap' => [ + 'folder' => 'folders/{folder}', + 'folderPolicy' => 'folders/{folder}/policies/{policy}', + 'organization' => 'organizations/{organization}', + 'organizationPolicy' => 'organizations/{organization}/policies/{policy}', + 'policy' => 'projects/{project}/policies/{policy}', + 'project' => 'projects/{project}', + 'projectPolicy' => 'projects/{project}/policies/{policy}', ], ], ], diff --git a/OrgPolicy/tests/Unit/V2/Client/OrgPolicyClientTest.php b/OrgPolicy/tests/Unit/V2/Client/OrgPolicyClientTest.php new file mode 100644 index 000000000000..494e1a9c0168 --- /dev/null +++ b/OrgPolicy/tests/Unit/V2/Client/OrgPolicyClientTest.php @@ -0,0 +1,572 @@ +getMockBuilder(CredentialsWrapper::class)->disableOriginalConstructor()->getMock(); + } + + /** @return OrgPolicyClient */ + private function createClient(array $options = []) + { + $options += [ + 'credentials' => $this->createCredentials(), + ]; + return new OrgPolicyClient($options); + } + + /** @test */ + public function createPolicyTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name = 'name3373707'; + $expectedResponse = new Policy(); + $expectedResponse->setName($name); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $policy = new Policy(); + $request = (new CreatePolicyRequest()) + ->setParent($formattedParent) + ->setPolicy($policy); + $response = $gapicClient->createPolicy($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.orgpolicy.v2.OrgPolicy/CreatePolicy', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualRequestObject->getPolicy(); + $this->assertProtobufEquals($policy, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createPolicyExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $policy = new Policy(); + $request = (new CreatePolicyRequest()) + ->setParent($formattedParent) + ->setPolicy($policy); + try { + $gapicClient->createPolicy($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function deletePolicyTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $expectedResponse = new GPBEmpty(); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->policyName('[PROJECT]', '[POLICY]'); + $request = (new DeletePolicyRequest()) + ->setName($formattedName); + $gapicClient->deletePolicy($request); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.orgpolicy.v2.OrgPolicy/DeletePolicy', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function deletePolicyExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->policyName('[PROJECT]', '[POLICY]'); + $request = (new DeletePolicyRequest()) + ->setName($formattedName); + try { + $gapicClient->deletePolicy($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getEffectivePolicyTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $expectedResponse = new Policy(); + $expectedResponse->setName($name2); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->policyName('[PROJECT]', '[POLICY]'); + $request = (new GetEffectivePolicyRequest()) + ->setName($formattedName); + $response = $gapicClient->getEffectivePolicy($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.orgpolicy.v2.OrgPolicy/GetEffectivePolicy', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getEffectivePolicyExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->policyName('[PROJECT]', '[POLICY]'); + $request = (new GetEffectivePolicyRequest()) + ->setName($formattedName); + try { + $gapicClient->getEffectivePolicy($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getPolicyTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name2 = 'name2-1052831874'; + $expectedResponse = new Policy(); + $expectedResponse->setName($name2); + $transport->addResponse($expectedResponse); + // Mock request + $formattedName = $gapicClient->policyName('[PROJECT]', '[POLICY]'); + $request = (new GetPolicyRequest()) + ->setName($formattedName); + $response = $gapicClient->getPolicy($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.orgpolicy.v2.OrgPolicy/GetPolicy', $actualFuncCall); + $actualValue = $actualRequestObject->getName(); + $this->assertProtobufEquals($formattedName, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function getPolicyExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedName = $gapicClient->policyName('[PROJECT]', '[POLICY]'); + $request = (new GetPolicyRequest()) + ->setName($formattedName); + try { + $gapicClient->getPolicy($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listConstraintsTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $constraintsElement = new Constraint(); + $constraints = [ + $constraintsElement, + ]; + $expectedResponse = new ListConstraintsResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setConstraints($constraints); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $request = (new ListConstraintsRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listConstraints($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getConstraints()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.orgpolicy.v2.OrgPolicy/ListConstraints', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listConstraintsExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $request = (new ListConstraintsRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listConstraints($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listPoliciesTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $nextPageToken = ''; + $policiesElement = new Policy(); + $policies = [ + $policiesElement, + ]; + $expectedResponse = new ListPoliciesResponse(); + $expectedResponse->setNextPageToken($nextPageToken); + $expectedResponse->setPolicies($policies); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $request = (new ListPoliciesRequest()) + ->setParent($formattedParent); + $response = $gapicClient->listPolicies($request); + $this->assertEquals($expectedResponse, $response->getPage()->getResponseObject()); + $resources = iterator_to_array($response->iterateAllElements()); + $this->assertSame(1, count($resources)); + $this->assertEquals($expectedResponse->getPolicies()[0], $resources[0]); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.orgpolicy.v2.OrgPolicy/ListPolicies', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function listPoliciesExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $request = (new ListPoliciesRequest()) + ->setParent($formattedParent); + try { + $gapicClient->listPolicies($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function updatePolicyTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name = 'name3373707'; + $expectedResponse = new Policy(); + $expectedResponse->setName($name); + $transport->addResponse($expectedResponse); + // Mock request + $policy = new Policy(); + $request = (new UpdatePolicyRequest()) + ->setPolicy($policy); + $response = $gapicClient->updatePolicy($request); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.orgpolicy.v2.OrgPolicy/UpdatePolicy', $actualFuncCall); + $actualValue = $actualRequestObject->getPolicy(); + $this->assertProtobufEquals($policy, $actualValue); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function updatePolicyExceptionTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + $status = new stdClass(); + $status->code = Code::DATA_LOSS; + $status->details = 'internal error'; + $expectedExceptionMessage = json_encode([ + 'message' => 'internal error', + 'code' => Code::DATA_LOSS, + 'status' => 'DATA_LOSS', + 'details' => [], + ], JSON_PRETTY_PRINT); + $transport->addResponse(null, $status); + // Mock request + $policy = new Policy(); + $request = (new UpdatePolicyRequest()) + ->setPolicy($policy); + try { + $gapicClient->updatePolicy($request); + // If the $gapicClient method call did not throw, fail the test + $this->fail('Expected an ApiException, but no exception was thrown.'); + } catch (ApiException $ex) { + $this->assertEquals($status->code, $ex->getCode()); + $this->assertEquals($expectedExceptionMessage, $ex->getMessage()); + } + // Call popReceivedCalls to ensure the stub is exhausted + $transport->popReceivedCalls(); + $this->assertTrue($transport->isExhausted()); + } + + /** @test */ + public function createPolicyAsyncTest() + { + $transport = $this->createTransport(); + $gapicClient = $this->createClient([ + 'transport' => $transport, + ]); + $this->assertTrue($transport->isExhausted()); + // Mock response + $name = 'name3373707'; + $expectedResponse = new Policy(); + $expectedResponse->setName($name); + $transport->addResponse($expectedResponse); + // Mock request + $formattedParent = $gapicClient->projectName('[PROJECT]'); + $policy = new Policy(); + $request = (new CreatePolicyRequest()) + ->setParent($formattedParent) + ->setPolicy($policy); + $response = $gapicClient->createPolicyAsync($request)->wait(); + $this->assertEquals($expectedResponse, $response); + $actualRequests = $transport->popReceivedCalls(); + $this->assertSame(1, count($actualRequests)); + $actualFuncCall = $actualRequests[0]->getFuncCall(); + $actualRequestObject = $actualRequests[0]->getRequestObject(); + $this->assertSame('/google.cloud.orgpolicy.v2.OrgPolicy/CreatePolicy', $actualFuncCall); + $actualValue = $actualRequestObject->getParent(); + $this->assertProtobufEquals($formattedParent, $actualValue); + $actualValue = $actualRequestObject->getPolicy(); + $this->assertProtobufEquals($policy, $actualValue); + $this->assertTrue($transport->isExhausted()); + } +}