testsupport

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Overview

Package testsupport builds migrated databases for the Auth-All test suites.

Index

Constants

View Source
const PgBouncerDSNEnv = "AUTHALL_PGBOUNCER_DSN"

PgBouncerDSNEnv names the environment variable that points at the test PgBouncer instance. The verification command sets it.

View Source
const PgBouncerRequiredEnv = "AUTHALL_REQUIRE_PGBOUNCER"

PgBouncerRequiredEnv makes the PgBouncer run mandatory.

View Source
const PostgresDSNEnv = "AUTHALL_POSTGRES_DSN"

PostgresDSNEnv names the environment variable that points at the test PostgreSQL instance. The verification command sets it.

View Source
const PostgresRequiredEnv = "AUTHALL_REQUIRE_POSTGRES"

PostgresRequiredEnv names the environment variable that makes the PostgreSQL run mandatory. The verification command sets it to "1", so a missing DSN fails the suite there. A plain "go test ./..." leaves it empty, so the PostgreSQL tests skip instead of fail.

Variables

This section is empty.

Functions

func MigrateSchema

func MigrateSchema(t *testing.T, s store.Store, sc *schema.Schema)

MigrateSchema applies an effective schema to a store.

func NewPostgres

func NewPostgres(t *testing.T) store.Store

NewPostgres returns a migrated PostgreSQL store inside a private schema. The schema is dropped when the test ends.

func NewPostgresPool added in v0.3.0

func NewPostgresPool(t *testing.T, dsn string, o schema.Options, opts ...postgres.Option) store.Store

NewPostgresPool returns a migrated store over a pgx pool that points at dsn.

A transaction pooler gives one server connection for one transaction only, so the test cannot own a private schema through the search path. Every store gets a unique table prefix instead, and the cleanup drops those tables.

func NewPostgresWithOptions added in v0.3.0

func NewPostgresWithOptions(t *testing.T, o schema.Options) store.Store

NewPostgresWithOptions returns a migrated PostgreSQL store that uses the given physical schema options.

func NewSQLite

func NewSQLite(t *testing.T) store.Store

NewSQLite returns a migrated SQLite store backed by a temporary file.

func NewSQLiteWithOptions added in v0.3.0

func NewSQLiteWithOptions(t *testing.T, o schema.Options) store.Store

NewSQLiteWithOptions returns a migrated SQLite store that uses the given physical schema options.

func NewUser added in v0.3.0

func NewUser(address string) *store.User

NewUser returns a valid user value for a store test.

func PgBouncerDSN added in v0.3.0

func PgBouncerDSN(t *testing.T) string

PgBouncerDSN returns the configured PgBouncer DSN. It skips the test when no DSN exists, and it fails when the run is mandatory.

func PostgresDSN

func PostgresDSN(t *testing.T) string

PostgresDSN returns the configured PostgreSQL DSN.

A missing DSN skips the test, so a first "go test ./..." on a new checkout reports no failure. A missing DSN fails the test when PostgresRequiredEnv is set, because the PostgreSQL contract run is required in verification.

func QueryParam

func QueryParam(t *testing.T, target, name string) string

QueryParam returns one query parameter of a URL.

func RawDB

func RawDB(t *testing.T, path string) *sql.DB

RawDB opens a second handle on the same SQLite file for direct inspection.

func SignChallenge

func SignChallenge(verifier string) string

SignChallenge returns the S256 challenge of a verifier.

func TokenFromURL

func TokenFromURL(t *testing.T, link string) string

TokenFromURL returns the token query parameter of a link.

func UniquePrefix added in v0.3.0

func UniquePrefix() string

UniquePrefix returns a table prefix that no other test uses.

Types

type AuthResult

type AuthResult struct {
	User *struct {
		ID            string `json:"id"`
		Email         string `json:"email"`
		EmailVerified bool   `json:"emailVerified"`
		Name          string `json:"name"`
	} `json:"user"`
	Session *struct {
		ID        string `json:"id"`
		UserID    string `json:"userId"`
		ExpiresAt string `json:"expiresAt"`
	} `json:"session"`
	EmailVerificationRequired bool `json:"emailVerificationRequired"`
}

