testkit

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 82 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 (
	MailpitUser = "relay"
	// The credentials guard a throwaway container.
	MailpitPassword = "mailpit-relay-pass-8812" //nolint:gosec // a test credential
)

The credentials of the Mailpit modes that ask for them.

View Source
const DexPublicURL = "http://localhost:8080"

DexPublicURL is the public address of the instance Dex's redirect URIs are registered for.

View Source
const KeycloakPublicURL = "http://localhost:8080"

KeycloakPublicURL is the public address of the instance the SAML clients' entity IDs and ACS addresses are registered for.

View Source
const MailpitAllowedDomain = "picky.example"

MailpitAllowedDomain is the only domain a MailpitPicky takes mail for.

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 DexUsers = []DexUser{
	{Email: "ada@example.com", Password: "ada-password", Groups: []string{"engineering", "admins"}},
	{Email: "grace@example.com", Password: "grace-password", Groups: []string{"engineering"}},
	{Email: "alan@example.org", Password: "alan-password"},
}

DexUsers are the people every Dex of the test kit knows.

View Source
var KeycloakUsers = []KeycloakUser{
	{Username: "ada", Email: "ada@saml.example.com", FirstName: "Ada", Password: "ada-password", Groups: []string{"engineering", "admins"}},
	{Username: "grace", Email: "grace@saml.example.com", FirstName: "Grace", Password: "grace-password", Groups: []string{"engineering"}},
	{Username: "alan", Email: "alan@saml.example.org", FirstName: "Alan", Password: "alan-password"},
}

KeycloakUsers are the people every Keycloak of the test kit knows, all with verified emails.

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 DexLogin added in v0.3.0

func DexLogin(user DexUser) func(page string) (string, url.Values, bool)

DexLogin answers Dex's login page as user.

func DexSlug added in v0.3.0

func DexSlug(t testing.TB) string

DexSlug returns a provider slug that Dex's client has the redirect URI registered for, under DexPublicURL, a new one at each call: Dex lists the redirect URIs of its client exactly, and the container is started once per package.

func Doc added in v0.4.0

func Doc(t testing.TB, name string) string

Doc returns the text of docs/name, so that a test can hold a page to the code it describes.

func DocAfterMarker added in v0.4.0

func DocAfterMarker(t testing.TB, doc, marker string) string

DocAfterMarker is doc from the line after `<!-- marker -->` on.

func DocMetricLabels added in v0.4.0

func DocMetricLabels(doc, metric string) ([]string, bool)

DocMetricLabels returns the labels of the row of metric in doc's metrics table, sorted, and whether doc has the row.

func DocSQL added in v0.4.0

func DocSQL(t testing.TB, doc, marker string) string

DocSQL is the sql block following `<!-- marker -->`, without its trailing semicolon.

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 KeycloakLogin added in v0.3.0

func KeycloakLogin(user KeycloakUser) func(page string) (string, url.Values, bool)

KeycloakLogin answers Keycloak's pages as user: its login form with the person's credentials, and the page that hands the browser the SAML response to post to the ACS.

func KeycloakSlug added in v0.3.0

func KeycloakSlug(t testing.TB) string

KeycloakSlug returns a provider slug that Keycloak has a SAML client for, under KeycloakPublicURL, a new one at each call: a client is registered by its entity ID, which names the slug, and the container is started once per package.

func MailpitRoots added in v0.3.0

func MailpitRoots() *x509.CertPool

MailpitRoots are the roots the SMTP servers' certificates are signed by; a test serving with WithMailRoots trusts them.

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 OtherCluster added in v0.3.0

func OtherCluster(t testing.TB) string

OtherCluster returns the connection string of an empty database in a second PostgreSQL cluster, stopped when the test ends: where a logical dump of the package's database is restored to.

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 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 SPCertificates added in v0.3.0

func SPCertificates(metadata []byte) []*x509.Certificate

SPCertificates returns the certificates a service provider's metadata publishes.

func SeedAuditEntries added in v0.4.0

