Documentation
Testing
Run a cluster inside one go test, break it on purpose, test one actor with fakes, and make timers deterministic.
A multi-node scenario runs as a plain go test, with no sockets and no registry. The code is from examples/testing and the tutorial's conversations service.
A cluster in a test
grpcproctest.New(t, names...) starts a node per name, each with its own gRPC server, talking over in-memory connections. The nodes stop when the test ends. Every node resolves the others by name, so a process on one is reached from another through grpcproc.Named, as in production.
c := grpcproctest.New(t, "shop", "warehouse")
shop, warehouse := c.Node("shop"), c.Node("warehouse")NewWith(t, opts, names...) takes options that apply to every node, each time it starts, restarts included:
WithHooks(h) | Installs an observability tap on every node. |
WithLogger(l) | The logger every node uses. By default the nodes log nothing. |
WithConfig(fn) | Adjusts a node's Config before the node is created, by name: a Registrar, a Membership, a DialBackoff, hooks for one node only. |
WithServices(fn) | Registers extra gRPC services on every node's server, an Inspector say. c.Conn(name) dials a node's server from outside the cluster to call them. |
Two things differ from a production node. The cluster's nodes dial a peer again at once after a failed dial, since DialBackoff is negative, so the send right after a partition heals reaches the peer; a test of the backoff itself sets one with WithConfig. And the connections are in memory, so keepalive never fires: the cluster breaks links itself.
Partitions, crashes and restarts
The cluster is also the network between its nodes, and can break it. Processes see each fault as they would in production:
Partition(a, b) | Cuts the network between two nodes both ways. Existing links break, so monitors across them fire Down{noconnection} and pending calls fail with ErrNoConnection; new dials are refused until Heal(a, b). |
Kill(name) | Stops a node abruptly, as a crash would: no Down{shutdown} reaches anyone, peers see their links break. By the time it returns, monitors have fired and calls have failed. |
Stop(name) | Stops a node gracefully: its processes exit with shutdown, and their watchers get Down{shutdown} before the links close. |
Restart(name) | Starts a stopped or killed node again, with a new incarnation and none of the processes the old one ran. An address from before points at a process that no longer exists. |
The example's test uses each. The process under test is the quick start's stock; the test reserves across nodes, then breaks things:
func TestReserveAcrossNodes(t *testing.T) {
// Two nodes over in-memory gRPC connections, stopped when the test ends.
c := grpcproctest.New(t, "shop", "warehouse")
shop := c.Node("shop")
if _, err := c.Node("warehouse").Spawn(Stock(map[string]int64{"apple": 3}), grpcproc.WithName("stock")); err != nil {
t.Fatal(err)
}
stock := grpcproc.Named[*shoppb.Reserve]("warehouse", "stock")
apple := &shoppb.Reserve{Sku: "apple", Qty: 1}
if r, err := stock.Call[*shoppb.Reserved](t.Context(), shop, apple); err != nil || r.Left != 2 {
t.Fatal(r, err)
}
// A partition fails calls, and fires monitors with Down{noconnection},
// until it heals.
c.Partition("shop", "warehouse")
if _, err := stock.Call[*shoppb.Reserved](t.Context(), shop, apple); !errors.Is(err, grpcproc.ErrNoConnection) {
t.Fatal(err)
}
c.Heal("shop", "warehouse")
if r, err := stock.Call[*shoppb.Reserved](t.Context(), shop, apple); err != nil || r.Left != 1 {
t.Fatal(r, err)
}
// A crash, and a restart: same node name, new incarnation, and none of
// the processes the old one ran.
c.Kill("warehouse")
c.Restart("warehouse")
if _, err := stock.Call[*shoppb.Reserved](t.Context(), shop, apple); !errors.Is(err, grpcproc.ErrNoProc) {
t.Fatal(err)
}
}Assert on the error, with errors.Is: ErrNoConnection during a partition, ErrNoProc after a restart, since the name is registered on nobody on the new incarnation. After Stop, a process monitoring the stock would receive Down{shutdown}; after Kill or a partition, the reason is noconnection. Errors and exit reasons lists every one.
One actor, with fakes
Most tests need one node. An actor that calls other actors takes their addresses, and a test puts fakes behind them: plain process functions, registered under the names the contracts give, on the node the actor was told to use. In the tutorial a conversation calls a model and a sandbox; its test composes the platform and the conversations module alone, then spawns a model and a sandbox of its own:
// The conversations alone. Their collaborators are addresses, so a test
// puts fakes behind them: processes registered under the names the
// contracts give, on the node the placement points at, which with none is
// this one, and a scheduler in the models group. What the model is asked
// comes out on a channel, for the test to read.
func service(t *testing.T, limits conversations.Limits, model func(*modelsv1.Generate) *modelsv1.Generated) (*grpcproc.Node, <-chan *modelsv1.Generate) {
t.Helper()
s := di.Test(t)
platform.Compose(s, platform.Config{Node: "local", Listen: "127.0.0.1:0"}, slog.New(slog.DiscardHandler), conversations.Module)
s.Value(limits).Override()
if err := s.Start(t.Context()); err != nil {
t.Fatal(err)
}
n := s.Get[*grpcproc.Node]()
asked := make(chan *modelsv1.Generate, 8)
scheduler := func(p *grpcproc.Process[*modelsv1.Generate]) error {
for {
m, err := p.Receive()
if err != nil {
return err
}
asked <- m.Body
_ = m.Reply(model(m.Body), nil)
}
}
a, err := n.Spawn(scheduler, grpcproc.WithName(modelsv1.SchedulerProcess))
if err != nil {
t.Fatal(err)
}
if err := s.Get[*groups.Scope]().Join(t.Context(), n, modelsv1.Group, a.PID()); err != nil {
t.Fatal(err)
}
// A sandbox that takes every call and answers none.
runner := func(p *grpcproc.Process[*toolsv1.Run]) error {
for {
if _, err := p.Receive(); err != nil {
return err
}
}
}
if _, err := n.Spawn(runner, grpcproc.WithName(toolsv1.RunnerProcess)); err != nil {
t.Fatal(err)
}
return n, asked
}The model is the test's parameter, and reports what it is asked on a channel; the sandbox takes every call and answers none. One test has the model ask for a tool, and expects the conversation to give up on the sandbox at its deadline and tell the model:
// A tool that does not answer in time is an answer: the model is asked
// again, and told.
func TestAToolWithNoAnswerIsToldToTheModel(t *testing.T) {
limits := conversations.Limits{Idle: time.Minute, Generate: time.Second, Tool: 50 * time.Millisecond, Busy: time.Millisecond}
n, asked := service(t, limits, func(g *modelsv1.Generate) *modelsv1.Generated {
if last := g.History[len(g.History)-1]; last.Role == modelsv1.Role_ROLE_TOOL {
return &modelsv1.Generated{Text: "It did not answer."}
}
return &modelsv1.Generated{Text: "One moment.", Tool: &toolsv1.Run{Name: "sleep", Args: "1h"}}
})
if _, err := conversationsv1.NewConversation("local", "1").Say(t.Context(), n, "wait an hour"); err != nil {
t.Fatal(err)
}
next(t, asked)
last := next(t, asked).History[2] // the user, the model, the tool
if last.Role != modelsv1.Role_ROLE_TOOL || !strings.Contains(last.Text, "no answer from the sandbox") {
t.Fatalf("the model was told %v", last)
}
}Another lets a conversation go idle, waits for its process to end, speaks to it again, and reads from the channel that the new process showed the model what was said to the old one:
// A conversation nobody speaks to ends its process, and the next thing said
// starts one that knows what was said before.
func TestAnIdleConversationEndsAndComesBack(t *testing.T) {
limits := conversations.Limits{Idle: 50 * time.Millisecond, Generate: time.Second, Tool: time.Second, Busy: time.Millisecond}
n, asked := service(t, limits, func(*modelsv1.Generate) *modelsv1.Generated {
return &modelsv1.Generated{Text: "Noted."}
})
c := conversationsv1.NewConversation("local", "1")
if said, err := c.Say(t.Context(), n, "one"); err != nil || said.Turn != 1 {
t.Fatalf("%v %v", said, err)
}
next(t, asked)
// A call of a type the conversation has no rpc for is answered ErrType,
// as the node answered it when the mailbox held one type, and does not
// keep the conversation from going idle.
if _, err := n.CallTo[*conversationsv1.Said](t.Context(), c.ConversationAddr, &conversationsv1.Open{Id: "1"}); !errors.Is(err, grpcproc.ErrType) {
t.Fatalf("a stranger's call: %v", err)
}
for range 500 {
if _, running := n.Whereis(c.Name()); !running {
break
}
time.Sleep(10 * time.Millisecond)
}
if _, running := n.Whereis(c.Name()); running {
t.Fatal("the conversation is still running")
}
if said, err := c.Say(t.Context(), n, "two"); err != nil || said.Turn != 2 {
t.Fatalf("%v %v", said, err)
}
if h := next(t, asked).History; len(h) != 3 || h[0].Text != "one" || h[1].Text != "Noted." || h[2].Text != "two" {
t.Fatalf("the model was shown %v", h)
}
}A fake is a process function, a dozen lines here. One that must answer on another node is the same function spawned on another node of a grpcproctest cluster.
Waiting for an exit or a spawn
A test that crashes a supervised actor needs to know when the replacement runs. node.Subscribe(ctx, buffer) returns a channel of events: spawns, exits with their reasons, links up and down, dead letters. Subscribe before the fault, so the exit cannot be missed, then read until the spawn:
events := node.Subscribe(ctx, 16)
if err := inventory.Restock(ctx, node, &shoppb.Restock{Sku: "apple", Qty: 0}); err != nil {
log.Fatal(err)
}
for e := range events {
if e.Process.Name != "inventory" {
continue
}
if e.Kind == grpcproc.EventExit {
fmt.Println("inventory exited:", e.Reason)
}
if e.Kind == grpcproc.EventSpawn {
fmt.Println("inventory started again")
break
}
}A subscriber that falls behind loses events rather than block the node; the next event it gets says how many in Missed. A test buffer of a few dozen is plenty. For a process that must be gone, node.Process(pid) answers whether it still runs, and node.Whereis(name) whether a name is registered.
Deterministic tests
Go's testing/synctest makes tests that involve time deterministic. Inside synctest.Test, the time package runs on a fake clock that moves only when every goroutine in the test's bubble waits, and synctest.Wait returns once they all do. grpcproc runs in a bubble as it is: a process waits on channels the bubble sees, and SendAfter, ReceiveTimeout, a caller's deadline and a supervisor's restart window and Shutdown all keep the bubble's time. A grpcproctest cluster runs there too, since its connections are in memory, and so do its partitions, crashes and restarts.
// The tree restarts the inventory 3 times a minute. Inside a synctest
// bubble a minute is virtual: time.Sleep spends it at once, and
// synctest.Wait returns once the restart it caused has settled.
func TestRestartsThreeTimesAMinute(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
node, err := grpcproc.NewNode(grpcproc.Config{Admit: grpcproc.AdmitAll, Name: "shop", Resolver: grpcproc.StaticResolver{}})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = node.Stop(context.Background()) })
sup, err := actor.Supervise(node, tree(&Ledger{left: map[string]int64{}}))
if err != nil {
t.Fatal(err)
}
inventory := shoppb.StockAddr{Addr: grpcproc.Named[*shoppb.Stock]("shop", "inventory")}
crash := func() { // a restock of zero is a bug, and ends the inventory
_ = inventory.Restock(t.Context(), node, &shoppb.Restock{Sku: "apple", Qty: 0})
synctest.Wait()
}
supervising := func() bool { _, ok := node.Process(sup); return ok }
// A crash a minute never makes two restarts in one.
for range 5 {
crash()
time.Sleep(time.Minute)
}
if !supervising() {
t.Fatal("the supervisor gave up on a crash a minute")
}
// Four in a row are one restart too many.
for range 4 {
crash()
}
if supervising() {
t.Fatal("the supervisor outlived four crashes in a minute")
}
})
}time.Sleep(time.Minute) takes no real time, and synctest.Wait after a crash returns once the supervisor has restarted the child, or given up: every process waits, so the test can look. Outside a bubble, subscribing does that for one event.
Two rules keep a test in its bubble. Everything it uses is made inside synctest.Test: nodes, clusters, channels, contexts; a channel or a timer made outside cannot be used inside. And every process has ended by the time the test does, or synctest reports a deadlock with the goroutines still waiting: stopping the node in t.Cleanup, as grpcproctest does, ends them all, and the report shows a process that ignores its exit. Real sockets stay outside: a goroutine blocked on the network is not waiting where the bubble can see it, so a test that listens on a port, as the blocking I/O example does, or talks to etcd, runs on real time.
In CI
A cluster test needs no ports and no external services, and takes a few hundred milliseconds. Run it under the race detector: a test that reaches into an actor's fields from the test goroutine is a race, and should talk to the actor through its mailbox instead.
go test -race -count=1 ./...Timeouts on calls in tests come from t.Context(), which is cancelled when the test ends, or a context.WithTimeout around it for a call that is expected to fail; a call with no deadline to a process that never answers is a test that never ends.