testenv

package
v0.0.0-...-df7a9a8 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 32 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 testenv starts a complete Keywell HTTP stack on an httptest server for tests in the web, oidc and api packages (which use external test packages so they can import this one without a cycle).

Index

Constants

View Source
const (
	AdminEmail    = "admin@example.org"
	AdminPassword = "admin password for tests"
)

AdminEmail and AdminPassword are the account AdminClient signs in as.

View Source
const Version = "test"

Version is the version string the test server reports.

Variables

This section is empty.

Functions

This section is empty.

Types

type Clock

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

Clock is a settable time source shared by the session manager and the rate limiters. It starts at the real current time because the store compares session expiry with the real clock.

func (*Clock) Advance

func (c *Clock) Advance(d time.Duration)

Advance moves the clock forward by d.

func (*Clock) Now

func (c *Clock) Now() time.Time

Now returns the clock's current time.

type Env

type Env struct {
	TS    *httptest.Server
	Store *store.Store
	// DB is the store's database, for reading tables the store has no
	// reader for, such as audit_events.
	DB     *sql.DB
	Mailer *mail.Memory
	Cfg    *config.Config
	Clock  *Clock
	// Enc is the server's encryptor, for sealing and opening TOTP secrets.
	Enc *secrets.Encryptor
	// Keys holds the token signing keys, stored in Store and sealed by Enc.
	Keys *oidc.KeyManager
	// Provider serves the OpenID Connect endpoints, on Clock's time.
	Provider *oidc.Provider
	// contains filtered or unexported fields
}

Env is a running test stack.

func New

func New(t *testing.T, opts ...Option) *Env

New builds the full stack: test store, memory mailer, fake clock, the production rate limits, and a config whose PublicURL is the server's URL.

func (*Env) API

func (e *Env) API(t *testing.T, token, method, path string, body any) (map[string]any, *http.Response)

API sends a request to the admin API, with token as its bearer token (none when ""). path is from the server root, such as "/api/v1/me". body is sent as JSON unless it is nil (no body) or an io.Reader (sent as is). It returns the response body decoded as a JSON object (nil when empty) and the response, whose body is already closed. A body that is not a JSON object fails the test. Cookies are never sent.

func (*Env) APIToken

func (e *Env) APIToken(t *testing.T, username string, scope model.APITokenScope) (raw string, account *model.User)

APIToken stores a new API token with scope for the service account username, creating the account (named after its username, in no groups) when there is none, and returns the raw token and the account. Each call makes another token, so calling it twice with one username gives the same account two tokens.

func (*Env) AdminClient

func (e *Env) AdminClient(t *testing.T) (*http.Client, *model.User)

AdminClient returns a client signed in as AdminEmail, a member of the group "Admin", and that member. Both are created when missing: the group as an admin group with no second step. A group "Admin" a test already made is used as it is.

func (*Env) Authorize

func (e *Env) Authorize(t *testing.T, c *http.Client, app *model.Application, pkce bool) (code, verifier, state string)

Authorize asks for a code for app with c, which must be signed in, at app's first redirect URI with scope "openid profile email groups" and a random state and nonce, using PKCE (S256) when pkce is set. It fails the test unless the server redirects back with a code and the same state, and returns the code, the PKCE verifier ("" without PKCE) and the state.

func (*Env) AuthorizeRaw

func (e *Env) AuthorizeRaw(t *testing.T, c *http.Client, params url.Values) *http.Response

AuthorizeRaw sends an authorization request with params from c and returns the response unread; the caller closes its body.

func (*Env) AuthorizeWithNonce

func (e *Env) AuthorizeWithNonce(t *testing.T, c *http.Client, app *model.Application, pkce bool) (code, verifier, state, nonce string)

AuthorizeWithNonce is Authorize that also returns the nonce it sent.

func (*Env) Client

func (e *Env) Client(t *testing.T) *http.Client

Client returns a browser-like client with its own cookie jar that does not follow redirects, so tests can assert on each one.

func (*Env) CreateApp

func (e *Env) CreateApp(t *testing.T, a model.Application, secret string) *model.Application

CreateApp stores a, hashing secret into ClientSecretHash when non-empty.

func (*Env) CreateGroup

func (e *Env) CreateGroup(t *testing.T, name string, isAdmin, requireTOTP bool) *model.Group

CreateGroup creates a group.

func (*Env) CreateUser

func (e *Env) CreateUser(t *testing.T, email, pw string, groups ...string) *model.User

CreateUser creates an active member with the given password (none if empty), adding them to the named groups, which are created if missing.

func (*Env) EnrolTOTP

func (e *Env) EnrolTOTP(t *testing.T, u *model.User) (secret string)

EnrolTOTP enrols u in TOTP directly through the store, as if they had confirmed it, and returns the base32 secret for generating codes. u's TOTP fields are updated to match.

func (*Env) Exchange

func (e *Env) Exchange(t *testing.T, app *model.Application, secret, code, verifier, redirectURI string) (map[string]any, *http.Response)

Exchange trades an authorization code for tokens as app (see PostAsClient), sending verifier as code_verifier when non-empty.

func (*Env) Login

func (e *Env) Login(t *testing.T, c *http.Client, email, pw string)

Login posts the sign-in form with c and fails the test unless the password is accepted: a 303 and a session cookie in c's jar.

func (*Env) Page

func (e *Env) Page(t *testing.T, c *http.Client, path string) (*http.Response, string)

Page gets path with c and returns the response, its body already closed, and the body as text.

func (*Env) PostAsClient

func (e *Env) PostAsClient(t *testing.T, path string, app *model.Application, secret string, form url.Values) (map[string]any, *http.Response)

PostAsClient posts form to path as app: with HTTP Basic credentials when secret is non-empty (each part form-urlencoded, RFC 6749 §2.3.1), else with client_id in the form. It returns the body decoded as a JSON object (nil when empty) and the response, whose body is already closed.

func (*Env) Refresh

func (e *Env) Refresh(t *testing.T, app *model.Application, secret, refreshToken string) (map[string]any, *http.Response)

Refresh redeems refreshToken for new tokens as app (see PostAsClient).

func (*Env) Submit

func (e *Env) Submit(t *testing.T, c *http.Client, path string, form url.Values) (*http.Response, string)

Submit posts form to path with c, as a browser submits a form, and returns the response, its body already closed, and the body as text.

func (*Env) SubmitMultipart

func (e *Env) SubmitMultipart(t *testing.T, c *http.Client, path string, form url.Values, file, filename string, content []byte) (*http.Response, string)

SubmitMultipart posts form plus one file part (field file, named filename, holding content) to path with c, as a browser submits a multipart form, and returns the response and its body as Submit does.

func (*Env) WaitMail

func (e *Env) WaitMail(t *testing.T)

WaitMail waits for the emails the server is sending in the background, so a test can then assert on Mailer.Sent.

type Option

type Option func(*options)

Option adjusts how New builds the stack.

func WithConfig

func WithConfig(f func(*config.Config)) Option

WithConfig edits the config after the defaults (and PublicURL) are set.

func WithLog

func WithLog(log *slog.Logger) Option

WithLog gives the stack log instead of a logger that discards everything, so a test can assert on what the server logs.

func WithMailer

func WithMailer(wrap func(*mail.Memory) mail.Mailer) Option

WithMailer gives the server wrap(Env.Mailer) as its mailer, e.g. to hold or fail sends. Env.Mailer records what the wrapper passes on.

Jump to

Keyboard shortcuts

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