func SeedAuditEntries(t testing.TB, pool *pgxpool.Pool, n, payload int)

SeedAuditEntries writes n entries of the instance's audit log in one statement, each carrying an `after` document of about payload bytes, so a test can make a download large without making n changes through the API. The entries are system entries of no project.

func SilenceableListener added in v0.2.0

func SilenceableListener(f *pglisten.Fault) pglisten.Options

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

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) Post added in v0.3.0

func (b *Browser) Post(t testing.TB, rawURL string, form url.Values, opts VisitOptions) Visit

Post submits form to rawURL as a page an identity provider served would, then follows the redirects it answers like Visit.

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.

func (*Browser) Visit added in v0.3.0

func (b *Browser) Visit(t testing.TB, rawURL string, opts VisitOptions) Visit

Visit follows rawURL as a browser does, hop by hop, carrying the cookies it holds, and returns where it ended: on a response that is not a redirect or a login page opts.Login does not answer, or before an address opts.Stop holds.

type ClickHouse added in v0.4.0

type ClickHouse struct {
	// URL is its HTTP interface as a sink's configuration names it, without
	// credentials.
	URL string
	// Username and Password are the user a sink authenticates as.
	Username, Password string
}

ClickHouse is the package's ClickHouse server.

func StartClickHouse added in v0.4.0

func StartClickHouse(t testing.TB) *ClickHouse

StartClickHouse returns the package's ClickHouse, starting it on first use: the server CLICKHOUSE_URL names (http://user:password@host:8123) when it is set, otherwise a container stopped after the package's last test. Tests share it and isolate by database, see NewDatabase.

func (*ClickHouse) Exec added in v0.4.0

func (ch *ClickHouse) Exec(t testing.TB, statement string)

Exec runs statement, failing the test on any error.

func (*ClickHouse) NewDatabase added in v0.4.0

func (ch *ClickHouse) NewDatabase(t testing.TB) string

NewDatabase creates a uniquely named database for one test, so tests sharing the server never see each other's tables.

func (*ClickHouse) Query added in v0.4.0

func (ch *ClickHouse) Query(t testing.TB, query string) []map[string]any

Query runs query and returns its rows, every number a json.Number.

type Dex added in v0.3.0

type Dex struct {
	// Issuer is the address Dex's discovery document is served under; it is
	// plain http on a loopback address.
	Issuer string
	// ClientID and ClientSecret are the credentials of the client Dex is
	// configured with; it uses PKCE besides.
	ClientID, ClientSecret string
	// Users are the people Dex knows, all with verified emails.
	Users []DexUser
}

Dex is a running Dex, an OpenID Connect provider, configured with one public client that uses PKCE and static users with groups.

func StartDex added in v0.3.0

func StartDex(t testing.TB) *Dex

StartDex returns the package's Dex, starting it on first use: one container serves every test of the package, and ends with the package's tests.

type DexUser added in v0.3.0

type DexUser struct {
	Email    string
	Password string
	Groups   []string
}

DexUser is a person Dex knows.

type DocColumn added in v0.4.0

type DocColumn struct{ Name, Type string }

DocColumn is one row of a documented column table.

func DocColumns added in v0.4.0

func DocColumns(t testing.TB, doc, kind string) []DocColumn

DocColumns is the Column | Type | Meaning table following `<!-- columns:kind -->`.

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

func OpenEventStream(t testing.TB, c *http.Client, req *http.Request) *EventStream

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 Fault added in v0.3.0

type Fault int

Fault is what a ForgingIDP gets wrong in the one ID token it signs next.

const (
	// SignedByOtherKey signs with a key the provider's JWKS does not publish.
	SignedByOtherKey Fault = iota + 1
	// WrongAudience addresses the token to another client.
	WrongAudience
	// WrongIssuer names another issuer.
	WrongIssuer
	// Expired dates the token ten minutes ago, beyond any clock skew.
	Expired
	// WrongNonce answers another nonce than the attempt's.
	WrongNonce
)

