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
- Variables
- func Bootstrap(t testing.TB, pool *pgxpool.Pool) string
- func Client(t testing.TB, srv *Server, token string) *management.ClientWithResponses
- func Clock() *clock.Fake
- func DatabaseURL(t testing.TB) string
- func EmptyDatabase(t testing.TB) string
- func FindSecretsInAudit(ctx context.Context, pool *pgxpool.Pool, secrets []string) error
- func FreshPool(t testing.TB) *pgxpool.Pool
- func Grant(t testing.TB, pool *pgxpool.Pool, project workspace.ProjectID, ...)
- func GrantedToken(t testing.TB, pool *pgxpool.Pool, project workspace.ProjectID, ...) string
- func IDs(c clock.Clock) *id.Source
- func InstanceAdminToken(t testing.TB) string
- func Main(m *testing.M) int
- func MemberToken(t testing.TB, pool *pgxpool.Pool, scopes ...access.Scope) string
- func Metric(t testing.TB, scrape, series string) float64
- func PersonalToken(t testing.TB, pool *pgxpool.Pool, member access.MemberID, name string, ...) string
- func Pool(t testing.TB) *pgxpool.Pool
- func ProjectToken(t testing.TB, pool *pgxpool.Pool, project workspace.ProjectID, ...) string
- func Record(pool *pgxpool.Pool) *appgovernance.Record
- func RecordSecret(v string)
- func RecordSecretsIn(text string)
- func RecordedSecrets() []string
- func SilenceableListener(f *pglisten.Fault) pglisten.Options
- type Browser
- type EventStream
- type Frame
- type LogRecord
- type LogSink
- type Member
- type MemberOption
- type QueryLog
- type ReceivedCall
- type Receiver
- type Reply
- type RestorePoint
- type Server
- func (s *Server) AwaitListening(t testing.TB, channel string)
- func (s *Server) CloseBackground()
- func (s *Server) Drain()
- func (s *Server) HoldNextIngest(t testing.TB) (written <-chan struct{}, release func())
- func (s *Server) Listen(channel string, h pglisten.Handler, opts pglisten.Options)
- func (s *Server) RestartListeners(t testing.TB)
- func (s *Server) Scrape(t testing.TB) string
- func (s *Server) Tick(t testing.TB, name string) error
- func (s *Server) TickRollup(t testing.TB, name string)
- type ServerOption
- func WithAuditExportMaxEntries(n int) ServerOption
- func WithBaseURL(baseURL string) ServerOption
- func WithClock(c clock.Clock) ServerOption
- func WithConsole(defaultLocale string) ServerOption
- func WithDigestSlot(slot governance.DigestSlot) ServerOption
- func WithEdge(change func(*flaghttp.Options)) ServerOption
- func WithInsecureCookies() ServerOption
- func WithListenerOptions(o pglisten.Options) ServerOption
- func WithPool(pool *pgxpool.Pool) ServerOption
- func WithRateLimits(change func(*config.RateLimits)) ServerOption
- func WithRoute(pattern string, build func(*flaghttp.Server) http.Handler, ...) ServerOption
- func WithRulesetLoadFault(f *pgdelivery.RulesetLoadFault) ServerOption
- func WithWebhookTargets(p governance.TargetPolicy) ServerOption
- func WithWorker(w worker.Worker) ServerOption
Constants ¶
const ( InstanceAdminEmail = "admin@example.com" InstanceAdminName = "Test Admin" InstanceAdminPassword = "lantern-quartz-meadow-2291" )
The instance admin every test kit database is bootstrapped with.
const MemberPassword = "tangerine-violin-orbit-1987"
MemberPassword is the password of every member NewMember creates.
const SecretKey = "test secret key of the in-process server, 32+ bytes"
SecretKey is the secret key of every in-process server.
Variables ¶
Start is the time a test's fake clock reads until the test moves it.
Functions ¶
func Bootstrap ¶
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 DatabaseURL ¶
DatabaseURL returns the connection string of the package's migrated schema.
func EmptyDatabase ¶
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 ¶
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 ¶
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 InstanceAdminToken ¶
InstanceAdminToken returns the bootstrap token of the package's database, bootstrapping its instance admin on first use.
func Main ¶
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 ¶
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 ¶
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 ¶
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 Record ¶ added in v0.2.0
func Record(pool *pgxpool.Pool) *appgovernance.Record
Record returns the governance service every context records its audit entries through, on pool, as the server wires it.
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.
func SilenceableListener ¶ added in v0.2.0
SilenceableListener returns listener options whose fault lets a test silence the listener and have it found deaf within about a second. Pings go out every 50ms so the silence is noticed soon after it starts, but each may take a full second to come back: under the race detector on a busy CI runner a round trip to PostgreSQL can exceed a tighter timeout, and a listener found deaf by a slow pong before the test silenced it waits out its backoff instead of being up when the test expects it to be. Once found deaf while silenced, the listener stays down until the fault is restored, so the default backoff serves.
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 ¶
NewBrowser returns a browser of the console served at baseURL, such as an in-process Server's URL, holding no cookie.
func (*Browser) Cookie ¶
Cookie returns the value of the browser's cookie called name, "" when it holds none.
func (*Browser) Do ¶
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.
type EventStream ¶ added in v0.2.0
type EventStream struct {
// Response is the answer to the request that opened the stream; its
// body is read by the stream unless the status is not 200.
Response *http.Response
// contains filtered or unexported fields
}
EventStream is a server-sent event stream a test holds open.
func OpenEventStream ¶ added in v0.2.0
OpenEventStream sends req through c, nil for the default client, and returns its answer whatever its status; a 200's frames are read as they arrive. The stream is closed when the test ends, or by Close.
func (*EventStream) Close ¶ added in v0.2.0
func (s *EventStream) Close()
Close ends the stream from the client's side.
func (*EventStream) Ended ¶ added in v0.2.0
func (s *EventStream) Ended(d time.Duration) bool
Ended reports whether the stream ends within d, frames before the end skipped.
func (*EventStream) Next ¶ added in v0.2.0
func (s *EventStream) Next(t testing.TB) Frame
Next returns the next frame, failing when none arrives within 5 seconds.
func (*EventStream) Quiet ¶ added in v0.2.0
func (s *EventStream) Quiet(t testing.TB, d time.Duration)
Quiet fails when a frame arrives, or the stream ends, within d.
func (*EventStream) Started ¶ added in v0.2.0
func (s *EventStream) Started(t testing.TB)
Started fails unless s is an open event stream, unbuffered and uncached, whose first frame is retry: 3000 alone. A stream's timers are armed by the time it is written, so a test may move its clock from then on.
type Frame ¶ added in v0.2.0
Frame is one server-sent event frame: its fields by name, a comment under "comment".
func (Frame) IsHeartbeat ¶ added in v0.2.0
IsHeartbeat reports whether f is the heartbeat comment.
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.
type MemberOption ¶
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 ¶
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 ¶
Containing returns how many statements recorded since the last Reset hold text.
func (*QueryLog) TraceQueryEnd ¶
TraceQueryEnd does nothing: a statement counts once it is sent.
type ReceivedCall ¶ added in v0.2.0
ReceivedCall is a call a Receiver was sent.
func (ReceivedCall) Envelope ¶ added in v0.2.0
func (c ReceivedCall) Envelope(t testing.TB) map[string]any
Envelope returns the call's body decoded.
func (ReceivedCall) Verifies ¶ added in v0.2.0
func (c ReceivedCall) Verifies(secret string) bool
Verifies reports whether the call's signature holds under secret, checked as a receiver written from the documentation checks it: one of the comma separated `v1=` values of X-Flagnetic-Signature is the lower-case hex of HMAC-SHA256 over "{X-Flagnetic-Timestamp}.{body}" keyed by the secret's bytes.
type Receiver ¶ added in v0.2.0
type Receiver struct {
// URL is where the receiver listens, its path /hook.
URL string
// contains filtered or unexported fields
}
Receiver is a webhook receiver in the test: a plain http server on loopback, so the server under test must allow http and private networks (WithWebhookTargets), that records every call and answers each with the next reply scripted, the last one repeating.
func StartReceiver ¶ added in v0.2.0
StartReceiver starts a receiver answering replies in turn, the last one repeating; 200 to every call when there are none.
func (*Receiver) AwaitCall ¶ added in v0.2.0
AwaitCall waits for the next call to arrive, failing the test after ten seconds.
func (*Receiver) Calls ¶ added in v0.2.0
func (r *Receiver) Calls() []ReceivedCall
Calls returns the calls received so far, in the order they arrived.
type Reply ¶ added in v0.2.0
type Reply struct {
// Status is the status answered; 200 when zero.
Status int
Body string
// Delay holds the answer this long, so a recorded latency or a timeout
// shows.
Delay time.Duration
// Redirect, when set, is the Location answered with a 3xx Status.
Redirect string
// Drop closes the connection without an answer.
Drop bool
// Release, when set, holds the answer until it is closed or the call is
// abandoned, so a test can act while an attempt is in flight.
Release <-chan struct{}
}
Reply is how a Receiver answers one call.
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) AwaitListening ¶ added in v0.2.0
AwaitListening returns once the replica listens on channel, failing after 5 seconds. A replica starts listening shortly after it starts serving; a test that must not see what a replica does while it is not listening yet waits for it.
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) HoldNextIngest ¶ added in v0.2.0
HoldNextIngest keeps the transaction of the next batch of events the server ingests open once its rows are written, so a test can show what a transaction still open holds back. written is closed then; release lets it commit, and is called when the test ends at the latest.
func (*Server) Listen ¶
Listen starts a notification listener of the server's replica, reported on its registry, until the test ends.
func (*Server) RestartListeners ¶
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 ¶
Scrape returns the server's metrics in the Prometheus text format, as the metrics listener serves them.
func (*Server) Tick ¶
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.
func (*Server) TickRollup ¶ added in v0.2.0
TickRollup runs one round of the rollup worker called name, once every transaction running in the database when it was called has ended, except those a test holds open on purpose: a rollup reads only below the snapshot horizon, which any transaction of another test, of this package or another one sharing the database, holds back while it runs. What the test committed before the call is then read by the round.
type ServerOption ¶
type ServerOption func(*serverOptions)
ServerOption changes what the in-process server is built with.
func WithAuditExportMaxEntries ¶ added in v0.2.0
func WithAuditExportMaxEntries(n int) ServerOption
WithAuditExportMaxEntries serves with n as the most entries one download of the audit log may hold, instead of the configuration's default.
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 WithDigestSlot ¶ added in v0.2.0
func WithDigestSlot(slot governance.DigestSlot) ServerOption
WithDigestSlot serves with the weekly stale-flag digest due at slot instead of the configuration's default.
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 WithWebhookTargets ¶ added in v0.2.0
func WithWebhookTargets(p governance.TargetPolicy) ServerOption
WithWebhookTargets serves allowing webhook targets as p does, such as a receiver the test runs on loopback over plain http.
func WithWorker ¶
func WithWorker(w worker.Worker) ServerOption
WithWorker registers w with the server's runner, for Tick.