stubs

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 19 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package stubs provides test stubs.

Index

Constants

View Source
const ExpectedDeviceAuthDisplay = "Open this URL in your browser," +
	" complete the authorization, and verify the code 'user-code':\n" +
	"${URL}/authorization?client_id=discovered_spa_client_id&organization=org-1&" +
	"redirect_uri=verification_uri_complete&response_type=code&scope=openid+profile+offline_access"

ExpectedDeviceAuthDisplay is the expected display when using the stub auth endpoint.

Variables

View Source
var (
	// StubAuthHeaders represents the headers expected from test clients when
	// making requests to Workbench API endpoints.
	StubAuthHeaders = map[string]string{
		constants.AuthorizationHeaderKey:      "Bearer access-token",
		constants.PostgrestCSRFTokenHeaderKey: "csrf-token",
		constants.CookieHeaderKey:             constants.PostgrestCSRFTokenKey + "=csrf-token;",
	}
)

Functions

func AsString

func AsString[T any](
	v T,
) string

AsString returns the given value as a json marshaled string.

func Host

func Host(t *testing.T, _url string) string

Host returns the host part of the given url.

func Port

func Port(t *testing.T, _url string) string

Port returns the port part of the given url.

func Replace

func Replace(src string, replacements map[string]string) string

Replace returns a copy fo the given src string with all instances of keys in the given replacements map with the corresponding values.

func Sanitize

func Sanitize(expected, actual string, replacements map[string]string) (string, string)

Sanitize is a testing utility function. It takes an expected string and actual string and a list of name/value pairs. First, any occurrences of {SANITIZE:regexp:replacement} are found in the expected string. Any matches of the regexp in the actual string are replaced with the replacement value. Then the entire {SANITIZE:regexp:replacement} string in the expected string is replaced with the replacement value. Lastly, any occurrences of the keys of the replacements map are replaced in the expected string with the corresponding values. See TestExampleSanitizeUsage for an example.

func SanitizeSlice

func SanitizeSlice(expectedSlice, actualSlice []string, replacements map[string]string) ([]string, []string)

SanitizeSlice calls Sanitize on each pair of strings in the expectedSlice and actualSlice slices. If there are a different number of elements in each slice then they are returned unchanged.

Types

type CapturedTable

type CapturedTable struct {
	Headers    []string
	PrintCalls int
	Rows       [][]string
}

CapturedTable records all table interactions for assertions in tests.

func (*CapturedTable) Add

func (t *CapturedTable) Add(values ...string)

Add appends a row to the captured table.

func (*CapturedTable) Print

func (t *CapturedTable) Print()

Print records a print call.

func (*CapturedTable) String

func (t *CapturedTable) String() string

String is an exported method.

type HitCounts

type HitCounts map[string]int

HitCounts maps an endpoint key to the number of times it was invoked in tests.

func NewStubHTTPServer

func NewStubHTTPServer(
	t *testing.T,
	endpoints []StubHTTPEndpoint,
) (*httptest.Server, *HitCounts)

NewStubHTTPServer returns a new httptest.Server configured with the given endpoints.

func NewStubHTTPServerWithMultipleResponsesPerEndpoint

func NewStubHTTPServerWithMultipleResponsesPerEndpoint(
	t *testing.T,
	endpoints []StubHTTPEndpoints,
) (*httptest.Server, *HitCounts)

NewStubHTTPServerWithMultipleResponsesPerEndpoint returns a new httptest.Server configured with the given endpoints. nolint:cyclop

func (*HitCounts) Count

func (h *HitCounts) Count(key string) int

Count returns the recorded hit count for the specified key.

func (*HitCounts) CountPrefix

func (h *HitCounts) CountPrefix(prefix string) int

CountPrefix returns the total hits for keys that begin with the provided prefix.

type StubFS

type StubFS struct {
	afero.Fs
	CreateFunc    func(afero.Fs, string) (afero.File, error)
	MkdirFunc     func(afero.Fs, string, os.FileMode) error
	MkdirAllFunc  func(afero.Fs, string, os.FileMode) error
	OpenFunc      func(afero.Fs, string) (afero.File, error)
	OpenFileFunc  func(afero.Fs, string, int, os.FileMode) (afero.File, error)
	RemoveFunc    func(afero.Fs, string) error
	RemoveAllFunc func(afero.Fs, string) error
	RenameFunc    func(afero.Fs, string, string) error
	StatFunc      func(afero.Fs, string) (os.FileInfo, error)
	NameFunc      func(afero.Fs) string
	ChmodFunc     func(afero.Fs, string, os.FileMode) error
	ChownFunc     func(afero.Fs, string, int, int) error
	ChtimesFunc   func(afero.Fs, string, time.Time, time.Time) error
}

StubFS is a test filesystem that delegates to injected functions when set.

func (StubFS) Chmod

func (s StubFS) Chmod(name string, mode os.FileMode) error

Chmod changes file permissions, using the injected function when present.

func (StubFS) Chown

func (s StubFS) Chown(name string, uid, gid int) error

Chown changes file ownership, using the injected function when present.

func (StubFS) Chtimes

func (s StubFS) Chtimes(name string, atime time.Time, mtime time.Time) error

Chtimes updates file timestamps, using the injected function when present.

func (StubFS) Create

func (s StubFS) Create(name string) (afero.File, error)

Create opens a file for writing, using the injected function when present.

func (StubFS) Mkdir

func (s StubFS) Mkdir(name string, perm os.FileMode) error

Mkdir creates a directory, using the injected function when present.

func (StubFS) MkdirAll

func (s StubFS) MkdirAll(path string, perm os.FileMode) error

MkdirAll creates a directory tree, using the injected function when present.

func (StubFS) Name

func (s StubFS) Name() string

Name returns the filesystem name, using the injected function when present.

func (StubFS) Open

func (s StubFS) Open(name string) (afero.File, error)

Open opens a file, using the injected function when present.

func (StubFS) OpenFile

func (s StubFS) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error)

OpenFile opens a file with flags, using the injected function when present.

func (StubFS) Remove

func (s StubFS) Remove(name string) error

Remove deletes a file, using the injected function when present.

func (StubFS) RemoveAll

func (s StubFS) RemoveAll(path string) error

RemoveAll deletes a path tree, using the injected function when present.

func (StubFS) Rename

func (s StubFS) Rename(oldname, newname string) error

Rename renames a file, using the injected function when present.

func (StubFS) Stat

func (s StubFS) Stat(name string) (os.FileInfo, error)

Stat returns file information, using the injected function when present.

type StubFile

type StubFile struct {
	afero.File
	CloseFunc        func(afero.File) error
	ReadFunc         func(afero.File, []byte) (int, error)
	ReadAtFunc       func(afero.File, []byte, int64) (int, error)
	SeekFunc         func(afero.File, int64, int) (int64, error)
	WriteFunc        func(afero.File, []byte) (int, error)
	WriteAtFunc      func(afero.File, []byte, int64) (int, error)
	NameFunc         func(afero.File) string
	ReaddirFunc      func(afero.File, int) ([]os.FileInfo, error)
	ReaddirnamesFunc func(afero.File, int) ([]string, error)
	StatFunc         func(afero.File) (os.FileInfo, error)
	SyncFunc         func(afero.File) error
	TruncateFunc     func(afero.File, int64) error
	WriteStringFunc  func(afero.File, string) (int, error)
}

StubFile is a test file that delegates to injected functions when set.

func (StubFile) Close

func (s StubFile) Close() error

Close closes the file, using the injected function when present.

func (StubFile) Name

func (s StubFile) Name() string

Name returns the file name, using the injected function when present.

func (StubFile) Read

func (s StubFile) Read(p []byte) (int, error)

Read reads from the file, using the injected function when present.

func (StubFile) ReadAt

func (s StubFile) ReadAt(p []byte, off int64) (int, error)

ReadAt reads from an offset, using the injected function when present.

func (StubFile) Readdir

func (s StubFile) Readdir(count int) ([]os.FileInfo, error)

Readdir reads directory entries, using the injected function when present.

func (StubFile) Readdirnames

func (s StubFile) Readdirnames(n int) ([]string, error)

Readdirnames reads directory entry names, using the injected function when present.

func (StubFile) Seek

func (s StubFile) Seek(offset int64, whence int) (int64, error)

Seek changes the file offset, using the injected function when present.

func (StubFile) Stat

func (s StubFile) Stat() (os.FileInfo, error)

Stat returns file information, using the injected function when present.

func (StubFile) Sync

func (s StubFile) Sync() error

Sync flushes file contents, using the injected function when present.

func (StubFile) Truncate

func (s StubFile) Truncate(size int64) error

Truncate truncates the file, using the injected function when present.

func (StubFile) Write

func (s StubFile) Write(p []byte) (int, error)

Write writes to the file, using the injected function when present.

func (StubFile) WriteAt

func (s StubFile) WriteAt(p []byte, off int64) (int, error)

WriteAt writes at an offset, using the injected function when present.

func (StubFile) WriteString

func (s StubFile) WriteString(st string) (int, error)

WriteString writes a string, using the injected function when present.

type StubHTTPBodyOption

type StubHTTPBodyOption func(
	r *http.Request,
	body string,
) string

StubHTTPBodyOption mutates or formats a response body before it is written. Receives the request and the current body and must return the body to send.

func StubHTTPBodyReplaceHOST

func StubHTTPBodyReplaceHOST() StubHTTPBodyOption

StubHTTPBodyReplaceHOST returns a StubHTTPBodyOption that replaces ${HOST} placeholders in the body with the request Host value.

type StubHTTPEndpoint