The mistakes a forging identity provider makes.

type ForgingIDP added in v0.3.0

type ForgingIDP struct {
	// Issuer is the provider's address, plain http on a loopback address.
	Issuer string
	// ClientID and ClientSecret are the only credentials it accepts.
	ClientID, ClientSecret string
	// contains filtered or unexported fields
}

ForgingIDP is an in-process OIDC provider that signs what a test asks, to produce what a real identity provider never sends: a token signed by another key, for another audience or issuer, expired, or answering another nonce. It fakes the outside party for refusals, never a repository.

func StartForgingIDP added in v0.3.0

func StartForgingIDP(t testing.TB) *ForgingIDP

StartForgingIDP starts a forging provider that ends with the test.

func (*ForgingIDP) DenyNext added in v0.3.0

func (f *ForgingIDP) DenyNext(code string)

DenyNext makes the next authorization end with the error code.

func (*ForgingIDP) FailNext added in v0.3.0

func (f *ForgingIDP) FailNext(fault Fault)

FailNext makes the provider get fault wrong in the next ID token it signs.

func (*ForgingIDP) NextClaims added in v0.3.0

func (f *ForgingIDP) NextClaims(claims map[string]any)

NextClaims sets claims the next ID token holds over its defaults: the subject "subject-1", the email "ada@example.com" and email_verified true. A nil value removes the default claim.

func (*ForgingIDP) NextUserInfo added in v0.3.0

func (f *ForgingIDP) NextUserInfo(claims map[string]any)

NextUserInfo sets what UserInfo answers for the next token, verbatim. While unset, UserInfo answers 404.

type ForgingSAMLIDP added in v0.3.0

type ForgingSAMLIDP struct {
	// EntityID, SSOURL and MetadataURL are its addresses, plain http on a
	// loopback address.
	EntityID, SSOURL, MetadataURL string
	// Certificate is the PEM certificate it signs with.
	Certificate []byte
	// Now is the time its assertions are dated at.
	Now func() time.Time
	// contains filtered or unexported fields
}

ForgingSAMLIDP is an in-process SAML identity provider that builds what a test asks, to produce what a real one never sends: a response unsigned or signed by another key, for another audience or destination, expired, replayed, wrapped, encrypted with a key transport the instance refuses. It fakes the outside party for refusals, never a repository.

func StartForgingSAMLIDP added in v0.3.0

func StartForgingSAMLIDP(t testing.TB) *ForgingSAMLIDP

StartForgingSAMLIDP starts a forging provider that ends with the test.

func (*ForgingSAMLIDP) Close added in v0.3.0

func (f *ForgingSAMLIDP) Close()

Close stops the provider answering, as an identity provider that went away.

func (*ForgingSAMLIDP) DelayMetadata added in v0.3.0

func (f *ForgingSAMLIDP) DelayMetadata(d time.Duration)

DelayMetadata makes the metadata endpoint take d to answer, so two requests for it overlap.

func (*ForgingSAMLIDP) FailMetadata added in v0.3.0

func (f *ForgingSAMLIDP) FailMetadata(status int)

FailMetadata makes the metadata endpoint answer status, and the metadata again for 0.

func (*ForgingSAMLIDP) Metadata added in v0.3.0

func (f *ForgingSAMLIDP) Metadata(o SAMLMetadataOptions) string

Metadata returns the provider's metadata document.

func (*ForgingSAMLIDP) MetadataFetches added in v0.3.0

func (f *ForgingSAMLIDP) MetadataFetches() int

MetadataFetches is how many times the metadata endpoint was requested.

func (*ForgingSAMLIDP) ParseRequest added in v0.3.0

func (f *ForgingSAMLIDP) ParseRequest(t testing.TB, redirect *url.URL, spMetadata []byte) SAMLRequest

ParseRequest reads the AuthnRequest in the address a browser was sent to the provider's single sign-on endpoint at, and checks the signature of its query against the certificates in spMetadata, the service provider's metadata: Signed says whether it carried one that verified.