AuthResult is the decoded body of a sign-up or sign-in response.

type Clock

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

Clock is a controllable clock for deterministic expiry tests.

func NewClock

func NewClock() *Clock

NewClock returns a clock that starts at the current time. A test moves it with Advance, so expiry behavior stays deterministic while cookie lifetimes stay valid for the HTTP client.

func NewClockAt

func NewClockAt(start time.Time) *Clock

NewClockAt returns a clock that starts at a fixed time.

func (*Clock) Advance

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

Advance moves the clock forward.

func (*Clock) Now

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

Now returns the current clock value.

type FakeGitHub

type FakeGitHub struct {
	Server *httptest.Server
	// contains filtered or unexported fields
}

FakeGitHub is a deterministic replacement for the GitHub OAuth endpoints.

func NewFakeGitHub

func NewFakeGitHub(t *testing.T) *FakeGitHub

NewFakeGitHub starts a fake GitHub server.

func (*FakeGitHub) Endpoints

func (f *FakeGitHub) Endpoints() (authURL, tokenURL, userURL, emailsURL string)

Endpoints returns the fake authorize, token, user, and emails URLs.

func (*FakeGitHub) SetAccount

func (f *FakeGitHub) SetAccount(id int64, address string, verified bool)

SetAccount changes the reported provider account.

type FakeGoogle

type FakeGoogle struct {
	Server *httptest.Server
	// contains filtered or unexported fields
}

FakeGoogle is a deterministic replacement for the Google OpenID Connect endpoints. It signs identity tokens with a generated RSA key.

func NewFakeGoogle

func NewFakeGoogle(t *testing.T, clientID string) *FakeGoogle

NewFakeGoogle starts a fake Google server for one client id.

func (*FakeGoogle) DiscoveryCount added in v0.2.0

func (f *FakeGoogle) DiscoveryCount() int

DiscoveryCount returns the number of discovery document fetches.

func (*FakeGoogle) Endpoints

func (f *FakeGoogle) Endpoints() (authURL, tokenURL, jwksURL, issuer string)

Endpoints returns the fake authorize, token, key set, and issuer URLs.

func (*FakeGoogle) IDToken

func (f *FakeGoogle) IDToken() string

IDToken returns a signed identity token for the current configuration.

func (*FakeGoogle) Issuer added in v0.2.0

func (f *FakeGoogle) Issuer() string

Issuer returns the base URL of the fake issuer.

func (*FakeGoogle) SetAccount

func (f *FakeGoogle) SetAccount(subject, address string, verified bool)

SetAccount changes the reported subject and address.

func (*FakeGoogle) SetDiscoveryIssuer added in v0.2.0

func (f *FakeGoogle) SetDiscoveryIssuer(v string)

SetDiscoveryIssuer overrides the issuer field of the discovery document.

func (*FakeGoogle) SetDiscoveryTokenURL added in v0.2.0

func (f *FakeGoogle) SetDiscoveryTokenURL(v string)

SetDiscoveryTokenURL overrides the token endpoint of the discovery document.

func (*FakeGoogle) SetExpectedChallenge

func (f *FakeGoogle) SetExpectedChallenge(challenge string)

SetExpectedChallenge makes the token endpoint validate the PKCE verifier.

func (*FakeGoogle) SetExpiryOffset

func (f *FakeGoogle) SetExpiryOffset(d time.Duration)

SetExpiryOffset changes how long the identity token stays valid.

func (*FakeGoogle) SetIssuer

func (f *FakeGoogle) SetIssuer(v string)

SetIssuer overrides the issuer claim of the identity token.

func (*FakeGoogle) SetNonce

func (f *FakeGoogle) SetNonce(v string)

SetNonce sets the nonce the next identity token carries.

type Harness

type Harness struct {
	T       *testing.T
	Auth    *authall.Auth
	Server  *httptest.Server
	BaseURL string
	Client  *http.Client
	Mail    *MailBox
	Store   store.Store
	// contains filtered or unexported fields
}

Harness runs one configured Auth-All instance behind a test HTTP server.

func NewHarness

