Files
archie/internal/infrastructure/controlplanerpc/workflows_test.go
T

90 lines
3.0 KiB
Go

package controlplanerpc
import (
"context"
"strings"
"testing"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/access"
)
// fakeControlPlane records the commands it is sent and refuses a replace the
// way the control plane does when a field it audits is missing.
type fakeControlPlane struct {
pb.ControlPlaneServiceClient
commands []*pb.CommandRequest
}
func (*fakeControlPlane) Query(context.Context, *pb.QueryRequest, ...grpc.CallOption) (*pb.QueryResponse, error) {
return &pb.QueryResponse{Resource: &pb.Resource{ValueJson: []byte(`{"drafts":[]}`), Version: 3}}, nil
}
func (f *fakeControlPlane) Command(_ context.Context, request *pb.CommandRequest, _ ...grpc.CallOption) (*pb.CommandResponse, error) {
f.commands = append(f.commands, request)
if request.GetActor() == "" || request.GetSource() == "" || request.GetRequestId() == "" {
return nil, status.Error(codes.InvalidArgument, "actor, source, and request ID are required")
}
return &pb.CommandResponse{}, nil
}
func TestPutDraftAttributesTheCaller(t *testing.T) {
for _, tt := range []struct {
name string
principal *access.Principal
saves int
wantErr bool
}{
{"authenticated caller is the actor", &access.Principal{IdentityID: "alice"}, 1, false},
{"no principal", nil, 1, true},
{"each save is its own request", &access.Principal{IdentityID: "alice"}, 2, false},
} {
t.Run(tt.name, func(t *testing.T) {
client := &fakeControlPlane{}
ctx := t.Context()
if tt.principal != nil {
ctx = access.WithPrincipal(ctx, *tt.principal)
}
workflows := NewWorkflows(client)
for range tt.saves {
err := workflows.PutDraft(ctx, "report", "id: report\n")
if (err != nil) != tt.wantErr {
t.Fatalf("PutDraft error = %v, want error %t", err, tt.wantErr)
}
}
if tt.wantErr {
if len(client.commands) != 0 {
t.Fatalf("issued %d commands, want none", len(client.commands))
}
return
}
if len(client.commands) != tt.saves {
t.Fatalf("issued %d commands, want %d", len(client.commands), tt.saves)
}
requestIDs := make(map[string]bool, len(client.commands))
for _, command := range client.commands {
if got, want := command.GetActor(), string(tt.principal.IdentityID); got != want {
t.Errorf("actor = %q, want %q", got, want)
}
if command.GetSource() == "" || command.GetRequestId() == "" {
t.Errorf("command %+v lacks a source or request ID", command)
}
if requestIDs[command.GetRequestId()] {
t.Errorf("request ID %q repeats an earlier save", command.GetRequestId())
}
requestIDs[command.GetRequestId()] = true
if command.GetExpectedVersion() != 3 {
t.Errorf("expected version = %d, want 3", command.GetExpectedVersion())
}
if !strings.Contains(string(command.GetValueJson()), `"id":"report"`) {
t.Errorf("value = %s, want the draft for report", command.GetValueJson())
}
}
})
}
}