workflowtest

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package workflowtest holds the conformance suite every workflow driver runs, and two doubles for app tests: Fake, a recording client that runs nothing and refuses what a real driver refuses, with expressive assertions (AssertEnqueued and its siblings); and Recorder, which wraps a real client and records its enqueues. Recorder's standalone mode, NewRecorder(nil), is deprecated: use NewFake for a client that runs nothing.

A driver's own test file builds a Harness and calls Run, so the memory driver, which apps test against, and an engine driver such as Hatchet, which production runs, are held to the same assertions and cannot drift apart: a fake that honours IdempotencyKey, RunAt and retries while an engine driver silently drops them keeps every test green.

Every subtest checks Client.Capabilities first and calls t.Skip naming the missing capability, so one suite serves every driver honestly: a skipped assertion is reported as skipped, never silently passed.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Run

func Run(t *testing.T, h Harness)

Run executes the whole conformance suite against h. Each assertion is a subtest on a fresh Instance; subtests whose capabilities the driver lacks are skipped with the missing capability named.

The suite asserts: lifecycle errors; enqueue runs once and succeeds; DAG order and step inputs; Status reaches a terminal state through valid states; idempotency keys dedup while in flight and are released after; RunAt neither runs early nor late; retries follow step, workflow and RetriesNone rules and Permanent stops them; a RetryAfter delay under DelayFor and the Backoff.Jitter lower bound; step and workflow timeouts; OnFailure runs once; Cancel of a running and a scheduled run, idempotently; wait for event resumes on the matching key only (fixed Key and per-run KeyFrom) and times out; StepInfo on the handler's ctx; durable sleep; each concurrency strategy; rate limits; declared cron registered once and Schedule / Unschedule; each misfire policy (skip, fire once, fire all, Within and Max), a declared cron in its CronLocation, and the refusal of a zone or misfire policy the driver lacks; run-finished events (RunNotifier with CapRunFinished) for succeeded, failed and cancelled runs; capability refusals at Start and at Enqueue; and, for a durable driver with a Restart hook, runs that survive a restart and a step cut off by a restart that runs again on the new client; named queues and their refusals; Job.Retry, RetryPolicy.Until and MaxErrors; Discard; Runs filters and paging, Retry from the failed step, Delete and CancelAll; pausing a workflow and a queue; named-schedule upserts, time.Local refused, ScheduleWhen with tick events, windows, Schedules listing and schedule pause; graceful Drain; Retrying and Discarded run states; job chains and chain edits from a running step; worker scaling; QueueConfig.Limit across clients and a crash; retry precedence (job, step, workflow, default); DiscardOnExhaust per stopping rule and level; drain reports (finished and cut steps, grace edges, repeated drains); and closures, with the refusals of each on a driver that lacks it.

Types

type BatchMatcher

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

BatchMatcher narrows a batch assertion. Build it with BatchSize, BatchHasJob or BatchWhere; its description appears in failure messages.

func BatchHasJob

func BatchHasJob(wf string, m ...JobMatcher) BatchMatcher

BatchHasJob matches a batch with at least one job of workflow wf matching every m.

func BatchSize

func BatchSize(n int) BatchMatcher

BatchSize matches a batch of exactly n jobs.

func BatchWhere

func BatchWhere(desc string, fn func(FakeBatch) bool) BatchMatcher

BatchWhere matches batches for which fn is true; desc names the condition in failure messages.

func (BatchMatcher) String

func (m BatchMatcher) String() string

String is the matcher's description.

type Fake

type Fake struct {

	// Forward implements the optional client interfaces (run query,
	// pause, drain and the rest) by forwarding to the pass-through client
	// and refusing without one; the Fake claims none of their
	// capabilities. It does not provide ScheduleLister, whose Schedules
	// method the Fake's own Schedules (the recorded calls) shadows.
	workflow.Forward
	// contains filtered or unexported fields
}

Fake is a workflow.Client that records what an app asked for and runs nothing. An app test hands it to the code under test, then asserts on what was enqueued, scheduled, signalled and cancelled.

It refuses what a real driver refuses, so a test cannot pass on the Fake while production fails: Register validates (Validate, cron expressions) and refuses after Start; Start checks every workflow against the claimed capabilities (FakeCaps, FakeLike) and refuses expression keys unless FakeKeyExpr; Enqueue, Signal and Schedule before Start return ErrNotStarted; an unregistered workflow is ErrNotFound; a Job or Schedule needing a missing capability is an UnsupportedError; a workflow with IdempotencyRequired refuses a job without a key.

Recorded runs never finish: Status reports StatusScheduled for a RunAt job and StatusQueued otherwise until Cancel or Finish moves it. An idempotency key held by an unfinished run dedups as on a real driver: the second Enqueue returns the first run's RunRef and records nothing.

Recorder is the other test double in this package: it wraps a real client and records its enqueues. Its standalone mode, NewRecorder(nil), fakes a client that claims every capability and is deprecated in favour of Fake.

Batches dispatched by a batch.Manager over the Fake are recorded as their labelled jobs: Batches, AssertBatched, AssertBatchCount and AssertNothingBatched read them. AssertChained checks a registered workflow's step graph. FakeExcept and FakeOnly pass chosen workflows through to a real client.

A Fake is safe for concurrent use. Jobs are copied when recorded.

Example
package main

import (
	"context"
	"fmt"

	"github.com/ubgo/workflow"
	"github.com/ubgo/workflow/workflowtest"
)

// signUp is app code under test: it takes the Client interface, so a test
// hands it a Fake and production hands it a real driver.
func signUp(ctx context.Context, c workflow.Client, email string) error {
	_, err := c.Enqueue(ctx, workflow.Job{
		Workflow:       "welcome-email",
		Payload:        []byte(`{"email":"` + email + `"}`),
		IdempotencyKey: "welcome:" + email,
		Labels:         map[string]string{"source": "signup"},
	})
	return err
}

var welcome = workflow.Workflow{Name: "welcome-email", Steps: []workflow.Step{{
	Name: "send",
	Run:  func(context.Context, []byte) ([]byte, error) { return nil, nil },
}}}

func main() {
	ctx := context.Background()
	fake := workflowtest.NewFake()
	_ = fake.Register(welcome)
	_ = fake.Start(ctx)

	_ = signUp(ctx, fake, "a@example.com")
	_ = signUp(ctx, fake, "b@example.com")

	for _, j := range fake.Enqueued("welcome-email", workflowtest.HasLabel("source", "signup")) {
		fmt.Println(j.IdempotencyKey)
	}
}
Output:
welcome:a@example.com
welcome:b@example.com

func NewFake

func NewFake(opts ...FakeOption) *Fake

NewFake returns an unstarted Fake claiming the memory driver's capabilities unless FakeCaps or FakeLike says otherwise.

func (*Fake) AssertBatchCount

func (f *Fake) AssertBatchCount(t testing.TB, n int)

AssertBatchCount fails t unless exactly n batches were dispatched.

func (*Fake) AssertBatched

func (f *Fake) AssertBatched(t testing.TB, m ...BatchMatcher)

AssertBatched fails t unless a dispatched batch matches every m.

func (*Fake) AssertCancelled

func (f *Fake) AssertCancelled(t testing.TB, ref workflow.RunRef)

AssertCancelled fails t unless ref was cancelled.

func (*Fake) AssertChained

func (f *Fake) AssertChained(t testing.TB, wf string, steps ...string)

AssertChained fails t unless workflow wf is registered with exactly the steps named, in declaration order, each running after the one before it (the first after none), and at least one job of wf was enqueued. It is the chain assertion for a chain written as one workflow; a passed-through workflow's graph is checked, but its enqueues are not recorded, so it never passes.

func (*Fake) AssertClosureEnqueued

func (f *Fake) AssertClosureEnqueued(t testing.TB, name string)

AssertClosureEnqueued fails t unless a closure named name was enqueued.

func (*Fake) AssertDeleted

func (f *Fake) AssertDeleted(t testing.TB, ref workflow.RunRef)

AssertDeleted fails t unless ref was deleted.

func (*Fake) AssertEnqueued

func (f *Fake) AssertEnqueued(t testing.TB, wf string, m ...JobMatcher)

AssertEnqueued fails t unless at least one job of workflow wf matching every m was enqueued.

func (*Fake) AssertEnqueuedOn

func (f *Fake) AssertEnqueuedOn(t testing.TB, queue, wf string, m ...JobMatcher)