func (*ForgingSAMLIDP) Respond added in v0.3.0

Respond builds what the identity provider posts to the ACS in answer to req: the form's SAMLResponse and RelayState.

func (*ForgingSAMLIDP) RotateSigningKey added in v0.3.0

func (f *ForgingSAMLIDP) RotateSigningKey(t testing.TB, keepOld bool)

RotateSigningKey makes the provider sign with a new key and publish its certificate in its metadata, as an identity provider does when its certificate is about to expire. With keepOld the certificate it replaced is published beside the new one; without, it is not.

func (*ForgingSAMLIDP) ServeMetadata added in v0.3.0

func (f *ForgingSAMLIDP) ServeMetadata(o SAMLMetadataOptions)

ServeMetadata changes the mistakes the metadata endpoint makes in what it serves from now on, such as another entity ID.

func (*ForgingSAMLIDP) URL added in v0.3.0

func (f *ForgingSAMLIDP) URL(path string) string

URL returns the address of path on the provider's own server.

type Frame added in v0.2.0

type Frame map[string]string

Frame is one server-sent event frame: its fields by name, a comment under "comment".

func (Frame) IsHeartbeat added in v0.2.0

func (f Frame) IsHeartbeat() bool

IsHeartbeat reports whether f is the heartbeat comment.

type Keycloak added in v0.3.0

type Keycloak struct {
	// MetadataURL is the address of the realm's identity provider metadata,
	// plain http on a loopback address.
	MetadataURL string
	// Users are the people Keycloak knows.
	Users []KeycloakUser
}

Keycloak is a running Keycloak with a realm holding SAML clients, one for each slug KeycloakSlug hands out, and the people KeycloakUsers lists. A client's assertions are signed, carry the attributes email and name and the person's groups as the attribute groups, and name the person by username.

func StartKeycloak added in v0.3.0

func StartKeycloak(t testing.TB) *Keycloak

StartKeycloak returns the package's Keycloak, starting it on first use: one container serves every test of the package, and ends with the package's tests.

type KeycloakUser added in v0.3.0

type KeycloakUser struct {
	Username  string
	Email     string
	FirstName string
	Password  string
	Groups    []string
}

KeycloakUser is a person Keycloak knows.

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 Mailpit added in v0.3.0

type Mailpit struct {
	// Host and Port are where its SMTP server listens, on loopback.
	Host string
	Port int
	// API is the base URL of its HTTP interface.
	API string
	// contains filtered or unexported fields
}

Mailpit is a running Mailpit.

func StartMailpit added in v0.3.0

func StartMailpit(t testing.TB, mode MailpitMode) *Mailpit

StartMailpit returns the package's Mailpit in mode, starting it on first use. Tests share it and isolate by recipient: each mail a test sends goes to an address of its own.

func (*Mailpit) AssertNoMail added in v0.3.0

func (m *Mailpit) AssertNoMail(t testing.TB, address string)

AssertNoMail fails if address has been sent a mail, after the replica's background work is done.

func (*Mailpit) AwaitMails added in v0.3.0

func (m *Mailpit) AwaitMails(t testing.TB, address string, n int) []ReceivedMail

AwaitMails returns the mails sent to address once there are n of them, failing after 10 seconds. Mail leaves a replica in the background, so a test waits for it as the recipient would.

func (*Mailpit) Credentials added in v0.3.0

func (m *Mailpit) Credentials() bool

Credentials reports whether this Mailpit asks the client to authenticate.

func (*Mailpit) MailsTo added in v0.3.0

func (m *Mailpit) MailsTo(t testing.TB, address string) []ReceivedMail

MailsTo returns the mails sent to address, oldest first.

func (*Mailpit) Security added in v0.3.0

func (m *Mailpit) Security() string

Security is how a client reaches this Mailpit's SMTP server, as the SMTP settings name it.

type MailpitMode added in v0.3.0

type MailpitMode string

MailpitMode is how a Mailpit receives mail.

