testsupport

package
v0.5.0-beta.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 24, 2026 License: PostgreSQL Imports: 11 Imported by: 0

Documentation

Overview

Package testsupport holds the test fixtures every Starfleet module's command tree needs: an isolated Runtime, the stub token/resource server, and the authenticated-command runner.

It gives the environment-isolation list, which keeps a developer's shell settings out of the suite, one home: per-module copies drifted, one tree gaining a variable the others lacked, and the gap shows only as a test behaving differently under a developer's own shell. ClearEnv is split from NewRuntime for tests that need the names cleared with no Runtime built.

It is a non-test package importing "testing" because Go has no other way to share fixtures across packages; nothing outside a test calls it. It must not import any module's cmd package, because the cmd packages' tests import this one.

Index

Constants

View Source
const TokenBody = `{"access_token":"tok",` +
	`"token_type":"Bearer","expires_in":3600}`

TokenBody is the canned OAuth token payload the stub servers return, so authenticated resource commands can obtain a bearer token without a real identity provider.

View Source
const TokenPath = "/account/v1/oauth/token" //nolint:gosec // G101: a URL path, not a credential

TokenPath is where the account API serves the OAuth token endpoint, and therefore the only path a stub server must answer itself. It is namespaced: the CLI does not reference the retired bare /v1 surface.

Variables

This section is empty.

Functions

func BrokenHandler

func BrokenHandler() http.HandlerFunc

BrokenHandler hijacks and immediately closes the connection so the API client sees a transport error (rather than an HTTP status). It drives the `if err != nil { return fmt.Errorf(...) }` branch that follows every generated *WithResponse call, and is shared because the byoc and account cmd tests table-test that branch across their whole resource-command surface.

func ClearEnv

func ClearEnv(t *testing.T)

ClearEnv neutralises every variable in hostEnv and leaves HOME alone. It is NewRuntime's environment half, for tests with no constructed Runtime: cmd/pgedge's cases hand a subprocess the parent's os.Environ(), and internal/starfleet/conn's build their *module.Runtime by hand.

t.Setenv(name, "") rather than os.Unsetenv: every non-test reader compares a plain os.Getenv against "", and no os.LookupEnv exists outside _test.go files, so "" is a faithful clear. t.Setenv also restores the developer's value on cleanup, which os.Unsetenv would not.

Call it BEFORE setting any variable the test wants to control: it wipes whatever was set before it ran.

func IsPureRouter

func IsPureRouter(c *cobra.Command) bool

IsPureRouter reports whether c is a "pure router": a non-root group command whose Use declares no positional argument (see declaresArgument), unlike a hybrid such as "pgedge controlplane database restore <database_id>", which is itself an action.

It is structural only; callers set their own policy for a pure router with neither RunE nor Run. internal/clitest fails it (absence is the bug it gates); WalkPureRouters skips it (it only exercises a real invocation).

func JSONHandler

func JSONHandler(status int, body string) http.HandlerFunc

JSONHandler returns a handler that writes status and body with a JSON content type. It is the building block for the per-endpoint stub responses the resource command tests rely on.

func LooksLikeHelp

func LooksLikeHelp(text string) bool

LooksLikeHelp reports whether text resembles cobra's default help rendering, which a pure router's bare invocation ("return c.Help()") should print. Non-empty is not enough: one stray character or an unrelated message would pass that. Every cobra help template renders "Usage:" (command.go's default UsageTemplate), so its presence shows help was printed, not just something.

func NewAuthedServer

func NewAuthedServer(t *testing.T, resource http.HandlerFunc) string

NewAuthedServer starts an httptest server that answers TokenPath with TokenBody and delegates every other request to resource. It returns the server's base URL, which callers pass as --api-url, so a resource command can authenticate and run fully hermetically.

func NewRuntime

func NewRuntime(t *testing.T, stdin, format string) (
	rt *module.Runtime, stdout, stderr *bytes.Buffer,
)

NewRuntime returns a Runtime wired to an isolated HOME and captured output buffers, with every variable in hostEnv cleared. Both returned buffers are also the Runtime's Output writers, so a caller can assert on rendered output as well as on raw writes.

func PathHandler

func PathHandler(tb testing.TB, path string, status int,
	body string) http.HandlerFunc

PathHandler is JSONHandler for one path: it serves status and body when the request is for path and fails tb otherwise. JSONHandler discards the request, so a command asking for the wrong resource gets the right answer and every assertion downstream still holds; this is the stub for a test whose point is which path the command asked for.

func RunAuthed

func RunAuthed(t *testing.T, root *cobra.Command, out *bytes.Buffer,
	srvURL string, args ...string,
) error

RunAuthed executes root against the stub server at srvURL, supplying dummy credentials through the persistent --client-id / --client-secret flags and pointing --api-url at the stub. Output and errors are captured into out.

It takes root rather than a Runtime because each module builds its own tree, and importing those constructors here would cycle. Callers wrap it in a three-line adapter naming their own root.

func RunBareCapture

func RunBareCapture(c *cobra.Command) (captured string, err error)

RunBareCapture invokes c with no arguments via whichever of RunE or Run is set, capturing c's out and err in one buffer, and returns the buffer and RunE's error. With neither set it returns ("", nil): whether one must exist is a policy IsPureRouter's callers decide.

Handling Run as well is essential: c.RunE(c, nil) on a Run-only router is a nil pointer dereference, and a panicking test takes its whole package's run down and reports nothing useful. Nothing in the shipped tree uses bare Run today.

func WalkPureRouters

func WalkPureRouters(t *testing.T, root *cobra.Command)

WalkPureRouters reports a pureRouterViolations(root) failure for every pure-router group under root whose bare invocation (no args) errors or does not print a help rendering.

It is the runtime half of internal/clitest's structural gate (TestCommandTreeConformance), duplicated rather than called from there because `go test ./...` runs with no -coverpkg: a check living only in internal/clitest exercises the byoc, controlplane, account and cli packages but credits none of their coverage.out entries, so each runs this from its own test binary. It catches a no-op RunE (return nil, print nothing), which satisfies cobra and every static check yet silently succeeds on a bare invocation.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL