testkit

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: Apache-2.0 Imports: 42 Imported by: 0

Documentation

Overview

Package testkit is the Flagnetic test kit: a real, migrated PostgreSQL for every test package, and the fake clock, deterministic identifiers and log sink a test hands to the code under test.

A package whose tests need the database starts with

func TestMain(m *testing.M) { os.Exit(testkit.Main(m)) }

Index

Constants

View Source
const (
	InstanceAdminEmail    = "admin@example.com"
	InstanceAdminName     = "Test Admin"
	InstanceAdminPassword = "lantern-quartz-meadow-2291"
)

The instance admin every test kit database is bootstrapped with.

View Source
const MemberPassword = "tangerine-violin-orbit-1987"

MemberPassword is the password of every member NewMember creates.

View Source
const SecretKey = "test secret key of the in-process server, 32+ bytes"

SecretKey is the secret key of every in-process server.

Variables

View Source
var Start = time.Date(2026, time.January, 1, 9, 0, 0, 0, time.UTC)

Start is the time a test's fake clock reads until the test moves it.

Functions

func Bootstrap

func Bootstrap(t testing.TB, pool *pgxpool.Pool) string

Bootstrap returns the bootstrap token of the instance on pool, running `admin bootstrap` as InstanceAdminEmail on first use, at the test kit's Start.

func Client

func Client(t testing.TB, srv *Server, token string) *management.ClientWithResponses

Client returns a client of the management API of srv presenting token as a bearer, or no credential when token is "". The secrets its requests and responses carry are recorded for the audit guard.

func Clock

func Clock() *clock.Fake

Clock returns a fake clock reading Start.

func DatabaseURL

func DatabaseURL(t testing.TB) string

DatabaseURL returns the connection string of the package's migrated schema.

func EmptyDatabase

func EmptyDatabase(t testing.TB) string

EmptyDatabase returns the connection string of a new schema with nothing in it, not even the migrations, dropped when the test ends. If the test migrates it, its audit log is guarded as the package's is.

func FindSecretsInAudit

func FindSecretsInAudit(ctx context.Context, pool *pgxpool.Pool, secrets []string) error

FindSecretsInAudit reads every audit entry on pool through the audit log's own query and returns an error naming each entry holding one of secrets, without repeating the secret. A database whose migrations have not created the audit log yet holds no entry.

func FreshPool

func FreshPool(t testing.TB) *pgxpool.Pool

FreshPool returns a pool on a new migrated database of its own, dropped when the test ends, for a test that needs an instance nobody else touches, such as one not yet bootstrapped.

func Grant

func Grant(t testing.TB, pool *pgxpool.Pool, project workspace.ProjectID, member access.MemberID, roles ...access.RoleName)

Grant grants member each of roles in project on pool, made by nobody, as if an owner had.

func GrantedToken

func GrantedToken(t testing.TB, pool *pgxpool.Pool, project workspace.ProjectID, roles ...access.RoleName) string

GrantedToken returns the value of a personal access token, carrying every scope a member who is no instance admin holds, of a new active member of the instance on pool who holds roles in project.

func IDs

func IDs(c clock.Clock) *id.Source

IDs returns a deterministic identifier source reading c.

func InstanceAdminToken

func InstanceAdminToken(t testing.TB) string

InstanceAdminToken returns the bootstrap token of the package's database, bootstrapping its instance admin on first use.

func Main

func Main(m *testing.M) int

Main gives the package one schema with the server's migrations applied, runs its tests, fails the package if its audit log holds a secret value the tests recorded, and drops the schema. It returns the exit code for os.Exit.

func MemberToken

func MemberToken(t testing.TB, pool *pgxpool.Pool, scopes ...access.Scope) string

MemberToken returns the value of a personal access token carrying scopes (read alone when none) of a new active member of the instance on pool, who is no instance admin and holds no grant.

func Metric

func Metric(t testing.TB, scrape, series string) float64

Metric returns the value of one sample of a scrape, named as it is written, such as `flagnetic_listener_up{channel="rulesets"}`, or -1 when the scrape has none.

func PersonalToken

func PersonalToken(t testing.TB, pool *pgxpool.Pool, member access.MemberID, name string, scopes ...access.Scope) string

PersonalToken returns the value of a new personal access token called name of member on pool, carrying scopes (read alone when none).

func Pool

func Pool(t testing.TB) *pgxpool.Pool

Pool returns the pool on the package's migrated schema, shared by the package's tests: a test isolates by its own data, never by emptying tables.

func ProjectToken

func ProjectToken(t testing.TB, pool *pgxpool.Pool, project workspace.ProjectID, role access.RoleName, scopes ...access.Scope) string

ProjectToken returns the value of a project token of project on pool holding role, with scopes (every scope a project token may carry when none).

func RecordSecret

func RecordSecret(v string)

RecordSecret records v as a secret value no audit entry may hold.

func RecordSecretsIn

func RecordSecretsIn(text string)

RecordSecretsIn records every token value text holds, such as a command's output or a response body.

func RecordedSecrets

func RecordedSecrets() []string

RecordedSecrets returns the secret values recorded so far.

Types

type Browser

type Browser struct {
	// Client calls the management API with the browser's cookies.
	*management.ClientWithResponses
	// HTTP is the browser's own HTTP client, for requests the generated
	// client cannot shape.
	HTTP *http.Client
	// Header is sent with every request, such as Origin or Sec-Fetch-Site;
	// empty, the browser sends neither, as a client that is no browser.
	Header http.Header
	// contains filtered or unexported fields
}

Browser is a client of the management API as the console is: it holds cookies, and sends the fetch metadata a browser would.

func NewBrowser

func NewBrowser(t testing.TB, baseURL string) *Browser

NewBrowser returns a browser of the console served at baseURL, such as an in-process Server's URL, holding no cookie.

func (*Browser) Cookie

func (b *Browser) Cookie(name string) string

Cookie returns the value of the browser's cookie called name, "" when it holds none.

func (*Browser) Do

func (b *Browser) Do(t testing.TB, method, path, contentType, body string) (*http.Response, string)

Do sends a request of method to path under the server's URL with body as contentType, and returns the response with its body read.

func (*Browser) SetCookie

func (b *Browser) SetCookie(name, value string)

SetCookie makes the browser hold the cookie name with value, such as a forged or an old session cookie.

func (*Browser) SignIn

func (b *Browser) SignIn(t testing.TB, email, password string) *management.Me

SignIn signs in as email with password, failing the test unless the session opens.

type LogRecord

type LogRecord struct {
	Level   slog.Level
	Message string
	// Attrs holds every attribute by its key, group names joined with dots
	// ("http.status"), with LogValuers resolved.
	Attrs map[string]any
}

LogRecord is one record a LogSink captured.

type LogSink

type LogSink struct {
	// contains filtered or unexported fields
}

LogSink captures what a logger writes as structured records, at every level, so a test asserts on fields rather than on formatted text. It is safe for concurrent use: a server logs from many goroutines.

func NewLogSink

func NewLogSink() *LogSink

NewLogSink returns an empty sink.

func (*LogSink) Find

func (s *LogSink) Find(message string) []LogRecord

Find returns the records captured so far with the given message.

func (*LogSink) Logger

func (s *LogSink) Logger() *slog.Logger

Logger returns a logger writing into the sink.

func (*LogSink) Records

func (s *LogSink) Records() []LogRecord

Records returns every record captured so far.

type Member

type Member struct {
	ID       access.MemberID
	Email    string
	Password string
}

Member is a member a test created, with what they sign in with.

func NewMember

func NewMember(t testing.TB, pool *pgxpool.Pool, opts ...MemberOption) Member

NewMember creates an active member on pool, who holds no grant and signs in with MemberPassword. An invited member holds no password, as one who has not accepted their invitation.

type MemberOption

type MemberOption func(*access.Member)

MemberOption changes the member NewMember creates.

func AsInstanceAdmin

func AsInstanceAdmin() MemberOption

AsInstanceAdmin makes the member an instance admin.

func WithDisplayName

func WithDisplayName(name string) MemberOption

WithDisplayName gives the member name instead of "Test Member".

func WithEmail

func WithEmail(email string) MemberOption

WithEmail gives the member email instead of a random one.

func WithStatus

func WithStatus(s access.MemberStatus) MemberOption

WithStatus gives the member status instead of active.

type QueryLog

type QueryLog struct {
	// contains filtered or unexported fields
}

QueryLog records the SQL of every statement a pool sends, so a test can show how many queries a request costs.

func TracedPool

func TracedPool(t testing.TB) (*pgxpool.Pool, *QueryLog)

TracedPool returns a pool of its own on the package's migrated schema whose statements log records, closed when the test ends.

func (*QueryLog) Containing

func (l *QueryLog) Containing(text string) int

Containing returns how many statements recorded since the last Reset hold text.

func (*QueryLog) Reset

func (l *QueryLog) Reset()

Reset forgets every statement recorded so far.

func (*QueryLog) TraceQueryEnd

func (l *QueryLog) TraceQueryEnd(context.Context, *pgx.Conn, pgx.TraceQueryEndData)

TraceQueryEnd does nothing: a statement counts once it is sent.

func (*QueryLog) TraceQueryStart

func (l *QueryLog) TraceQueryStart(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryStartData) context.Context

TraceQueryStart records the statement.

type RestorePoint

type RestorePoint struct {
	// contains filtered or unexported fields
}

RestorePoint is what an environment held when it was taken, to take the environment back there as restoring a backup, or failing over to a replica that lost recent commits, would.

func TakeRestorePoint

func TakeRestorePoint(t testing.TB, pool *pgxpool.Pool, environment workspace.EnvironmentID) *RestorePoint

TakeRestorePoint records what environment holds now: its ruleset version and its flags' configurations.

It reads tables, unlike any test: no API answers what a database restore brings back, and this is a fault the test kit injects, not an observation.

func (*RestorePoint) Restore

func (p *RestorePoint) Restore(t testing.TB, replicas ...*Server)

Restore takes the environment back to the restore point, losing every change to its ruleset version and its flags' configurations since, and then restarts the listeners of replicas, as a database coming back from a restore or a failover makes every replica reconnect. Nothing is notified: a restored database announces nothing of what it lost.

type Server

type Server struct {
	// URL is the base URL, such as http://127.0.0.1:53211.
	URL string
	// Logs captures everything the server logs.
	Logs *LogSink
	// contains filtered or unexported fields
}

Server is a replica's public handler served in-process, for black-box HTTP tests without a network listener of the binary's own.

func StartServer

func StartServer(t testing.TB, opts ...ServerOption) *Server

StartServer serves the public handler until the test ends.

func (*Server) CloseBackground

func (s *Server) CloseBackground()

CloseBackground ends the work the replica's use cases started on their own, such as ruleset loads nobody waits for, as stopping the replica does.

func (*Server) Drain

func (s *Server) Drain()

Drain begins the replica's drain, as the stop signal does.

func (*Server) Listen

func (s *Server) Listen(channel string, h pglisten.Handler, opts pglisten.Options)

Listen starts a notification listener of the server's replica, reported on its registry, until the test ends.

func (*Server) RestartListeners

func (s *Server) RestartListeners(t testing.TB)

RestartListeners ends the replica's notification listeners and starts them again on new connections, as a database failover or restore makes them do.

func (*Server) Scrape

func (s *Server) Scrape(t testing.TB) string

Scrape returns the server's metrics in the Prometheus text format, as the metrics listener serves them.

func (*Server) Tick

func (s *Server) Tick(t testing.TB, name string) error

Tick runs one round of the worker called name, through the runner's wrapper. The in-process server never starts the workers' timers: a test drives every round it wants, when it wants.

type ServerOption

type ServerOption func(*serverOptions)

ServerOption changes what the in-process server is built with.

func WithBaseURL

func WithBaseURL(baseURL string) ServerOption

WithBaseURL serves as if the console's public URL were baseURL, such as https://flags.example.com.

func WithClock

func WithClock(c clock.Clock) ServerOption

WithClock serves with c as the application clock instead of the wall clock.

func WithConsole

func WithConsole(defaultLocale string) ServerOption

WithConsole serves the embedded console too, as serve does, its entry document naming defaultLocale.

func WithEdge

func WithEdge(change func(*flaghttp.Options)) ServerOption

WithEdge changes the edge's options, which otherwise are the defaults of the configuration.

func WithInsecureCookies

func WithInsecureCookies() ServerOption

WithInsecureCookies serves as FLAGNETIC_INSECURE_COOKIES does.

func WithListenerOptions

func WithListenerOptions(o pglisten.Options) ServerOption

WithListenerOptions starts the replica's notification listeners with o, such as a short ping interval and the fault hook that silences them.

func WithPool

func WithPool(pool *pgxpool.Pool) ServerOption

WithPool serves with pool instead of the package's migrated one, such as a pool whose PostgreSQL is unreachable.

func WithRateLimits

func WithRateLimits(change func(*config.RateLimits)) ServerOption

WithRateLimits changes the SDK API's limits, which otherwise are the defaults of the configuration.

func WithRoute

func WithRoute(pattern string, build func(*flaghttp.Server) http.Handler, opts ...flaghttp.RouteOption) ServerOption

WithRoute mounts the handler build returns on pattern, for a test to exercise the edge through routes of its own. build receives the server, to answer errors through it or log with its logger.

func WithRulesetLoadFault

func WithRulesetLoadFault(f *pgdelivery.RulesetLoadFault) ServerOption

WithRulesetLoadFault lets f stall the replica's ruleset materializations.

func WithWorker

func WithWorker(w worker.Worker) ServerOption

WithWorker registers w with the server's runner, for Tick.

Jump to

Keyboard shortcuts

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