const (
	// MailpitOpen takes mail over a plain connection from anyone.
	MailpitOpen MailpitMode = "open"
	// MailpitAuth takes mail over a plain connection only from MailpitUser.
	MailpitAuth MailpitMode = "auth"
	// MailpitStartTLS takes mail only after STARTTLS, from MailpitUser.
	MailpitStartTLS MailpitMode = "starttls"
	// MailpitTLS takes mail only over TLS from the first byte, from
	// MailpitUser.
	MailpitTLS MailpitMode = "tls"
	// MailpitPicky takes mail over a plain connection only from MailpitUser,
	// and refuses every recipient but those at picky.example: the refusal
	// comes after a login the server accepted.
	MailpitPicky MailpitMode = "picky"
)

The ways a Mailpit receives mail; each is a container of its own, started the first time a test of the package asks for it and stopped after the package's last test.

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 NewInstanceAdmin added in v0.3.0

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

NewInstanceAdmin creates an instance admin on pool and returns them with a personal access token carrying every scope, so a test acts as an instance admin whose address is its own: mail sent to them is theirs alone.

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.

func NewPasswordlessMember added in v0.3.0

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

NewPasswordlessMember creates a member as NewMember does, who holds no password, as one who signs in through an auth provider only: nobody can sign in as them with MemberPassword, which Member.Password still names.

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 WithLocale added in v0.3.0

func WithLocale(locale string) MemberOption

WithLocale gives the member the console language locale.

func WithStatus

func WithStatus(s access.MemberStatus) MemberOption

WithStatus gives the member status instead of active.

type ObjectStorage added in v0.4.0

type ObjectStorage struct {
	// Endpoint is the store's address as a sink's endpoint names it,
	// http://localhost:<port>, so that a virtual-hosted request for
	// <bucket>.localhost resolves to it as well.
	Endpoint string
	// Region is the region the store answers for.
	Region string
	// AccessKeyID and SecretAccessKey are the credentials a sink signs with.
	AccessKeyID, SecretAccessKey string
	// contains filtered or unexported fields
}

ObjectStorage is the package's S3-compatible store: MinIO in a container, or the one S3_ENDPOINT names.

func StartObjectStorage added in v0.4.0

func StartObjectStorage(t testing.TB) *ObjectStorage