type StubHTTPEndpoint struct {
	Request  StubHTTPRequest
	Response StubHTTPResponse
}

StubHTTPEndpoint pairs a single expected request with the response to return.

func GetStubApplicationsEndpoints

func GetStubApplicationsEndpoints(config StubHTTPPartialGetConfig) []StubHTTPEndpoint

GetStubApplicationsEndpoints returns an application endpoint. The first request/response is configured with the given config.

func GetStubAuthEndpoints

func GetStubAuthEndpoints() []StubHTTPEndpoint

GetStubAuthEndpoints returns default endpoints that mock an authentication server. Used when the auth server endpoints themselves are not under test.

func GetStubDataplaneEndpoints

func GetStubDataplaneEndpoints(config StubHTTPPartialGetConfig) []StubHTTPEndpoint

GetStubDataplaneEndpoints returns a dataplane endpoint. The first request/response is configured with the given config.

func GetStubNodepoolsEndpoints

func GetStubNodepoolsEndpoints(config StubHTTPPartialGetConfig) []StubHTTPEndpoint

GetStubNodepoolsEndpoints returns a nodepools endpoint. The first request/response is configured with the given config.

func GetStubServicesEndpoints

func GetStubServicesEndpoints(config StubHTTPPartialGetConfig) []StubHTTPEndpoint

GetStubServicesEndpoints returns a services endpoint. The first request/response is configured with the given config.

func GetStubWorkspaceEndpoints

func GetStubWorkspaceEndpoints(config StubHTTPPartialGetConfig) []StubHTTPEndpoint

GetStubWorkspaceEndpoints returns endpoints that represent workspaces. If the provided config is empty then two workspaces are represented, one for a home dir and one for a regular dir. The home dir must be requested first.

type StubHTTPEndpoints

type StubHTTPEndpoints struct {
	Request  StubHTTPRequests
	Response StubHTTPResponses
}

StubHTTPEndpoints groups request expectations and response configurations for a single route.

type StubHTTPPartialGetConfig

type StubHTTPPartialGetConfig struct {
	ExpectedQuery  string
	ResponseStatus int
	ResponseBody   string
}

StubHTTPPartialGetConfig represents a single get request and response that does not require additional config like headers.

type StubHTTPPartialPostConfig

type StubHTTPPartialPostConfig struct {
	ExpectedRequestBody string
	ResponseStatus      int
	ResponseBody        string
}

StubHTTPPartialPostConfig represents a single post request and response that does not require additional config like headers.

type StubHTTPRequest

type StubHTTPRequest struct {
	Method          string
	URL             string
	ExpectedQuery   string
	ExpectedHeaders map[string]string
	ExpectedBody    string
}

StubHTTPRequest contains expectations for a single HTTP request in the stub harness.

type StubHTTPRequests

type StubHTTPRequests struct {
	Method                string
	URL                   string
	ExpectedQueries       []string
	ExpectedHeaders       []map[string]string
	ExpectedRequestBodies []string
}

StubHTTPRequests describes expectations for incoming HTTP requests in the test stub.

type StubHTTPResponse

type StubHTTPResponse struct {
	Body        string
	Headers     map[string][]string
	Status      int
	BodyOptions []StubHTTPBodyOption
}

StubHTTPResponse describes a single HTTP response returned by a stub endpoint.

type StubHTTPResponses

type StubHTTPResponses struct {
	Bodies      []string
	Headers     []map[string][]string
	Statuses    []int
	BodyOptions [][]StubHTTPBodyOption
}

StubHTTPResponses configures the responses returned by a stub endpoint across multiple calls.

type StubUI

type StubUI struct {
	Displays []string
	Warns    []string
	Errors   []string

	// Recorded questions
	Asks            []string
	AskForPasswords []string

	// Configured responses
	AskResponses            []string
	AskForPasswordResponses []string

	// Captured tables, one entry per Table(...) call.
	Tables []*CapturedTable
}

StubUI is a test UI implementation that records display and warning messages. Configure AskResponses and AskForPasswordResponses with queued return values for Ask calls (FIFO; empty queue returns "").

func (*StubUI) Ask

func (u *StubUI) Ask(question string, args ...interface{}) string

Ask records a question and returns the next queued response.

func (*StubUI) AskForPassword

func (u *StubUI) AskForPassword(question string, args ...interface{}) string

AskForPassword records a password prompt and returns the next queued response.

func (*StubUI) Display

func (u *StubUI) Display(message string, args ...interface{})

Display records a formatted display message.

func (*StubUI) Error

func (u *StubUI) Error(message string, args ...interface{})

Error records a formatted error message.

func (*StubUI) Table

func (u *StubUI) Table(headers []string) ui.Table

Table captures table rows for later assertions.

func (*StubUI) Warn

func (u *StubUI) Warn(message string, args ...interface{})

Warn records a formatted warning message.

Jump to

Keyboard shortcuts

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