auth0mocktest

package
v0.229.0 Latest Latest
Warning

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

Go to latest
Published: May 27, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package auth0mocktest provides testing.TB-aware helpers for the pkg/auth0mock SDK. It lives in a subpackage (matching the standard library's net/http + net/http/httptest split) so production binaries that import auth0mock don't drag in the testing package just to call SDK methods.

Use this package from _test.go files only — every helper takes a testing.TB and calls Fatalf on failure, which is meaningless outside a test runner.

import (
    "github.com/sergiught/auth0-mock/pkg/auth0mock"
    "github.com/sergiught/auth0-mock/pkg/auth0mock/auth0mocktest"
)

func TestFoo(t *testing.T) {
    c, err := auth0mock.NewClient("http://localhost:8080")
    if err != nil {
        t.Fatal(err)
    }
    auth0mocktest.Bracket(t, c) // Reset on entry + exit, Verify at end

    reg := auth0mocktest.MustApply(t, c.ExpectGet("/api/v2/users/123").
        Respond(200).
        JSON(map[string]any{"user_id": "123"}))
    reg.Times(1)

    // ... exercise the system-under-test ...
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bracket

func Bracket(t testing.TB, c *auth0mock.Client)

Bracket is the one-liner setup for the canonical "register stubs + assert hits" flow:

func TestUserLookup(t *testing.T) {
    c, err := auth0mock.NewClient(mockURL)
    if err != nil { t.Fatal(err) }
    auth0mocktest.Bracket(t, c)

    reg := auth0mocktest.MustApply(t, c.ExpectGet("/api/v2/users/123").
        Respond(200).
        JSON(map[string]any{"user_id":"123"}))
    reg.Times(1)

    // ... exercise the system under test ...
}

Equivalent to writing:

auth0mocktest.ResetOnCleanup(t, c)            // pre-test reset + register Reset cleanup
t.Cleanup(func() { auth0mocktest.MustVerify(t, c) })  // register Verify cleanup

Cleanup ordering is the whole point of Bracket. Go's t.Cleanup is LIFO — the cleanup registered LAST fires FIRST. So we register Reset's cleanup first (via ResetOnCleanup) and Verify's cleanup last; at test end Verify fires first (reads ledger + server state), then Reset fires (wipes both). Without Bracket, a user who orders these the other way around silently passes every constraint check because Reset drops the local verification ledger before Verify can inspect it.

func MustAdd

MustAdd wraps Expectations.Add with t.Fatalf on error. The non-fluent counterpart to MustApply — use when you already have an Expectation struct built (e.g. shared across multiple tests). Returns the *auth0mock.RegisteredExpectation handle for per-stub operations.

func MustApply

MustApply wraps a ResponseBuilder.Apply call with t.Fatalf on error. Designed for the fluent chain:

reg := auth0mocktest.MustApply(t, c.ExpectGet("/api/v2/users/123").
    Respond(200).
    JSON(map[string]any{"id": "123"}))
reg.Times(1)
// Discard the handle with `_ = auth0mocktest.MustApply(...)`
// if you don't need to set hit-count constraints on it.

Returns the *auth0mock.RegisteredExpectation handle from Apply so per-stub operations (Clear, Hits, Times / AtLeast / AtMost / AnyTimes) chain naturally. The unwrapped *APIError (if any) is included in the failure message so the test output explains what the server rejected, not just "Apply failed".

func MustPush added in v0.228.0

func MustPush(t testing.TB, c *auth0mock.Client, payload string)

MustPush wraps Client.Events.Push with t.Fatalf on error. Pass an auth0mock.Event-shaped payload (the Auth0 event-stream envelope) as a JSON string for readability:

auth0mocktest.MustPush(t, c, `{
  "type":"user.created","offset":"0",
  "event":{"specversion":"1.0", ...}
}`)

func MustReset

func MustReset(t testing.TB, c *auth0mock.Client)

MustReset wraps Client.Reset with t.Fatalf on error. Use it when you want a one-line assertion at a specific point in the test — for the common "reset at start, reset at end" pattern, prefer ResetOnCleanup.

func MustVerify

func MustVerify(t testing.TB, c *auth0mock.Client)

MustVerify wraps Client.Expectations.Verify with t.Fatalf on constraint violations. Register this as the last t.Cleanup so every test that sets Times / AtLeast / AtMost on a stub has its expectations checked at test end:

t.Cleanup(func() { auth0mocktest.MustVerify(t, c) })

Or use Bracket(t, c) for the one-liner that does both Reset and Verify automatically.

MustVerify is a no-op when no stub on the Client has a constraint set.

func ResetOnCleanup

func ResetOnCleanup(t testing.TB, c *auth0mock.Client)

ResetOnCleanup resets the mock immediately and registers a t.Cleanup callback that resets it again on test end (including on failure). The recommended one-liner to bracket a test in known-empty state:

func TestMyFlow(t *testing.T) {
    c := auth0mock.NewClient(mockURL)
    auth0mocktest.ResetOnCleanup(t, c)

    // ... test setup + execution ...
}

The cleanup callback ignores reset errors — by the time t.Cleanup fires the test verdict is already decided, and a failing cleanup would only obscure the original failure. Use Client.Reset directly if you need to assert that teardown succeeded.

func WaitForActiveSubscribers added in v0.229.0

func WaitForActiveSubscribers(t testing.TB, c *auth0mock.Client, want int, timeout time.Duration)

WaitForActiveSubscribers polls GET /admin0/events/subscribers until the active count equals want, then returns. Calls t.Fatalf if it doesn't settle within timeout.

Use it to anchor on the SSE connection lifecycle rather than sleeping a fixed guess: WaitForActiveSubscribers(t, c, 1, …) after subscribing blocks until the subscription has registered server-side, and WaitForActiveSubscribers(t, c, 0, …) after closing a stream blocks until the hub has observed the disconnect (active is eventually-consistent, so a bare read can race the close).

Types

type SSEEvent added in v0.228.0

type SSEEvent struct {
	ID   string
	Type string
	Data json.RawMessage
}

SSEEvent is a parsed SSE frame: the `id:`, `event:`, and `data:` fields, glued together for one logical event. Comment frames (`:keep-alive`) are filtered out by SubscribeEvents — callers see only real events.

type SSEStream added in v0.228.0

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

SSEStream is an open SSE subscription. Read events with NextEvent (which blocks with a timeout). The connection is closed automatically on test cleanup; callers don't need to call Close directly unless they want to tear it down earlier (e.g. to test the disconnect behaviour).

func SubscribeEvents added in v0.228.0

func SubscribeEvents(t testing.TB, c *auth0mock.Client, bearer, query string) *SSEStream

SubscribeEvents opens an SSE connection to /api/v2/events on the mock with the given bearer and optional query string ("event_type= user.created", "from=evt_xxx", etc. — pass the value without the leading `?`). The stream filters out keep-alive comment frames and emits one SSEEvent per server frame.

The subscription is canceled on t.Cleanup. On t.Failed, the cleanup is still respected.

Calls t.Fatalf if the subscription fails to open (non-200 status, transport error, or missing text/event-stream content type).

func (*SSEStream) Close added in v0.228.0

func (s *SSEStream) Close()

Close ends the subscription early. Idempotent; safe to call from anywhere. The t.Cleanup registered by SubscribeEvents calls this automatically, so most tests don't need to.

func (*SSEStream) NextEvent added in v0.228.0

func (s *SSEStream) NextEvent(t testing.TB, timeout time.Duration) SSEEvent

NextEvent blocks until the next event arrives, the timeout fires, or the connection errors. Calls t.Fatalf with context on timeout or error. Returns the parsed event on success.

Jump to

Keyboard shortcuts

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