StartObjectStorage returns the package's object store, starting it on first use: the one S3_ENDPOINT names, with S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY and S3_REGION (us-east-1 when unset), or a MinIO container stopped after the package's last test. A store S3_ENDPOINT names must accept virtual-hosted requests for <bucket>.localhost (MinIO's MINIO_DOMAIN=localhost) for the path style test to pass. Tests share it and isolate by bucket.

func (*ObjectStorage) Keys added in v0.4.0

func (s *ObjectStorage) Keys(t testing.TB, bucket string) []string

Keys lists every object key in bucket, sorted.

func (*ObjectStorage) NewBucket added in v0.4.0

func (s *ObjectStorage) NewBucket(t testing.TB) string

NewBucket creates a bucket named for no other test, so that tests sharing the store never see each other's objects.

func (*ObjectStorage) Object added in v0.4.0

func (s *ObjectStorage) Object(t testing.TB, bucket, key string) (content []byte, contentType string)

Object reads the content of key in bucket, and its content type.

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 ReceivedCall added in v0.2.0

type ReceivedCall struct {
	Header http.Header
	Body   []byte
}

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 ReceivedMail added in v0.3.0

type ReceivedMail struct {
	ID      string
	From    string
	To      []string
	Subject string
	Text    string
	HTML    string
	Date    time.Time
}

ReceivedMail is a mail Mailpit holds.

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

func StartReceiver(t testing.TB, replies ...Reply) *Receiver

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

func (r *Receiver) AwaitCall(t testing.TB)

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 S3Proxy added in v0.4.0

type S3Proxy struct {
	// Endpoint is the proxy's address as a sink's endpoint names it.
	Endpoint string
	// contains filtered or unexported fields
}

S3Proxy is a proxy in front of the object store that records every request it forwards and can fail the next ones of a method after the store has handled them, as an answer lost on the way back would. It keeps the Host a sink signed, so the store verifies the signature made for the proxy's own address.

func NewS3Proxy added in v0.4.0

func NewS3Proxy(t testing.TB, s *ObjectStorage) *S3Proxy

NewS3Proxy starts a proxy in front of s, closed when t ends.

func (*S3Proxy) FailNext added in v0.4.0

func (p *S3Proxy) FailNext(method string, n int)

FailNext makes the next n requests of method fail with a 500 after the store has handled them.

func (*S3Proxy) Requests added in v0.4.0

func (p *S3Proxy) Requests() []S3Request

Requests lists every request forwarded so far, in order.

type S3Request added in v0.4.0

type S3Request struct {
	Method, Host, Path string
	// Status is what the proxy answered the client.
	Status int
}

S3Request is a request an S3Proxy forwarded.

type SAMLAssertion added in v0.3.0

type SAMLAssertion struct {
	// Subject is the NameID; "subject-1" when empty. NameIDFormat is its
	// format: unspecified when empty.
	Subject      string
	NameIDFormat string
	// Attributes are the assertion's attributes, name to values. Nil asserts
	// an email of "ada@example.com" and a name of "Ada Lovelace".
	Attributes map[string][]string
	// ID is the assertion's ID; random when empty.
	ID string
	// SignResponse signs the Response element instead of the assertion.
	SignResponse bool
	Fault        SAMLFault
	Encryption   SAMLEncryption
	// Until, when not zero, is when the assertion's validity ends, from now:
	// negative for a validity that ended already.
	Until time.Duration
	// EncryptTo is the certificate, PEM encoded, the assertion is encrypted to.
	EncryptTo []byte
}

SAMLAssertion is what a ForgingSAMLIDP asserts of a person, and what it gets wrong.

type SAMLEncryption added in v0.3.0

type SAMLEncryption int

SAMLEncryption is how a ForgingSAMLIDP encrypts the assertion.

const (
	// SAMLPlain leaves the assertion readable.
	SAMLPlain SAMLEncryption = iota
	// SAMLAES128CBC encrypts with AES-128-CBC, the key sent by RSA-OAEP.
	SAMLAES128CBC
	// SAMLAES256GCM encrypts with AES-256-GCM, the key sent by RSA-OAEP.
	SAMLAES256GCM
	// SAMLRSA15 encrypts with AES-128-CBC, the key sent by RSA 1.5, which the instance refuses.
	SAMLRSA15
	// SAMLTripleDES names Triple DES in CBC mode as the encryption, the key sent by RSA-OAEP, which the
	// instance refuses.
	SAMLTripleDES
)

The encryptions of an assertion.

type SAMLFault added in v0.3.0

type SAMLFault int

SAMLFault is what a ForgingSAMLIDP gets wrong in the one response it builds.

const (
	// SAMLUnsigned signs neither the response nor the assertion.
	SAMLUnsigned SAMLFault = iota + 1
	// SAMLSignedByOtherKey signs with a key the provider's metadata does not publish.
	SAMLSignedByOtherKey
	// SAMLWrongAudience addresses the assertion to another audience.
	SAMLWrongAudience
	// SAMLWrongDestination names another destination than the ACS the response is posted to.
	SAMLWrongDestination
	// SAMLWrongInResponseTo answers another request than the attempt's.
	SAMLWrongInResponseTo
	// SAMLNoInResponseTo answers no request: an unsolicited response.
	SAMLNoInResponseTo
	// SAMLExpired dates the assertion's validity ten minutes ago, beyond any clock skew.
	SAMLExpired
	// SAMLNotYetValid starts the assertion's validity ten minutes from now.
	SAMLNotYetValid
	// SAMLWrongIssuer names another entity as the issuer.
	SAMLWrongIssuer
	// SAMLWrapped signs an assertion about one person and wraps it, as an attacker would,
	// beside an unsigned assertion about another.
	SAMLWrapped
	// SAMLDocType puts a DOCTYPE in front of an otherwise valid response.
	SAMLDocType
	// SAMLFailedStatus answers that the person did not authenticate, with no assertion.
	SAMLFailedStatus
	// SAMLNoAudience leaves the audience restriction out.
	SAMLNoAudience
)

The mistakes a forging SAML identity provider makes.

type SAMLMetadataOptions added in v0.3.0

type SAMLMetadataOptions struct {
	// NoRedirectBinding offers the HTTP-POST binding only.
	NoRedirectBinding bool
	// NoCertificate publishes no signing certificate.
	NoCertificate bool
	// OtherEntityID is the entity ID the metadata names instead of the provider's.
	OtherEntityID string
}

SAMLMetadataOptions are the mistakes a forging provider makes in its metadata.

type SAMLRequest added in v0.3.0

type SAMLRequest struct {
	ID, Issuer, Destination, ACS, NameIDFormat string
	RelayState                                 string
	// Signed is whether the request's query carried a signature that verified
	// against a certificate of the service provider's metadata.
	Signed bool
	// Query is the raw query the browser was sent with.
	Query string
}

SAMLRequest is an AuthnRequest a forging provider was sent.

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) AwaitHorizon added in v0.3.0

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

