feat(tools/alloydb-list-cluster): Add custom tool kind for AlloyDB list_clusters (#1319)

## Description
---
This pull request introduces a new custom tool kind
`alloydb-list-clusters` that lists all AlloyDB clusters in a given
project and location.

### Example Configuration

```yaml
tools:
  list_clusters:
    kind: alloydb-list-clusters
    source: alloydb-admin-source
    description: Use this tool to list all AlloyDB clusters in a given project and location.
```

### Example Request
``` 
curl -X POST http://127.0.0.1:5000/api/tool/list_clusters/invoke \
-H "Content-Type: application/json" \
-d '{
    "projectId": "example-project",
    "locationId": "us-central1"
}'
```

## PR Checklist
---
> Thank you for opening a Pull Request! Before submitting your PR, there
are a
> few things you can do to make sure it goes smoothly:
- [x] Make sure you reviewed

[CONTRIBUTING.md](https://github.com/googleapis/genai-toolbox/blob/main/CONTRIBUTING.md)
- [ ] Make sure to open an issue as a

[bug/issue](https://github.com/googleapis/langchain-google-alloydb-pg-python/issues/new/choose)
before writing your code! That way we can discuss the change, evaluate
  designs, and agree on the general idea
- [x] Ensure the tests and linter pass
- [x] Code coverage does not decrease (if any source code was changed)
- [x] Appropriate docs were updated (if necessary)
- [x] Make sure to add `!` if this involve a breaking change

🛠️ Fixes #<issue_number_goes_here>

---------

Co-authored-by: Averi Kitsch <akitsch@google.com>
This commit is contained in:
Sri Varshitha
2025-09-12 02:33:17 +05:30
committed by GitHub
parent 5530b08f34
commit d4a9eb0ce2
10 changed files with 769 additions and 16 deletions

View File

@@ -62,6 +62,26 @@ steps:
postgressql \
postgresexecutesql
- id: "alloydb"
name: golang:1
waitFor: ["compile-test-binary"]
entrypoint: /bin/bash
env:
- "GOPATH=/gopath"
- "ALLOYDB_PROJECT=$PROJECT_ID"
- "ALLOYDB_CLUSTER=$_ALLOYDB_POSTGRES_CLUSTER"
- "ALLOYDB_REGION=$_REGION"
volumes:
- name: "go"
path: "/gopath"
args:
- -c
- |
.ci/test_with_coverage.sh \
"AlloyDB" \
alloydb \
alloydb
- id: "alloydb-pg"
name: golang:1
waitFor: ["compile-test-binary"]

View File

@@ -43,6 +43,7 @@ import (
// Import tool packages for side effect of registration
_ "github.com/googleapis/genai-toolbox/internal/tools/alloydbainl"
_ "github.com/googleapis/genai-toolbox/internal/tools/alloydb/alloydblistclusters"
_ "github.com/googleapis/genai-toolbox/internal/tools/bigquery/bigqueryanalyzecontribution"
_ "github.com/googleapis/genai-toolbox/internal/tools/bigquery/bigqueryconversationalanalytics"
_ "github.com/googleapis/genai-toolbox/internal/tools/bigquery/bigqueryexecutesql"

View File

@@ -1339,7 +1339,7 @@ func TestPrebuiltTools(t *testing.T) {
wantToolset: server.ToolsetConfigs{
"alloydb-postgres-admin-tools": tools.ToolsetConfig{
Name: "alloydb-postgres-admin-tools",
ToolNames: []string{"alloydb-create-cluster", "alloydb-operations-get", "alloydb-create-instance", "alloydb-list-clusters", "alloydb-list-instances", "alloydb-list-users", "alloydb-create-user"},
ToolNames: []string{"alloydb-create-cluster", "alloydb-operations-get", "alloydb-create-instance", "list_clusters", "alloydb-list-instances", "alloydb-list-users", "alloydb-create-user"},
},
},
},

View File

@@ -0,0 +1,7 @@
---
title: "AlloyDB for PostgreSQL"
type: docs
weight: 1
description: >
Tools for AlloyDB for PostgreSQL.
---

View File

@@ -0,0 +1,38 @@
---
title: "alloydb-list-clusters"
type: docs
weight: 1
description: >
The "alloydb-list-clusters" tool lists the AlloyDB clusters in a given project and location.
aliases:
- /resources/tools/alloydb-list-clusters
---
## About
The `alloydb-list-clusters` tool retrieves AlloyDB cluster information for all or specified locations in a given project. It is compatible with [alloydb-admin](../../sources/alloydb-admin.md) source.
`alloydb-list-clusters` tool lists the detailed information of AlloyDB cluster(cluster name, state, configuration, etc) for a given project and location. The tool takes the following input parameters:
| Parameter | Type | Description | Required |
| :--------- | :----- | :--------------------------------------------------------------------------------------- | :------- |
| `projectId` | string | The GCP project ID to list clusters for. | Yes |
| `locationId` | string | The location to list clusters in (e.g., 'us-central1'). Use `-` for all locations. Default: `-`.| No |
> **Note**
> This tool authenticates using the credentials configured in its [alloydb-admin](../../sources/alloydb-admin.md) source which can be either [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials) or client-side OAuth.
## Example
```yaml
tools:
list_clusters:
kind: alloydb-list-clusters
source: alloydb-admin-source
description: Use this tool to list all AlloyDB clusters in a given project and location.
```
## Reference
| **field** | **type** | **required** | **description** |
|-------------|:------------------------------------------:|:------------:|--------------------------------------------------------------------------------------------------|
| kind | string | true | Must be alloydb-list-clusters. | |
| source | string | true | The name of an `alloydb-admin` source. |
| description | string | true | Description of the tool that is passed to the agent. |

View File

@@ -1,3 +1,17 @@
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
sources:
alloydb-api-source:
kind: http
@@ -5,6 +19,8 @@ sources:
headers:
Authorization: Bearer ${API_KEY}
Content-Type: application/json
alloydb-admin-source:
kind: alloydb-admin
tools:
alloydb-create-cluster:
kind: http
@@ -114,20 +130,10 @@ tools:
type: string
description: "The full resource name of the primary cluster for a SECONDARY instance. Required only if instanceType is SECONDARY. Otherwise don't ask"
default: ""
alloydb-list-clusters:
kind: http
source: alloydb-api-source
method: GET
path: /v1/projects/{{.projectId}}/locations/{{.locationId}}/clusters
list_clusters:
kind: alloydb-list-clusters
source: alloydb-admin-source
description: "Lists all AlloyDB clusters in a given project and location."
pathParams:
- name: projectId
type: string
description: "The GCP project ID to list clusters for."
- name: locationId
type: string
description: "The location to list clusters in (e.g., 'us-central1'). Use '-' to list clusters across all locations."
default: "-"
alloydb-list-instances:
kind: http
source: alloydb-api-source
@@ -216,7 +222,7 @@ toolsets:
- alloydb-create-cluster
- alloydb-operations-get
- alloydb-create-instance
- alloydb-list-clusters
- list_clusters
- alloydb-list-instances
- alloydb-list-users
- alloydb-create-user

View File

@@ -0,0 +1,170 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package alloydblistclusters
import (
"context"
"fmt"
yaml "github.com/goccy/go-yaml"
"github.com/googleapis/genai-toolbox/internal/sources"
alloydbadmin "github.com/googleapis/genai-toolbox/internal/sources/alloydbadmin"
"github.com/googleapis/genai-toolbox/internal/tools"
"google.golang.org/api/alloydb/v1"
"google.golang.org/api/option"
)
const kind string = "alloydb-list-clusters"
func init() {
if !tools.Register(kind, newConfig) {
panic(fmt.Sprintf("tool kind %q already registered", kind))
}
}
func newConfig(ctx context.Context, name string, decoder *yaml.Decoder) (tools.ToolConfig, error) {
actual := Config{Name: name}
if err := decoder.DecodeContext(ctx, &actual); err != nil {
return nil, err
}
return actual, nil
}
// Configuration for the list-clusters tool.
type Config struct {
Name string `yaml:"name" validate:"required"`
Kind string `yaml:"kind" validate:"required"`
Source string `yaml:"source" validate:"required"`
Description string `yaml:"description" validate:"required"`
AuthRequired []string `yaml:"authRequired"`
BaseURL string `yaml:"baseURL"`
}
// validate interface
var _ tools.ToolConfig = Config{}
// ToolConfigKind returns the kind of the tool.
func (cfg Config) ToolConfigKind() string {
return kind
}
// Initialize initializes the tool from the configuration.
func (cfg Config) Initialize(srcs map[string]sources.Source) (tools.Tool, error) {
rawS, ok := srcs[cfg.Source]
if !ok {
return nil, fmt.Errorf("source %q not found", cfg.Source)
}
s, ok := rawS.(*alloydbadmin.Source)
if !ok {
return nil, fmt.Errorf("invalid source for %q tool: source kind must be `%s`", kind, alloydbadmin.SourceKind)
}
allParameters := tools.Parameters{
tools.NewStringParameter("projectId", "The GCP project ID to list clusters for."),
tools.NewStringParameterWithDefault("locationId", "-", "Optional: The location to list clusters in (e.g., 'us-central1'). Use '-' to list clusters across all locations.(Default: '-')"),
}
paramManifest := allParameters.Manifest()
inputSchema := allParameters.McpManifest()
inputSchema.Required = []string{"projectId", "locationId"}
mcpManifest := tools.McpManifest{
Name: cfg.Name,
Description: cfg.Description,
InputSchema: inputSchema,
}
return Tool{
Name: cfg.Name,
Kind: kind,
Source: s,
AllParams: allParameters,
manifest: tools.Manifest{Description: cfg.Description, Parameters: paramManifest},
mcpManifest: mcpManifest,
}, nil
}
// Tool represents the list-clusters tool.
type Tool struct {
Name string `yaml:"name"`
Kind string `yaml:"kind"`
Description string `yaml:"description"`
Source *alloydbadmin.Source
AllParams tools.Parameters `yaml:"allParams"`
manifest tools.Manifest
mcpManifest tools.McpManifest
}
// Invoke executes the tool's logic.
func (t Tool) Invoke(ctx context.Context, params tools.ParamValues, accessToken tools.AccessToken) (any, error) {
paramsMap := params.AsMap()
projectId, ok := paramsMap["projectId"].(string)
if !ok {
return nil, fmt.Errorf("invalid or missing 'projectId' parameter; expected a string")
}
locationId, ok := paramsMap["locationId"].(string)
if !ok {
return nil, fmt.Errorf("invalid 'locationId' parameter; expected a string")
}
// Get an authenticated HTTP client from the source
client, err := t.Source.GetClient(ctx, string(accessToken))
if err != nil {
return nil, fmt.Errorf("error getting authorized client: %w", err)
}
// Create a new AlloyDB service client using the authorized client
alloydbService, err := alloydb.NewService(ctx, option.WithHTTPClient(client))
if err != nil {
return nil, fmt.Errorf("error creating AlloyDB service: %w", err)
}
urlString := fmt.Sprintf("projects/%s/locations/%s", projectId, locationId)
resp, err := alloydbService.Projects.Locations.Clusters.List(urlString).Do()
if err != nil {
return nil, fmt.Errorf("error listing AlloyDB clusters: %w", err)
}
return resp, nil
}
// ParseParams parses the parameters for the tool.
func (t Tool) ParseParams(data map[string]any, claims map[string]map[string]any) (tools.ParamValues, error) {
return tools.ParseParams(t.AllParams, data, claims)
}
// Manifest returns the tool's manifest.
func (t Tool) Manifest() tools.Manifest {
return t.manifest
}
// McpManifest returns the tool's MCP manifest.
func (t Tool) McpManifest() tools.McpManifest {
return t.mcpManifest
}
// Authorized checks if the tool is authorized.
func (t Tool) Authorized(verifiedAuthServices []string) bool {
return true
}
func (t Tool) RequiresClientAuthorization() bool {
return t.Source.UseClientAuthorization()
}

View File

@@ -0,0 +1,94 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package alloydblistclusters_test
import (
"testing"
yaml "github.com/goccy/go-yaml"
"github.com/google/go-cmp/cmp"
"github.com/googleapis/genai-toolbox/internal/server"
"github.com/googleapis/genai-toolbox/internal/testutils"
alloydblistclusters "github.com/googleapis/genai-toolbox/internal/tools/alloydb/alloydblistclusters"
)
func TestParseFromYaml(t *testing.T) {
ctx, err := testutils.ContextWithNewLogger()
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
tcs := []struct {
desc string
in string
want server.ToolConfigs
}{
{
desc: "basic example",
in: `
tools:
list-my-clusters:
kind: alloydb-list-clusters
source: my-alloydb-admin-source
description: some description
`,
want: server.ToolConfigs{
"list-my-clusters": alloydblistclusters.Config{
Name: "list-my-clusters",
Kind: "alloydb-list-clusters",
Source: "my-alloydb-admin-source",
Description: "some description",
AuthRequired: []string{},
},
},
},
{
desc: "with auth required",
in: `
tools:
list-my-clusters-auth:
kind: alloydb-list-clusters
source: my-alloydb-admin-source
description: some description
authRequired:
- my-google-auth-service
- other-auth-service
`,
want: server.ToolConfigs{
"list-my-clusters-auth": alloydblistclusters.Config{
Name: "list-my-clusters-auth",
Kind: "alloydb-list-clusters",
Source: "my-alloydb-admin-source",
Description: "some description",
AuthRequired: []string{"my-google-auth-service", "other-auth-service"},
},
},
},
}
for _, tc := range tcs {
t.Run(tc.desc, func(t *testing.T) {
got := struct {
Tools server.ToolConfigs `yaml:"tools"`
}{}
// Parse contents
err := yaml.UnmarshalContext(ctx, testutils.FormatYaml(tc.in), &got)
if err != nil {
t.Fatalf("unable to unmarshal: %s", err)
}
if diff := cmp.Diff(tc.want, got.Tools); diff != "" {
t.Fatalf("incorrect parse: diff %v", diff)
}
})
}
}

View File

@@ -0,0 +1,417 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package alloydb
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"reflect"
"regexp"
"sort"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/googleapis/genai-toolbox/internal/server/mcp/jsonrpc"
"github.com/googleapis/genai-toolbox/internal/testutils"
"github.com/googleapis/genai-toolbox/tests"
)
var (
AlloyDBProject = os.Getenv("ALLOYDB_PROJECT")
AlloyDBLocation = os.Getenv("ALLOYDB_REGION")
AlloyDBCluster = os.Getenv("ALLOYDB_CLUSTER")
)
func getAlloyDBVars(t *testing.T) map[string]string {
if AlloyDBProject == "" {
t.Fatal("'ALLOYDB_PROJECT' not set")
}
if AlloyDBLocation == "" {
t.Fatal("'ALLOYDB_REGION' not set")
}
if AlloyDBCluster == "" {
t.Fatal("'ALLOYDB_CLUSTER' not set")
}
return map[string]string{
"projectId": AlloyDBProject,
"locationId": AlloyDBLocation,
"clusterId": AlloyDBCluster,
}
}
func getAlloyDBToolsConfig() map[string]any {
return map[string]any{
"sources": map[string]any{
"alloydb-admin-source": map[string]any{
"kind": "alloydb-admin",
},
},
"tools" : map[string]any{
// Tool for RunAlloyDBToolGetTest
"my-simple-tool": map[string]any{
"kind": "alloydb-list-clusters",
"source": "alloydb-admin-source",
"description": "Simple tool to test end to end functionality.",
},
// Tool for MCP test
"my-param-tool": map[string]any{
"kind": "alloydb-list-clusters",
"source": "alloydb-admin-source",
"description": "Tool to list clusters",
},
// Tool for MCP test that fails
"my-fail-tool": map[string]any{
"kind": "alloydb-list-clusters",
"source": "alloydb-admin-source",
"description": "Tool that will fail",
},
// AlloyDB specific tools
"alloydb-list-clusters": map[string]any{
"kind": "alloydb-list-clusters",
"source": "alloydb-admin-source",
"description": "Lists all AlloyDB clusters in a given project and location.",
},
},
}
}
func TestAlloyDBToolEndpoints(t *testing.T) {
vars := getAlloyDBVars(t)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
var args []string
toolsFile := getAlloyDBToolsConfig()
cmd, cleanup, err := tests.StartCmd(ctx, toolsFile, args...)
if err != nil {
t.Fatalf("command initialization returned an error: %v", err)
}
defer cleanup()
waitCtx, cancelWait := context.WithTimeout(ctx, 20*time.Second)
defer cancelWait()
out, err := testutils.WaitForString(waitCtx, regexp.MustCompile(`Server ready to serve`), cmd.Out)
if err != nil {
t.Logf("toolbox command logs: \n%s", out)
t.Fatalf("toolbox didn't start successfully: %v", err)
}
runAlloyDBToolGetTest(t)
runAlloyDBMCPToolCallMethod(t, vars)
// Run tool-specific invoke tests
runAlloyDBListClustersTest(t, vars)
}
func runAlloyDBToolGetTest(t *testing.T) {
tcs := []struct {
name string
api string
want map[string]any
}{
{
name: "get my-simple-tool",
api: "http://127.0.0.1:5000/api/tool/my-simple-tool/",
want: map[string]any{
"my-simple-tool": map[string]any{
"description": "Simple tool to test end to end functionality.",
"parameters": []any{
map[string]any{"name": "projectId", "type": "string", "description": "The GCP project ID to list clusters for.", "required": true, "authSources": []any{}},
map[string]any{"name": "locationId", "type": "string", "description": "Optional: The location to list clusters in (e.g., 'us-central1'). Use '-' to list clusters across all locations.(Default: '-')", "required": false, "authSources": []any{}},
},
"authRequired": nil,
},
},
},
}
for _, tc := range tcs {
t.Run(tc.name, func(t *testing.T) {
resp, err := http.Get(tc.api)
if err != nil {
t.Fatalf("error when sending a request: %s", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("response status code is not 200")
}
var body map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
t.Fatalf("error parsing response body: %v", err)
}
got, ok := body["tools"]
if !ok {
t.Fatalf("unable to find 'tools' in response body")
}
if diff := cmp.Diff(tc.want, got); diff != "" {
t.Errorf("response mismatch (-want +got):\n%s", diff)
}
})
}
}
func runAlloyDBMCPToolCallMethod(t *testing.T, vars map[string]string) {
sessionId := tests.RunInitialize(t, "2024-11-05")
header := map[string]string{}
if sessionId != "" {
header["Mcp-Session-Id"] = sessionId
}
invokeTcs := []struct {
name string
requestBody jsonrpc.JSONRPCRequest
wantContains string
isErr bool
}{
{
name: "MCP Invoke my-param-tool",
requestBody: jsonrpc.JSONRPCRequest{
Jsonrpc: "2.0",
Id: "my-param-tool-mcp",
Request: jsonrpc.Request{Method: "tools/call"},
Params: map[string]any{
"name": "my-param-tool",
"arguments": map[string]any{
"projectId": vars["projectId"],
"locationId": vars["locationId"],
},
},
},
wantContains: fmt.Sprintf(`"name\":\"projects/%s/locations/%s/clusters/%s\"`, vars["projectId"], vars["locationId"], vars["clusterId"]),
isErr: false,
},
{
name: "MCP Invoke my-fail-tool",
requestBody: jsonrpc.JSONRPCRequest{
Jsonrpc: "2.0",
Id: "invoke-fail-tool",
Request: jsonrpc.Request{Method: "tools/call"},
Params: map[string]any{
"name": "my-fail-tool",
"arguments": map[string]any{
"locationId": vars["locationId"],
},
},
},
wantContains: `parameter \"projectId\" is required`,
isErr: true,
},
{
name: "MCP Invoke invalid tool",
requestBody: jsonrpc.JSONRPCRequest{
Jsonrpc: "2.0",
Id: "invalid-tool-mcp",
Request: jsonrpc.Request{Method: "tools/call"},
Params: map[string]any{
"name": "non-existent-tool",
"arguments": map[string]any{},
},
},
wantContains: `tool with name \"non-existent-tool\" does not exist`,
isErr: true,
},
{
name: "MCP Invoke tool without required parameters",
requestBody: jsonrpc.JSONRPCRequest{
Jsonrpc: "2.0",
Id: "invoke-without-params-mcp",
Request: jsonrpc.Request{Method: "tools/call"},
Params: map[string]any{
"name": "my-param-tool",
"arguments": map[string]any{"locationId": vars["locationId"]},
},
},
wantContains: `parameter \"projectId\" is required`,
isErr: true,
},
{
name: "MCP Invoke my-auth-required-tool",
requestBody: jsonrpc.JSONRPCRequest{
Jsonrpc: "2.0",
Id: "invoke my-auth-required-tool",
Request: jsonrpc.Request{Method: "tools/call"},
Params: map[string]any{
"name": "my-auth-required-tool",
"arguments": map[string]any{},
},
},
wantContains: `tool with name \"my-auth-required-tool\" does not exist`,
isErr: true,
},
}
for _, tc := range invokeTcs {
t.Run(tc.name, func(t *testing.T) {
api := "http://127.0.0.1:5000/mcp"
reqMarshal, err := json.Marshal(tc.requestBody)
if err != nil {
t.Fatalf("unexpected error during marshaling of request body: %v", err)
}
req, err := http.NewRequest(http.MethodPost, api, bytes.NewBuffer(reqMarshal))
if err != nil {
t.Fatalf("unable to create request: %s", err)
}
req.Header.Add("Content-type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("unable to send request: %s", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("unable to read request body: %s", err)
}
got := string(bytes.TrimSpace(respBody))
if !strings.Contains(got, tc.wantContains) {
t.Fatalf("Expected substring not found:\ngot: %q\nwant: %q (to be contained within got)", got, tc.wantContains)
}
})
}
}
func runAlloyDBListClustersTest(t *testing.T, vars map[string]string) {
type ListClustersResponse struct {
Clusters []struct {
Name string `json:"name"`
} `json:"clusters"`
}
type ToolResponse struct {
Result string `json:"result"`
}
// NOTE: If clusters are added, removed or changed in the test project,
// this list must be updated for the "list clusters specific locations" test to pass
wantForSpecificLocation := []string{
fmt.Sprintf("projects/%s/locations/us-central1/clusters/alloydb-ai-nl-testing", vars["projectId"]),
fmt.Sprintf("projects/%s/locations/us-central1/clusters/alloydb-pg-testing", vars["projectId"]),
}
// NOTE: If clusters are added, removed, or changed in the test project,
// this list must be updated for the "list clusters all locations" test to pass
wantForAllLocations := []string{
fmt.Sprintf("projects/%s/locations/us-central1/clusters/alloydb-ai-nl-testing", vars["projectId"]),
fmt.Sprintf("projects/%s/locations/us-central1/clusters/alloydb-pg-testing", vars["projectId"]),
fmt.Sprintf("projects/%s/locations/us-east4/clusters/alloydb-private-pg-testing", vars["projectId"]),
fmt.Sprintf("projects/%s/locations/us-east4/clusters/colab-testing", vars["projectId"]),
}
invokeTcs := []struct {
name string
requestBody io.Reader
want []string
wantStatusCode int
}{
{
name: "list clusters for all locations",
requestBody: bytes.NewBufferString(fmt.Sprintf(`{"projectId": "%s", "locationId": "-"}`, vars["projectId"])),
want: wantForAllLocations,
wantStatusCode: http.StatusOK,
},
{
name: "list clusters specific location",
requestBody: bytes.NewBufferString(fmt.Sprintf(`{"projectId": "%s", "locationId": "us-central1"}`, vars["projectId"])),
want: wantForSpecificLocation,
wantStatusCode: http.StatusOK,
},
{
name: "list clusters missing project",
requestBody: bytes.NewBufferString(fmt.Sprintf(`{"locationId": "%s"}`, vars["locationId"])),
wantStatusCode: http.StatusBadRequest,
},
{
name: "list clusters non-existent location",
requestBody: bytes.NewBufferString(fmt.Sprintf(`{"projectId": "%s", "locationId": "abcd"}`, vars["projectId"])),
wantStatusCode: http.StatusInternalServerError,
},
{
name: "list clusters non-existent project",
requestBody: bytes.NewBufferString(fmt.Sprintf(`{"projectId": "non-existent-project", "locationId": "%s"}`, vars["locationId"])),
wantStatusCode: http.StatusInternalServerError,
},
{
name: "list clusters empty project",
requestBody: bytes.NewBufferString(fmt.Sprintf(`{"projectId": "", "locationId": "%s"}`, vars["locationId"])),
wantStatusCode: http.StatusBadRequest,
},
{
name: "list clusters empty location",
requestBody: bytes.NewBufferString(fmt.Sprintf(`{"projectId": "%s", "locationId": ""}`, vars["projectId"])),
wantStatusCode: http.StatusBadRequest,
},
}
for _, tc := range invokeTcs {
t.Run(tc.name, func(t *testing.T) {
api := "http://127.0.0.1:5000/api/tool/alloydb-list-clusters/invoke"
req, err := http.NewRequest(http.MethodPost, api, tc.requestBody)
if err != nil {
t.Fatalf("unable to create request: %s", err)
}
req.Header.Add("Content-type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("unable to send request: %s", err)
}
defer resp.Body.Close()
if resp.StatusCode != tc.wantStatusCode {
bodyBytes, _ := io.ReadAll(resp.Body)
t.Fatalf("response status code is not %d, got %d: %s", tc.wantStatusCode, resp.StatusCode, string(bodyBytes))
}
if tc.wantStatusCode == http.StatusOK {
var body ToolResponse
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
t.Fatalf("error parsing outer response body: %v", err)
}
var clustersData ListClustersResponse
if err := json.Unmarshal([]byte(body.Result), &clustersData); err != nil {
t.Fatalf("error parsing nested result JSON: %v", err)
}
var got []string
for _, cluster := range clustersData.Clusters {
got = append(got, cluster.Name)
}
sort.Strings(got)
sort.Strings(tc.want)
if !reflect.DeepEqual(got, tc.want) {
t.Errorf("cluster list mismatch:\n got: %v\nwant: %v", got, tc.want)
}
}
})
}
}

View File

@@ -272,4 +272,4 @@ func TestAlloyDBPgIAMConnection(t *testing.T) {
}
})
}
}
}