Files
genai-toolbox/tests/server.go
Yuan Teoh 195767bdcd refactor: refactor subcommands and move tests to its own package (#2439)
This PR refactors the command structure to decouple subcommands from the
root command, improving modularity and testability.

**Key Changes:**
- Move `internal/cli` to `cmd/internal`. Being in a `internal` folder,
other packages outside of `cmd` will not be able to import them.
- Encapsulated I/O: Introduced a new IOStreams struct to standardize in,
out, and errOut handling.
- Shared Dependencies: Extracted shared fields (including IOStreams,
Logger, ServerConfig, and various Tools paths) from the root `Command`
into a new `ToolboxOptions` struct. This also includes moving
`cmd/options.go` to be part of `ToolboxOptions`.
- Logic Migration: Moved setup logic, such as `Setup()` and
`LoadConfig()`, into `ToolboxOptions`. Removing the need to import
`rootCmd` to subcommands.
- Package Reorganization:
- Relocated PersistentFlag and ToolsFiles to the cli package to remove
base command dependencies. This removes dependencies on the base
command, allowing subcommands to consume these utilities independently.
- Moved all side-effect registration to the `cmd/internal` package,
enabling other packages to import it safely for unit tests.

**Testing Improvements:**
- Subcommand packages can now be tested in isolation without relying on
the base command package.
- Added `TestSubcommandWiring()` to the base command tests to verify
proper subcommand registration.
2026-02-13 02:28:58 +00:00

134 lines
3.2 KiB
Go

// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tests
import (
"context"
"fmt"
"io"
"os"
yaml "github.com/goccy/go-yaml"
"github.com/spf13/cobra"
"github.com/googleapis/genai-toolbox/cmd"
)
// tmpFileWithCleanup creates a temporary file with the content and returns the path and
// a function to clean it up, or any errors encountered instead
func tmpFileWithCleanup(content []byte) (string, func(), error) {
// create a random file in the temp dir
f, err := os.CreateTemp("", "*") // * indicates random string
if err != nil {
return "", nil, err
}
cleanup := func() { os.Remove(f.Name()) }
if _, err := f.Write(content); err != nil {
cleanup()
return "", nil, err
}
if err := f.Close(); err != nil {
cleanup()
return "", nil, err
}
return f.Name(), cleanup, err
}
// CmdExec represents an invocation of a toolbox command.
type CmdExec struct {
Out io.ReadCloser
cmd *cobra.Command
cancel context.CancelFunc
closers []io.Closer
done chan bool // closed once the cmd is completed
err error
}
// StartCmd returns a CmdExec representing a running instance of a toolbox command.
func StartCmd(ctx context.Context, toolsFile map[string]any, args ...string) (*CmdExec, func(), error) {
b, err := yaml.Marshal(toolsFile)
if err != nil {
return nil, nil, fmt.Errorf("unable to marshal tools file: %s", err)
}
path, cleanup, err := tmpFileWithCleanup(b)
if err != nil {
return nil, nil, fmt.Errorf("unable to write tools file: %s", err)
}
args = append(args, "--tools-file", path)
ctx, cancel := context.WithCancel(ctx)
// Open a pipe for tracking the output from the cmd
pr, pw, err := os.Pipe()
if err != nil {
cancel()
return nil, nil, fmt.Errorf("unable to open stdout pipe: %w", err)
}
c := cmd.GenerateCommand(pw, pw)
c.SetArgs(args)
t := &CmdExec{
Out: pr,
cmd: c,
cancel: cancel,
closers: []io.Closer{pr, pw},
done: make(chan bool),
}
// Start the command in the background
go func() {
defer close(t.done)
defer cancel()
t.err = c.ExecuteContext(ctx)
}()
return t, cleanup, nil
}
// Stop sends the TERM signal to the cmd and returns.
func (c *CmdExec) Stop() {
c.cancel()
}
// Waits until the execution is completed and returns any error from the result.
func (c *CmdExec) Wait(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-c.done:
return c.err
}
}
// Done returns true if the command has exited.
func (c *CmdExec) Done() bool {
select {
case <-c.done:
return true
default:
}
return false
}
// Close releases any resources associated with the instance.
func (c *CmdExec) Close() {
c.cancel()
for _, c := range c.closers {
c.Close()
}
}