AwaitHorizon returns once every transaction running in the database when it was called has ended, except those a test holds open on purpose: a reader of raw events reads only below the snapshot horizon, which any transaction of another test holds back while it runs. What the test committed before the call is then below the horizon.

func (*Server) AwaitListening added in v0.2.0

func (s *Server) AwaitListening(t testing.TB, channel string)

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

func (s *Server) HoldNextIngest(t testing.TB) (written <-chan struct{}, release func())

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

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) LoseNextSinkCommit added in v0.3.0

func (s *Server) LoseNextSinkCommit()

LoseNextSinkCommit makes the next batch a sink's target acknowledges go unrecorded, as a replica dying between the acknowledgement and the commit of the stream's cursor would: the stream sends the same batch again, under the same delivery ID, once its lease has run out.

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.

func (*Server) TickRollup added in v0.2.0

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

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 WithAuditExportMaxConcurrent added in v0.4.0

func WithAuditExportMaxConcurrent(n int) ServerOption

WithAuditExportMaxConcurrent serves with n as the most downloads of the audit log running at once, instead of the configuration's default.

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 WithDefaultLocale added in v0.3.0

func WithDefaultLocale(locale string) ServerOption

WithDefaultLocale serves as FLAGNETIC_DEFAULT_LOCALE does.

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 WithMailRoots added in v0.3.0

func WithMailRoots(roots *x509.CertPool) ServerOption

WithMailRoots serves verifying SMTP servers' certificates against roots, such as MailpitRoots, instead of the system's.

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.

type Visit added in v0.3.0

type Visit struct {
	// URL is the address last reached: the last fetched, or the one Stop held.
	URL *url.URL
	// Status and Body are the last response's; zero and empty when Stop held
	// the address before any fetch of it.
	Status int
	Body   string
	// Header is the last response's.
	Header http.Header
}

Visit is where a browser ended up.

func (Visit) Query added in v0.3.0

func (v Visit) Query(name string) string

Query returns the value of the query parameter name of where the visit ended.

type VisitOptions added in v0.3.0

type VisitOptions struct {
	// PublicURL is the address the instance believes it is served at, such as
	// http://localhost:8080; addresses on its origin are fetched from the
	// in-process server instead, as a reverse proxy would send them.
	PublicURL string
	// Login answers an identity provider's login page: the address to post to,
	// relative to the page's, and the form fields. A nil Login, or one
	// answering ok false, ends the visit at the page.
	Login func(page string) (action string, form url.Values, ok bool)
	// Stop ends the visit before the address u is fetched when it returns true.
	Stop func(u *url.URL) bool
}

VisitOptions shape how a Browser follows an address.

Jump to

Keyboard shortcuts

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