AssertEnqueuedOn fails t unless a job of workflow wf matching every m was enqueued to run on queue: its effective queue (workflow.EffectiveQueue: Job.Queue, else the registered workflow's Queue, else workflow.DefaultQueue).

func (*Fake) AssertEnqueuedTimes

func (f *Fake) AssertEnqueuedTimes(t testing.TB, wf string, n int, m ...JobMatcher)

AssertEnqueuedTimes fails t unless exactly n jobs of workflow wf matching every m were enqueued.

func (*Fake) AssertForced

func (f *Fake) AssertForced(t testing.TB, ref workflow.RunRef, complete bool)

AssertForced fails t unless ref was force-completed (complete true) or force-failed (complete false).

func (*Fake) AssertNotEnqueued

func (f *Fake) AssertNotEnqueued(t testing.TB, wf string, m ...JobMatcher)

AssertNotEnqueued fails t if any job of workflow wf matching every m was enqueued.

func (*Fake) AssertNotPaused

func (f *Fake) AssertNotPaused(t testing.TB, target workflow.PauseTarget)

AssertNotPaused fails t if target is paused now.

func (*Fake) AssertNothingBatched

func (f *Fake) AssertNothingBatched(t testing.TB)

AssertNothingBatched fails t if any batch was dispatched.

func (*Fake) AssertNothingEnqueued

func (f *Fake) AssertNothingEnqueued(t testing.TB)

AssertNothingEnqueued fails t if any job was enqueued.

func (*Fake) AssertPaused

func (f *Fake) AssertPaused(t testing.TB, target workflow.PauseTarget)

AssertPaused fails t unless target is paused now.

func (*Fake) AssertRetried

func (f *Fake) AssertRetried(t testing.TB, ref workflow.RunRef)

AssertRetried fails t unless ref was retried.

func (*Fake) AssertScheduled

func (f *Fake) AssertScheduled(t testing.TB, wf string)

AssertScheduled fails t unless a schedule of workflow wf is in place (recorded and not unscheduled).

func (*Fake) AssertSignalled

func (f *Fake) AssertSignalled(t testing.TB, name, key string)

AssertSignalled fails t unless an event named name with key key was signalled.

func (*Fake) AssertTriggered

func (f *Fake) AssertTriggered(t testing.TB, id workflow.ScheduleID)

AssertTriggered fails t unless schedule id was triggered.

func (*Fake) Batches

func (f *Fake) Batches() []FakeBatch

Batches returns the batches dispatched through the Fake (see FakeBatch), in the order their first job was recorded.

func (*Fake) Cancel

func (f *Fake) Cancel(ctx context.Context, ref workflow.RunRef) error

Cancel records the call and marks a recorded run cancelled. It needs CapCancel; cancelling a finished run is a no-op; a ref the Fake did not issue goes to the pass-through client, or is ErrNotFound without one.

func (*Fake) Cancels

func (f *Fake) Cancels() []workflow.RunRef

Cancels returns every ref passed to a successful Cancel, in order.

func (*Fake) Capabilities

func (f *Fake) Capabilities() workflow.Caps

Capabilities is the set the Fake was built with.

func (*Fake) Closures

func (f *Fake) Closures(names ...string) []workflow.ClosureJob

Closures returns the recorded closures, in enqueue order, optionally only those with one of names.

func (*Fake) Delete

func (f *Fake) Delete(ctx context.Context, ref workflow.RunRef) error

Delete forgets a recorded terminal run, as workflow.RunDeleter does: Status then returns ErrNotFound. The job stays in Jobs and Enqueued, since it was enqueued. It needs CapDeleteRun. A run that is not terminal is workflow.ErrWrongState, and a ref the Fake did not issue goes to the pass-through client, or is ErrNotFound without one.

func (*Fake) Deletes

func (f *Fake) Deletes() []workflow.RunRef

Deletes returns every ref passed to a successful Delete, in order.

func (*Fake) Enqueue

func (f *Fake) Enqueue(ctx context.Context, job workflow.Job) (workflow.RunRef, error)

Enqueue records job and returns a synthetic RunRef: a ScheduledID for a RunAt job, a RunID otherwise. It refuses what a real driver refuses (see Fake).

func (*Fake) EnqueueClosure

func (f *Fake) EnqueueClosure(ctx context.Context, c workflow.ClosureJob) (workflow.RunRef, error)

EnqueueClosure records c without running it, as a run of workflow.ClosureWorkflow labelled workflow.LabelClosure, so Status, Cancel, Finish and Jobs see it like any recorded run. It refuses what a real driver refuses: before Start ErrNotStarted, without CapClosure (FakeCaps of a durable driver) an UnsupportedError, an invalid closure ErrInvalid. Closures are never passed through. RunClosures runs the recorded ones when a test wants their effect.

func (*Fake) Enqueued

func (f *Fake) Enqueued(wf string, m ...JobMatcher) []workflow.Job

Enqueued returns the recorded jobs of workflow wf matching every m.

func (*Fake) Finish

func (f *Fake) Finish(ref workflow.RunRef, st workflow.Status) error

Finish moves a recorded run to a terminal status, releasing its idempotency key, so a test can model a run that completed. It returns ErrNotFound for an unknown ref and ErrInvalid for a status that is not terminal; finishing a finished run is a no-op.

func (*Fake) ForceComplete

func (f *Fake) ForceComplete(ctx context.Context, ref workflow.RunRef) error

ForceComplete records the call and marks a recorded run succeeded, as workflow.RunForcer does: it accepts an unfinished or failed run (ErrWrongState otherwise) and needs CapForceRun. The Fake runs no chain, so a chained job is not enqueued. A ref the Fake did not issue goes to the pass-through client, or is ErrNotFound without one.

func (*Fake) ForceFail

func (f *Fake) ForceFail(ctx context.Context, ref workflow.RunRef, reason string) error

ForceFail records the call and marks an unfinished recorded run failed, as workflow.RunForcer does (ErrWrongState for a finished run). It needs CapForceRun.

func (*Fake) Forced

func (f *Fake) Forced() []FakeForce

Forced returns the recorded ForceComplete and ForceFail calls, in order.

func (*Fake) Jobs

func (f *Fake) Jobs() []workflow.Job

Jobs returns a copy of every recorded job, in enqueue order. A deduped enqueue is not a job: it created no run.

func (*Fake) Pause

func (f *Fake) Pause(ctx context.Context, t workflow.PauseTarget) error

Pause records t as paused. It checks t as a driver does (workflow.CheckPause: CapPauseWorkflow for a workflow or All, CapPauseQueue for a queue). The Fake runs nothing, so a pause changes no status; it is there to be asserted (AssertPaused) and listed (Paused). A pause of a passed-through workflow (FakeExcept, FakeOnly) goes to the real client instead and is not recorded.

func (*Fake) Paused

func (f *Fake) Paused(ctx context.Context) ([]workflow.PauseTarget, error)

Paused lists the recorded pauses in force in workflow.Pauser's order: All first, then workflows, then queues, each by name.

func (*Fake) Register

func (f *Fake) Register(wf workflow.Workflow) error

Register validates wf, including its cron expressions, and stores it. A passed-through workflow (FakeExcept, FakeOnly) is registered with the real client instead.

func (*Fake) Resume

func (f *Fake) Resume(ctx context.Context, t workflow.PauseTarget) error

Resume removes the pause t, or every pause for workflow.PauseAll(), as workflow.Pauser does; resuming a target that is not paused is a no-op. A passed-through workflow's target goes to the real client.

func (*Fake) Retries

func (f *Fake) Retries() []workflow.RunRef

Retries returns every ref passed to a successful Retry, in order.

func (*Fake) Retry

func (f *Fake) Retry(ctx context.Context, ref workflow.RunRef) (workflow.RunRef, error)

Retry records a retry of a recorded failed run and moves it back to StatusQueued, as workflow.RunRetrier does: the run keeps its RunRef and takes its idempotency key again. It needs CapRetryRun. A run that is not StatusFailed is workflow.ErrWrongState, a key another unfinished run holds is workflow.ErrDuplicate, and a ref the Fake did not issue goes to the pass-through client, or is ErrNotFound without one. Use Finish to fail a run first.

func (*Fake) RunClosures

func (f *Fake) RunClosures(ctx context.Context) error

RunClosures calls every recorded closure's Fn once, in enqueue order, with ctx, and returns their errors joined (each naming its closure). It runs no retries and does not change the recorded runs' statuses; it is for a test that asserts on what the closures do.

func (*Fake) Schedule

func (f *Fake) Schedule(ctx context.Context, s workflow.Schedule) (workflow.ScheduleID, error)

Schedule validates s (including its cron expression), needs CapCron plus what RequiresSchedule names (a zone, a misfire policy) and a registered workflow, and records it under a synthetic ID.

func (*Fake) Schedules

func (f *Fake) Schedules() []FakeSchedule

Schedules returns every recorded Schedule call, in order.

func (*Fake) Signal

func (f *Fake) Signal(ctx context.Context, ev workflow.Event) error

Signal records ev. Nothing waits on the Fake, so nothing resumes; with a pass-through client, ev is also delivered to it, where passed-through runs may wait.

func (*Fake) Signals

func (f *Fake) Signals() []workflow.Event

Signals returns every recorded Signal, in order.

func (*Fake) Start

func (f *Fake) Start(ctx context.Context) error

Start checks every workflow against the capabilities and, unless FakeKeyExpr, refuses expression keys. It starts nothing of its own; a pass-through client (FakeExcept, FakeOnly) is started with ctx.

func (*Fake) Status

func (f *Fake) Status(ctx context.Context, ref workflow.RunRef) (workflow.Status, error)

Status reports a recorded run's status; a ref the Fake did not issue goes to the pass-through client, or is ErrNotFound without one.

func (*Fake) TriggerSchedule

func (f *Fake) TriggerSchedule(ctx context.Context, id workflow.ScheduleID) (workflow.RunRef, error)

TriggerSchedule records a trigger of a recorded schedule and enqueues its job as a driver would: the schedule's Input and workflow.TriggeredLabels, through Enqueue, so AssertEnqueued sees it. It needs CapScheduleTrigger and obeys OverlapSkip against the run the previous trigger made (use Finish to end it). An unscheduled or unknown id goes to the pass-through client, or is ErrNotFound without one.

func (*Fake) Triggers

func (f *Fake) Triggers() []workflow.ScheduleID

Triggers returns the schedules TriggerSchedule triggered, in order.

func (*Fake) Unschedule

func (f *Fake) Unschedule(ctx context.Context, id workflow.ScheduleID) error

Unschedule marks a recorded schedule removed. An empty id or a second call is a no-op; an id the Fake never issued goes to the pass-through client, or is ErrNotFound without one.

func (*Fake) Workflow

func (f *Fake) Workflow(name string) (workflow.Workflow, bool)

Workflow returns the registered definition of name, faked or passed through, and whether there is one.

type FakeBatch

type FakeBatch struct {
	ID   batch.ID
	Jobs []workflow.Job
}

FakeBatch is one batch as a test double saw it: the recorded jobs that carry the same batch.LabelBatch, in index order (batch.LabelIndex), so jobs a batch.Manager added later with Add are included. The batch's name and callbacks live in the Manager's Store, not on the jobs; read them with Manager.Progress(ctx, ID) when a test needs them.

type FakeForce

type FakeForce struct {
	Ref      workflow.RunRef
	Complete bool
	Reason   string
}

FakeForce is one recorded ForceComplete (Complete true) or ForceFail.

type FakeOption

type FakeOption func(*Fake)

FakeOption configures a Fake.

func FakeCaps

func FakeCaps(c workflow.Caps) FakeOption

FakeCaps sets the capabilities the Fake claims and enforces. Pass the production driver's set (or use FakeLike) so a test cannot pass on the Fake with a field the real driver would refuse. CapRunFinished is dropped: the Fake reports no run ends; so are the run query (and its label prefix filter), bulk cancel, schedule pause, schedule listing, tick and drain capabilities, which the Fake does not serve itself.

func FakeCronParser

func FakeCronParser(p cron.Parser) FakeOption

FakeCronParser makes the Fake check cron expressions with p instead of cron.Parse, matching a production driver built with a custom parser (memory.WithCronParser). Nil is ignored.

func FakeExcept

func FakeExcept(inner workflow.Client, workflows ...string) FakeOption

FakeExcept passes the jobs, schedules and registrations of the named workflows through to inner, a real client, and fakes every other workflow. FakeOnly is the inverse. Passed-through work is not recorded: inner runs it, and the Fake's assertions cover only what it faked. Start starts inner too, Status and Cancel of a ref the Fake did not issue go to inner, and Signal is recorded and also delivered to inner. A nil inner is ignored.

func FakeKeyExpr

func FakeKeyExpr() FakeOption

FakeKeyExpr makes the Fake accept expression keys (workflow.KeyExpr), as an engine such as Hatchet does. By default it refuses them at Start, as the in-process memory driver does.

func FakeLike

func FakeLike(c workflow.Client) FakeOption

FakeLike copies the capabilities of c, typically the production client built (but not started) with test configuration. It reads only c.Capabilities.

func FakeOnly

func FakeOnly(inner workflow.Client, workflows ...string) FakeOption

FakeOnly fakes only the named workflows and passes every other one through to inner; see FakeExcept.

type FakeSchedule

type FakeSchedule struct {
	ID          workflow.ScheduleID
	Schedule    workflow.Schedule
	Unscheduled bool

	// LastRun is the run the last TriggerSchedule of it enqueued; the
	// Fake fires no cron ticks, so only triggers set it.
	LastRun workflow.RunRef
}

FakeSchedule is one recorded Schedule call and whether it was removed.

type Harness

type Harness struct {
	// New returns a fresh, unstarted client for one subtest. The suite
	// registers workflows, calls Start with a context it cancels when the
	// subtest ends, and never shares a client between subtests.
	New func(t *testing.T) Instance

	// Unit is the base length of every delay, sleep, timeout and window
	// the suite asks for. Zero means one minute on a fake clock (where it
	// costs nothing) and two seconds on real time.
	Unit time.Duration

	// Wait is the wall-clock time the suite allows an expected outcome to
	// appear before failing. Zero means 5s on a fake clock and 60s on real
	// time.
	Wait time.Duration

	// Quiet is the wall-clock time the suite watches for something that
	// must not happen (a second run, a start before RunAt). Zero means
	// 50ms on a fake clock and one second on real time.
	Quiet time.Duration

	// Poll is the wall-clock interval between Status polls. Zero means 2ms
	// on a fake clock and 200ms on real time.
	Poll time.Duration

	// KeyFromLabel returns the ConcurrencyKey that buckets runs by the
	// value of Job.Labels[label]. Concurrency and rate-limit subtests use
	// it. Nil means workflow.KeyFunc reading the label, which an
	// in-process driver evaluates; an engine that only takes expressions
	// supplies a workflow.KeyExpr here.
	KeyFromLabel func(label string) workflow.ConcurrencyKey

	// WaitKeyFromLabel returns the WaitSpec.KeyFrom that keys a run's wait
	// by the value of Job.Labels[label]. It is separate from KeyFromLabel
	// because an engine may need expressions for concurrency yet evaluate
	// wait keys in Go (Hatchet has no API that turns CEL into a string).
	// Nil means workflow.KeyFunc reading the label, whatever KeyFromLabel
	// is.
	WaitKeyFromLabel func(label string) workflow.ConcurrencyKey

	// RateLimitPer is the RateLimit.Per of the rate-limit cases. Zero
	// means 2*Unit. An engine that only takes fixed windows (Hatchet:
	// second, minute, hour...) sets one it accepts, such as time.Minute;
	// the cases scale their waits from it, so a long window only makes
	// them slower on real time.
	RateLimitPer time.Duration

	// RealCron runs the cron-firing subtests on a real-time instance,
	// where each waits up to two minutes for a minute boundary. Without
	// it they are skipped on real time; on a fake clock they always run.
	RealCron bool

	// NewWithQueues is New for a client that serves exactly qs
	// (QueueConfig: Workers, Limit, Priority...), for the queue-limit
	// cases. The Instance it returns carries Restart, Crash and Peer that
	// build their clients with the same qs, so a replacement or a second
	// node enforces the same Limit. Nil skips those cases: the queue
	// configuration is a driver option the suite cannot name.
	NewWithQueues func(t *testing.T, qs []workflow.QueueConfig) Instance

	// Prefix starts every workflow and event name the suite makes, so a
	// shared engine shows which suite left a run behind. Empty means
	// "wftest". Names also carry a per-Run nonce, because real engines
	// keep state across runs of the suite.
	Prefix string
}

Harness adapts one driver to the suite. Only New is required; every other field has a default suited to the kind of clock the instance uses.

type Instance

type Instance struct {
	// Client is fresh and unstarted.
	Client workflow.Client

	// Clock is the fake clock the client reads, or nil when the client
	// runs on real time (an engine). With a fake clock the suite moves
	// time itself; without one it uses short real durations and polls
	// Status until Harness.Wait.
	Clock *clock.Fake

	// Restart, when set and the client claims CapDurable, stands for a
	// process restart: the suite has already cancelled the old client's
	// Start context, and Restart returns a new, unstarted client over the
	// same storage and the same Clock. The suite registers the same
	// workflows on it and starts it. Nil skips the durability subtests.
	//
	// Restart is also the kill-a-worker seam: the suite may cancel the old
	// Start context while a step is running, and a durable driver must
	// then resume the run on the new client (re-running the step, at once
	// or after a lease expires on Clock) rather than mark it cancelled.
	// Several workers over one store are modelled the same way: the old
	// client is the lost worker, the new one the survivor.
	Restart func(t *testing.T) workflow.Client

	// Crash, when set and the client claims CapDurable, stands for the
	// process dying mid-step: the suite does NOT cancel the old client's
	// Start context first, and Crash must abandon the old client the way a
	// killed process would (no lease release, no status writes, no further
	// claims), then return a new, unstarted client over the same storage
	// and Clock. The suite registers and starts it and expects the step
	// that was running to run again within Wait, once the old worker's
	// lease expires on whatever clock the driver measures leases with.
	// The abandoned step's handler stays blocked until the subtest ends.
	// Nil skips the crash subtest.
	Crash func(t *testing.T) workflow.Client

	// EnqueueOnly, when set and the client claims CapEnqueueOnly, returns
	// a client built in the driver's enqueue-only mode over the same
	// storage and Clock as Client. The suite never calls Start on it:
	// it enqueues through it and expects Client (registered and started)
	// to run the work. Nil skips the enqueue-only subtests.
	EnqueueOnly func(t *testing.T) workflow.Client

	// Peer, when set, returns a second, unstarted, fully working client
	// over the same storage and Clock as Client (another node of the same
	// deployment; Client stays alive). Only an Instance from
	// Harness.NewWithQueues uses it, and the peer is built with the same
	// queues. Nil skips the two-client cases: a driver whose state is one
	// process has no second node.
	Peer func(t *testing.T) workflow.Client
}

Instance is one client under test plus what the suite needs to drive it.

type JobMatcher

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

JobMatcher narrows an assertion to jobs with a property. Build it with HasPayload, HasPayloadJSON, HasLabel, HasKey, HasRunAt, HasPriority or Where; its description appears in failure messages.

func HasChain

func HasChain(workflows ...string) JobMatcher

HasChain matches jobs whose Job.Chain runs exactly the named workflows, in order, nested chains flattened as the driver would run them (workflow.NextInChain). HasChain() matches a job with no chain.

func HasKey

func HasKey(key string) JobMatcher

HasKey matches a job's IdempotencyKey.

func HasLabel

func HasLabel(k, v string) JobMatcher

HasLabel matches a job whose Labels[k] is v.

func HasPayload

func HasPayload(p []byte) JobMatcher

HasPayload matches a payload byte for byte.

func HasPayloadJSON

func HasPayloadJSON(v any) JobMatcher

HasPayloadJSON matches a JSON payload equal to v once both are decoded, so key order and spacing do not matter. A v that does not marshal matches nothing.

func HasPriority

func HasPriority(p int) JobMatcher

HasPriority matches a job's Priority.

func HasQueue

func HasQueue(q string) JobMatcher

HasQueue matches a job whose Job.Queue is q as given. An empty Job.Queue (the workflow's queue) matches only HasQueue(""); use AssertEnqueuedOn to match the queue a run actually lands on.

func HasRetry

func HasRetry(p workflow.RetryPolicy) JobMatcher

HasRetry matches a job whose Job.Retry override equals p (Max, Backoff, Until, MaxErrors, DiscardOnExhaust; a job's override carries no functions).

func HasRunAt

func HasRunAt(t time.Time) JobMatcher

HasRunAt matches a job delayed to exactly t.

func Where

func Where(desc string, fn func(workflow.Job) bool) JobMatcher

Where matches jobs for which fn is true; desc names the condition in failure messages.

func (JobMatcher) String

func (m JobMatcher) String() string

String is the matcher's description.

type Recorder

type Recorder struct {

	// Forward implements the optional client interfaces (run query,
	// pause, schedule listing, drain and the rest) by forwarding to inner
	// and refusing in the fake mode, so wrapping a client never hides one.
	workflow.Forward
	// contains filtered or unexported fields
}

Recorder is a workflow.Client that records every successful Enqueue so an app test can assert what its code enqueued.

It has two modes. NewRecorder(inner) wraps a real client: every call goes to inner and successful enqueues are recorded on the way back. NewRecorder(nil) is a fake, deprecated in favour of NewFake: Register validates and stores the definition, Start succeeds once, Enqueue records the job and returns a synthetic RunRef, Status reports StatusQueued for a recorded run, and nothing ever runs. The fake claims every capability, because a test double that refused fields would test the double, not the app.

A Recorder is safe for concurrent use. Jobs are copied on record, so a caller reusing its Job or Labels map cannot change what was recorded.

func NewRecorder

func NewRecorder(inner workflow.Client) *Recorder

NewRecorder returns a Recorder wrapping inner, or a pure fake when inner is nil.

NewRecorder(nil) is discouraged and kept only for compatibility; use NewFake for a client that runs nothing, since it refuses what a real driver refuses instead of claiming every capability. Wrapping a real client with NewRecorder(inner) is fully supported.

func (*Recorder) AssertBatchCount

func (r *Recorder) AssertBatchCount(t testing.TB, n int)

AssertBatchCount fails t unless exactly n batches were enqueued.

func (*Recorder) AssertBatched

func (r *Recorder) AssertBatched(t testing.TB, m ...BatchMatcher)

AssertBatched fails t unless a batch matching every m was enqueued.

func (*Recorder) AssertChained

func (r *Recorder) AssertChained(t testing.TB, wf string, steps ...string)

AssertChained fails t unless workflow wf is registered as exactly the chain steps and was enqueued at least once, as Fake.AssertChained does.

func (*Recorder) AssertDeleted

func (r *Recorder) AssertDeleted(t testing.TB, ref workflow.RunRef)

AssertDeleted fails t unless ref was deleted through the Recorder.

func (*Recorder) AssertEnqueued

func (r *Recorder) AssertEnqueued(t testing.TB, wf string, n int)

AssertEnqueued fails t unless workflow wf was enqueued exactly n times.

func (*Recorder) AssertEnqueuedOn

func (r *Recorder) AssertEnqueuedOn(t testing.TB, queue, wf string, m ...JobMatcher)

AssertEnqueuedOn fails t unless a job of workflow wf matching every m was enqueued to run on queue (workflow.EffectiveQueue), as Fake.AssertEnqueuedOn does.

func (*Recorder) AssertEnqueuedWith

func (r *Recorder) AssertEnqueuedWith(t testing.TB, wf string, match func(workflow.Job) bool)

AssertEnqueuedWith fails t unless at least one recorded job of workflow wf satisfies match.

func (*Recorder) AssertNotEnqueued

func (r *Recorder) AssertNotEnqueued(t testing.TB, wf string)

AssertNotEnqueued fails t if workflow wf was enqueued at all.

func (*Recorder) AssertNotPaused

func (r *Recorder) AssertNotPaused(t testing.TB, target workflow.PauseTarget)

AssertNotPaused fails t if the inner client reports target paused.

func (*Recorder) AssertNothingBatched

func (r *Recorder) AssertNothingBatched(t testing.TB)

AssertNothingBatched fails t if any batch was enqueued.

func (*Recorder) AssertNothingEnqueued

func (r *Recorder) AssertNothingEnqueued(t testing.TB)

AssertNothingEnqueued fails t if any job was enqueued.

func (*Recorder) AssertPaused

func (r *Recorder) AssertPaused(t testing.TB, target workflow.PauseTarget)

AssertPaused fails t unless the inner client reports target paused (its workflow.Pauser.Paused), so the assertion reads the real state.

func (*Recorder) AssertRetried

func (r *Recorder) AssertRetried(t testing.TB, ref workflow.RunRef)

AssertRetried fails t unless ref was retried through the Recorder.

func (*Recorder) Batches

func (r *Recorder) Batches() []FakeBatch

Batches returns the batches whose jobs were enqueued through the Recorder (see FakeBatch), as Fake.Batches does.

func (*Recorder) Cancel

func (r *Recorder) Cancel(ctx context.Context, ref workflow.RunRef) error

Cancel cancels through the inner client; the fake accepts any recorded run and returns ErrNotFound for others.

func (*Recorder) Capabilities

func (r *Recorder) Capabilities() workflow.Caps

Capabilities is the inner client's; the fake claims every capability.

func (*Recorder) Delete

func (r *Recorder) Delete(ctx context.Context, ref workflow.RunRef) error

Delete deletes through the inner client's workflow.RunDeleter and records ref when that succeeds; the fake, or an inner client without it, refuses with an UnsupportedError.

func (*Recorder) Deletes

func (r *Recorder) Deletes() []workflow.RunRef

Deletes returns every ref passed to a successful Delete, in order.

func (*Recorder) Enqueue

func (r *Recorder) Enqueue(ctx context.Context, job workflow.Job) (workflow.RunRef, error)

Enqueue enqueues through the inner client and records job when that succeeds. The fake records every job and never runs it. A refused job is not recorded: it was not enqueued.

func (*Recorder) Jobs

func (r *Recorder) Jobs() []workflow.Job

Jobs returns a copy of every recorded job, in enqueue order.

func (*Recorder) OnRunFinished

func (r *Recorder) OnRunFinished(fn workflow.RunFinishedFunc) error

OnRunFinished forwards fn to the inner client when it implements workflow.RunNotifier, so wrapping a client never hides its run-finished events. Recorder always has this method, so a type assertion on it always succeeds; the fake, or a Recorder over a client without RunNotifier, answers with an UnsupportedError instead of silently registering an observer that would never be called.

func (*Recorder) Register

func (r *Recorder) Register(wf workflow.Workflow) error

Register registers wf with the inner client; the fake validates it and refuses a Register after Start, as a real client does. Either way a registered definition is kept for Workflow and AssertChained.

func (*Recorder) Retries

func (r *Recorder) Retries() []workflow.RunRef

Retries returns every ref passed to a successful Retry, in order.

func (*Recorder) Retry

func (r *Recorder) Retry(ctx context.Context, ref workflow.RunRef) (workflow.RunRef, error)

Retry retries through the inner client's workflow.RunRetrier and records ref when that succeeds; the fake, or an inner client without it, refuses with an UnsupportedError.

func (*Recorder) Schedule

Schedule schedules through the inner client; the fake validates s and returns a synthetic ScheduleID.

func (*Recorder) Signal

func (r *Recorder) Signal(ctx context.Context, ev workflow.Event) error

Signal signals through the inner client; the fake drops it, as a real client drops a signal nobody waits for.

func (*Recorder) Start

func (r *Recorder) Start(ctx context.Context) error

Start starts the inner client; the fake succeeds once and returns ErrAlreadyStarted after that.

func (*Recorder) Status

func (r *Recorder) Status(ctx context.Context, ref workflow.RunRef) (workflow.Status, error)

Status asks the inner client; the fake reports StatusQueued for a recorded run, since nothing ever runs it, and ErrNotFound otherwise.

func (*Recorder) Unschedule

func (r *Recorder) Unschedule(ctx context.Context, id workflow.ScheduleID) error

Unschedule unschedules through the inner client; the fake accepts any id.

func (*Recorder) Workflow

func (r *Recorder) Workflow(name string) (workflow.Workflow, bool)

Workflow returns the registered definition of name and whether there is one.

type StepOption

type StepOption func(*stepRun)

StepOption configures RunStep.

func StepCaps

func StepCaps(c workflow.Caps) StepOption

StepCaps sets the capabilities the step's chain edits are checked against, as the production driver's would be. The default is the Fake's default set, which includes CapChain. Without CapChain the step's PrependToChain and AppendToChain are refused, as on a driver that cannot edit chains.

func StepChain

func StepChain(jobs ...workflow.Job) StepOption

StepChain sets the chain the run already holds (its Job.Chain), which the step's PrependToChain and AppendToChain edit; see StepOutcome.Chain.

func StepContext

func StepContext(ctx context.Context) StepOption

StepContext sets the parent ctx of the call; the default is context.Background.

func StepInfoOf

func StepInfoOf(info workflow.StepInfo) StepOption

StepInfoOf sets the workflow.StepInfo the handler sees, for a handler that reads its attempt, run or labels. The default is workflow "test", step "step", run "runstep", attempt 1.

func StepMiddleware

func StepMiddleware(mw ...workflow.Middleware) StepOption

StepMiddleware wraps the handler in mw, outermost first, as a driver built with the same middleware would.

type StepOutcome

type StepOutcome struct {
	Output []byte
	Err    error

	// Chain is the run's chain after this attempt: StepChain's jobs with
	// the attempt's PrependToChain and AppendToChain edits applied when
	// it succeeded, unchanged when it failed (a driver drops a failed
	// attempt's edits).
	Chain []workflow.Job
}

StepOutcome is what one call of a step handler returned, for asserting how the attempt ended (released, failed, permanent, discarded) without a client or a driver.

func RunStep

func RunStep(h workflow.Handler, in []byte, opts ...StepOption) StepOutcome

RunStep calls h once with in, on a ctx carrying StepInfo, and returns the outcome. It runs no retries, so it shows what one attempt asks for: a release (workflow.RetryAfter), a permanent failure, a discard (workflow.Discard), an ordinary failure the retry policy would retry, or success. A panic in h is not recovered, so it fails the test with its stack.

func (StepOutcome) AssertDiscarded

func (o StepOutcome) AssertDiscarded(t testing.TB)

AssertDiscarded fails t unless the attempt asked to drop the run.

func (StepOutcome) AssertFailed

func (o StepOutcome) AssertFailed(t testing.TB)

AssertFailed fails t unless the attempt returned an error that is neither permanent, discarded nor a release: one the retry policy retries.

func (StepOutcome) AssertPermanent

func (o StepOutcome) AssertPermanent(t testing.TB)

AssertPermanent fails t unless the attempt failed permanently.

func (StepOutcome) AssertReleased

func (o StepOutcome) AssertReleased(t testing.TB, d time.Duration)

AssertReleased fails t unless the attempt asked to be retried after exactly d.

func (StepOutcome) AssertSucceeded

func (o StepOutcome) AssertSucceeded(t testing.TB)

AssertSucceeded fails t unless the attempt succeeded.

func (StepOutcome) ChainNames

func (o StepOutcome) ChainNames() []string

ChainNames is the order the jobs of o.Chain would run in, nested chains flattened as a driver runs them.

func (StepOutcome) Discarded

func (o StepOutcome) Discarded() bool

Discarded reports whether the step asked to drop the run (workflow.Discard): no retry, and the run ends discarded (CapRunStates) or cancelled (CapDiscard) rather than failed; see workflow.EndStatus.

func (StepOutcome) Failed

func (o StepOutcome) Failed() bool

Failed reports whether the attempt returned an error of any kind: a release, a permanent failure or an ordinary one.

func (StepOutcome) Permanent

func (o StepOutcome) Permanent() bool

Permanent reports whether the error forbids any retry (workflow.Permanent).

func (StepOutcome) Released

func (o StepOutcome) Released() (time.Duration, bool)

Released reports whether the error asks for a retry after a delay (workflow.RetryAfter, a release) and that delay. A policy whose DelayFor is workflow.RetryAfterDelay honours it; other policies retry on their Backoff. Permanent and Discard win over a release, as on every driver.

func (StepOutcome) Succeeded

func (o StepOutcome) Succeeded() bool

Succeeded reports whether the attempt returned no error.

Jump to

Keyboard shortcuts

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