func NewHarness(t *testing.T, opts ...authall.Option) *Harness

NewHarness builds an Auth-All instance over SQLite behind a test server. The supplied options are applied after the defaults, so a test can override them.

func NewHarnessWithStore

func NewHarnessWithStore(t *testing.T, s store.Store, opts ...authall.Option) *Harness

NewHarnessWithStore builds a harness over a supplied store.

func (*Harness) ClearCookies

func (h *Harness) ClearCookies()

ClearCookies removes every stored cookie, which simulates a new browser.

func (*Harness) Do

func (h *Harness) Do(method, path string, body any, opts ...RequestOption) *Response

Do sends a request to an Auth-All path with a JSON body.

func (*Harness) DoForm

func (h *Harness) DoForm(target string, fields map[string]string, opts ...RequestOption) *Response

DoForm sends a form submission to an Auth-All path. The confirmation page of the Magic Link plugin submits a plain HTML form, so a test can reproduce it.

func (*Harness) DoURL

func (h *Harness) DoURL(method, target string, body any, opts ...RequestOption) *Response

DoURL sends a request to an absolute URL with a JSON body.

func (*Harness) GetSession

func (h *Harness) GetSession(opts ...RequestOption) AuthResult

GetSession reads the current session.

func (*Harness) Handle added in v0.2.0

func (h *Harness) Handle(pattern string, handler http.Handler)

Handle mounts one application route beside the Auth-All routes. A test uses it to put a handler behind the Auth-All middleware.

func (*Harness) RestoreCookies added in v0.3.0

func (h *Harness) RestoreCookies(jar http.CookieJar)

RestoreCookies installs an earlier cookie jar.

func (*Harness) SaveCookies added in v0.3.0

func (h *Harness) SaveCookies() http.CookieJar

SaveCookies returns the cookie jar of the client, so a test can come back to one browser after it used another one.

func (*Harness) SessionCookie

func (h *Harness) SessionCookie() *http.Cookie

SessionCookie returns the current session cookie of the client jar.

func (*Harness) SignIn

func (h *Harness) SignIn(address, password string) (*Response, AuthResult)

SignIn performs an email and password sign-in.

func (*Harness) SignUp

func (h *Harness) SignUp(address, password string) (*Response, AuthResult)

SignUp performs an email and password sign-up.

func (*Harness) URL

func (h *Harness) URL(path string) string

URL returns the absolute URL of an Auth-All path.

type MailBox

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

MailBox collects the messages Auth-All asks the application to send.

func (*MailBox) All

func (m *MailBox) All() []email.Message

All returns every collected message.

func (*MailBox) Count

func (m *MailBox) Count() int

Count returns the number of collected messages.

func (*MailBox) Find

func (m *MailBox) Find(intent email.Intent) (email.Message, bool)

Find returns whether a message with one intent exists.

func (*MailBox) Last

func (m *MailBox) Last(t *testing.T, intent email.Intent) email.Message

Last returns the most recent message with one intent.

func (*MailBox) Reset

func (m *MailBox) Reset()

Reset clears the collected messages.

func (*MailBox) Send

func (m *MailBox) Send(_ context.Context, msg email.Message) error

Send implements email.Sender.

type RequestOption

type RequestOption func(*http.Request)

RequestOption changes one request before it is sent.

func WithBearer

func WithBearer(token string) RequestOption

WithBearer sends the session token in the authorization header.

func WithHeader

func WithHeader(name, value string) RequestOption

WithHeader sets one request header.

func WithoutOrigin

func WithoutOrigin() RequestOption

WithoutOrigin removes the browser origin header.

type Response

type Response struct {
	Status  int
	Header  http.Header
	Body    []byte
	Cookies []*http.Cookie
}

Response is one captured HTTP response.

func (*Response) Decode

func (r *Response) Decode(t *testing.T, dst any)

Decode reads the JSON body.

func (*Response) ErrorCode

func (r *Response) ErrorCode(t *testing.T) string

ErrorCode returns the stable error code of a failed response.

func (*Response) Location

func (r *Response) Location() string

Location returns the redirect target.

Jump to

Keyboard shortcuts

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