Documentation
¶
Overview ¶
Package taskmilltest helps test code that uses taskmill.
The helpers work against a real PostgreSQL database, so tests see the same transactions, FIFO groups, deduplication, and retries as production. Each test gets its own schema from NewClient, so tests can run in parallel. Every helper fails the test on errors in its own setup.
A typical test checks two things: that the code under test enqueues the right tasks, with Enqueued, and that a handler does the right work, with Run. An integration test can also process everything enqueued, with Work. The testing guide shows each of them in a test.
Example ¶
This example tests code that enqueues a task, and the task's handler; see testSignUp above, which TestExampleRuns calls.
package main
import (
"context"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/code19m/taskmill"
"github.com/code19m/taskmill/taskmilltest"
)
// SendWelcome is the task that signing up enqueues.
type SendWelcome struct {
UserID int64 `json:"user_id"`
}
func (SendWelcome) Kind() string { return "user.welcome" }
// signUp is the code under test.
func signUp(ctx context.Context, client *taskmill.Client, userID int64) error {
_, err := client.Enqueue(ctx, SendWelcome{UserID: userID}, nil)
return err
}
// testSignUp is the body of a test, TestSignUp(t), that checks that signing
// up enqueues a welcome email, and that the email's handler succeeds. pool
// connects to the test database.
func testSignUp(t *testing.T, pool *pgxpool.Pool, sendEmail func(userID int64) error) {
t.Helper()
client := taskmilltest.NewClient(t, pool, nil)
if err := signUp(t.Context(), client, 42); err != nil {
t.Fatal(err)
}
tasks := taskmilltest.Enqueued[SendWelcome](t, client)
if len(tasks) != 1 || tasks[0].Args.UserID != 42 {
t.Fatalf("enqueued %+v", tasks)
}
handler := taskmill.HandlerFunc[SendWelcome](func(_ context.Context, task *taskmill.Task[SendWelcome]) error {
return sendEmail(task.Args.UserID)
})
info, err := taskmilltest.Run(t, client, handler, SendWelcome{UserID: 42}, nil)
if err != nil || info.State != taskmill.StateCompleted {
t.Fatalf("got %s, %v", info.State, err)
}
}
func main() {
_ = testSignUp
}
Output:
Index ¶
- func Enqueued[A taskmill.Args](tb testing.TB, client *taskmill.Client) []*taskmill.Task[A]
- func NewClient(tb testing.TB, pool *pgxpool.Pool, cfg *taskmill.ClientConfig) *taskmill.Client
- func Run[A taskmill.Args](tb testing.TB, client *taskmill.Client, h taskmill.Handler[A], args A, ...) (*taskmill.TaskInfo, error)
- func Work(tb testing.TB, client *taskmill.Client, cfg *taskmill.WorkerConfig)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Enqueued ¶
Enqueued returns every committed task of A's kind, oldest first, with its arguments decoded: unfinished tasks, finished ones, and those in history. Use it to check that the code under test enqueued a task when its transaction committed, and no task when it rolled back.
The returned tasks cannot complete themselves with taskmill.Task.CompleteTx; use Run to run a handler.
func NewClient ¶
NewClient migrates a new schema with a random name in the database that pool connects to, and returns a client for it. cfg may be nil; its Schema must be empty.
When the test ends, the client is closed, and the schema is dropped on a connection of pool. A worker that the test stopped may have left a statement that the database still runs, and a drop that met it could fail the test with a deadlock. So the drop first waits until pool has closed the connections of such statements, for up to a second. Where that cannot tell, through a proxy such as PgBouncer or on a pool that other tests use, a drop that PostgreSQL ended as a deadlock is tried again.
func Run ¶
func Run[A taskmill.Args](tb testing.TB, client *taskmill.Client, h taskmill.Handler[A], args A, opts *taskmill.EnqueueOptions) (*taskmill.TaskInfo, error)
Run enqueues a task with args and opts, runs h on it once, the way a worker does, and records the outcome. opts may be nil: set them to run h on a task with metadata, such as taskmill.MetadataScheduledFor for a scheduled run, in a FIFO group, or in another queue. The attempt holds a real lease, so h may complete the task with taskmill.Task.CompleteTx. Run does not retry: a failed task stays retryable or dead. It returns the task afterwards, and the error h returned, or an error describing its panic. If h did not run, because the task's payload does not decode into A, Run returns an error that says so, and the task is dead. To run a task again after a failure, use taskmill.Worker.RunTask.
Run fails the test if the task cannot run now: opts set a DedupeKey that another task holds, or a GroupKey whose group has an unfinished task.
func Work ¶
Work runs a worker with cfg until no task is available or running, then stops it. Tasks that wait for a later run time, such as retries, stay waiting. cfg must not be nil: the worker needs its handlers. If cfg.PollInterval is zero, the worker polls every 10 milliseconds. Work fails the test if cfg is nil, if the worker fails, or if tasks are still available or running after a minute, for example in a queue that the worker does not read.
Example ¶
This example runs every task that the code under test enqueues, with a real worker; see testSignUpEndToEnd above.
package main
import (
"context"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/code19m/taskmill"
"github.com/code19m/taskmill/taskmilltest"
)
// SendWelcome is the task that signing up enqueues.
type SendWelcome struct {
UserID int64 `json:"user_id"`
}
func (SendWelcome) Kind() string { return "user.welcome" }
// signUp is the code under test.
func signUp(ctx context.Context, client *taskmill.Client, userID int64) error {
_, err := client.Enqueue(ctx, SendWelcome{UserID: userID}, nil)
return err
}
// testSignUpEndToEnd is the body of a test that signs a user up, then runs
// every task that this enqueued, with the application's handlers. pool
// connects to the test database.
func testSignUpEndToEnd(t *testing.T, pool *pgxpool.Pool, handlers *taskmill.Handlers) {
t.Helper()
client := taskmilltest.NewClient(t, pool, nil)
if err := signUp(t.Context(), client, 42); err != nil {
t.Fatal(err)
}
taskmilltest.Work(t, client, &taskmill.WorkerConfig{Handlers: handlers})
for _, task := range taskmilltest.Enqueued[SendWelcome](t, client) {
if task.State != taskmill.StateCompleted {
t.Errorf("task %d is %s", task.ID, task.State)
}
}
}
func main() {
_ = testSignUpEndToEnd
}
Output:
Types ¶
This section is empty.