Files
lincodex/backend/internal/usecase/candidateprivacy/service_test.go
T

274 lines
10 KiB
Go

package candidateprivacy
import (
"context"
"encoding/json"
"errors"
"fmt"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func TestPublicationCloseWritesHistoryAndTransactionalClosureIntentOnce(t *testing.T) {
const now = "2026-10-07T12:00:00.123456Z"
at := mustTime(t, now)
candidateID, consentID := uuid.New(), uuid.New()
initial := mustPublished(t, candidateID, consentID, at.Add(-time.Hour))
transactor := &privacyTestTransactor{
user: domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: timePointer(at)},
publication: initial,
}
service := mustPrivacyService(t, transactor, at)
closed, err := service.SetMyPublication(context.Background(), candidateID, initial.Version(), domain.PublicationClosed, nil)
if err != nil {
t.Fatalf("SetMyPublication(close) error = %v", err)
}
if closed.StoredState() != domain.PublicationClosed || closed.Version() != initial.Version()+1 {
t.Fatalf("close result = %s v%d, want closed v%d", closed.StoredState(), closed.Version(), initial.Version()+1)
}
if len(transactor.history) != 1 || len(transactor.outboxEvents) != 1 || len(transactor.closureCalls) != 1 {
t.Fatalf("committed close effects = history %d, outbox %d, grants %d; want one each", len(transactor.history), len(transactor.outboxEvents), len(transactor.closureCalls))
}
if got := transactor.sequence; fmt.Sprint(got) != "[close history outbox]" {
t.Fatalf("closure order = %v, want close -> history -> outbox", got)
}
assertVisibilityClosedEvent(t, transactor.outboxEvents[0], candidateID, uuid.Nil, transactor.history[0].ID(), at)
_, err = service.SetMyPublication(context.Background(), candidateID, closed.Version(), domain.PublicationClosed, nil)
if err != nil {
t.Fatalf("repeated SetMyPublication(close) error = %v", err)
}
if len(transactor.history) != 1 || len(transactor.outboxEvents) != 1 || len(transactor.closureCalls) != 1 {
t.Fatalf("repeated close effects = history %d, outbox %d, grants %d; want no duplicate intent", len(transactor.history), len(transactor.outboxEvents), len(transactor.closureCalls))
}
}
func TestValidatePageAcceptsTypedNilInitialCursors(t *testing.T) {
t.Parallel()
var privacyCursor *outbound.CandidatePrivacyEventPosition
var hiddenCursor *outbound.HiddenOrganizationPosition
userID := uuid.New()
for _, test := range []struct {
name string
after any
}{
{name: "privacy history", after: privacyCursor},
{name: "hidden organizations", after: hiddenCursor},
} {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
if err := validatePage(userID, 20, test.after); err != nil {
t.Fatalf("validatePage(initial cursor) error = %v, want nil", err)
}
})
}
}
func TestPublicationCloseRollsBackWhenClosureIntentCannotBeStored(t *testing.T) {
at := mustTime(t, "2026-10-07T12:00:00.123456Z")
candidateID, consentID := uuid.New(), uuid.New()
initial := mustPublished(t, candidateID, consentID, at.Add(-time.Hour))
transactor := &privacyTestTransactor{
user: domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: timePointer(at)},
publication: initial, outboxError: errors.New("outbox unavailable"),
}
service := mustPrivacyService(t, transactor, at)
if _, err := service.SetMyPublication(context.Background(), candidateID, initial.Version(), domain.PublicationClosed, nil); err == nil {
t.Fatal("SetMyPublication(close) error = nil, want closure intent failure")
}
if transactor.publication.Version() != initial.Version() || transactor.publication.StoredState() != domain.PublicationPublished {
t.Fatalf("publication after failed transaction = %s v%d, want unchanged published v%d", transactor.publication.StoredState(), transactor.publication.Version(), initial.Version())
}
if len(transactor.history) != 0 || len(transactor.outboxEvents) != 0 || len(transactor.closureCalls) != 0 {
t.Fatalf("effects after failed transaction = history %d, outbox %d, grants %d; want rollback", len(transactor.history), len(transactor.outboxEvents), len(transactor.closureCalls))
}
}
func mustPrivacyService(t *testing.T, transactor outbound.Transactor, at time.Time) *Service {
t.Helper()
service, err := NewService(Dependencies{Transactor: transactor, Clock: func() time.Time { return at }})
if err != nil {
t.Fatalf("NewService() error = %v", err)
}
return service
}
func mustPublished(t *testing.T, candidateID, consentID uuid.UUID, at time.Time) domain.Publication {
t.Helper()
publication, err := domain.NewPublication(candidateID)
if err != nil {
t.Fatalf("NewPublication() error = %v", err)
}
request, err := domain.NewPublicationRequest(domain.PublicationPublished, []domain.CardField{domain.CardFieldStack})
if err != nil {
t.Fatalf("NewPublicationRequest() error = %v", err)
}
change, err := publication.Apply(request, 0, consentID, at)
if err != nil || !change.Changed {
t.Fatalf("Apply(publish) = %+v, %v, want change", change, err)
}
return change.Publication
}
func assertVisibilityClosedEvent(t *testing.T, event domain.DomainEvent, candidateID, organizationID, privacyEventID uuid.UUID, at time.Time) {
t.Helper()
if event.EventType() != "privacy.visibility_closed" || event.SchemaVersion() != 1 ||
event.AggregateType() != "privacy_event" || event.AggregateID() != privacyEventID || event.AggregateVersion() != 1 {
t.Fatalf("closure event identity = %s v%d %s/%s v%d", event.EventType(), event.SchemaVersion(), event.AggregateType(), event.AggregateID(), event.AggregateVersion())
}
var payload struct {
CandidateID uuid.UUID `json:"candidate_id"`
OrganizationID *uuid.UUID `json:"organization_id"`
Reason string `json:"reason"`
OccurredAt time.Time `json:"occurred_at"`
PrivacyEventID uuid.UUID `json:"privacy_event_id"`
}
if err := json.Unmarshal(event.Payload(), &payload); err != nil {
t.Fatalf("decode closure payload: %v", err)
}
if payload.CandidateID != candidateID || payload.Reason != "publication_closed" ||
payload.PrivacyEventID != privacyEventID || !payload.OccurredAt.Equal(at) || payload.OrganizationID != nil || organizationID != uuid.Nil {
t.Fatalf("closure payload = %+v", payload)
}
}
func mustTime(t *testing.T, value string) time.Time {
t.Helper()
at, err := time.Parse(time.RFC3339Nano, value)
if err != nil {
t.Fatalf("parse test time: %v", err)
}
return at
}
func timePointer(value time.Time) *time.Time { return &value }
type privacyTestTransactor struct {
user domain.User
publication domain.Publication
history []domain.PrivacyEvent
outboxEvents []domain.DomainEvent
closureCalls []privacyClosureCall
sequence []string
outboxError error
}
type privacyClosureCall struct {
candidateID uuid.UUID
organizationID uuid.UUID
at time.Time
}
func (transactor *privacyTestTransactor) WithinTransaction(ctx context.Context, fn func(context.Context, outbound.UnitOfWork) error) error {
draft := &privacyTestTransactor{
user: transactor.user, publication: transactor.publication,
history: append([]domain.PrivacyEvent(nil), transactor.history...),
outboxEvents: append([]domain.DomainEvent(nil), transactor.outboxEvents...),
closureCalls: append([]privacyClosureCall(nil), transactor.closureCalls...),
sequence: append([]string(nil), transactor.sequence...), outboxError: transactor.outboxError,
}
unit := privacyTestUnit{
users: privacyTestUsers{user: draft.user},
settings: privacyTestSettings{transactor: draft},
view: privacyTestView{transactor: draft},
outbox: privacyTestOutbox{transactor: draft},
}
if err := fn(ctx, unit); err != nil {
return err
}
transactor.publication = draft.publication
transactor.history = draft.history
transactor.outboxEvents = draft.outboxEvents
transactor.closureCalls = draft.closureCalls
transactor.sequence = draft.sequence
return nil
}
type privacyTestUnit struct {
outbound.UnitOfWork
users outbound.UserRepository
settings outbound.PrivacySettingsRepository
view outbound.PrivacyViewRepository
outbox outbound.OutboxWriter
}
func (unit privacyTestUnit) Users() outbound.UserRepository { return unit.users }
func (unit privacyTestUnit) PrivacySettings() outbound.PrivacySettingsRepository {
return unit.settings
}
func (unit privacyTestUnit) PrivacyView() outbound.PrivacyViewRepository { return unit.view }
func (unit privacyTestUnit) Outbox() outbound.OutboxWriter { return unit.outbox }
type privacyTestUsers struct {
outbound.UserRepository
user domain.User
}
func (users privacyTestUsers) GetByID(context.Context, uuid.UUID) (domain.User, error) {
return users.user, nil
}
type privacyTestSettings struct {
outbound.PrivacySettingsRepository
transactor *privacyTestTransactor
}
func (settings privacyTestSettings) ReadSettings(context.Context, uuid.UUID) (outbound.CandidatePrivacySettings, error) {
return outbound.CandidatePrivacySettings{Publication: settings.transactor.publication}, nil
}
func (settings privacyTestSettings) LockCurrentC2ForPublication(context.Context, uuid.UUID) (uuid.UUID, error) {
return settings.transactor.publication.ConsentRecordID(), nil
}
func (settings privacyTestSettings) SavePublication(_ context.Context, publication domain.Publication, _ int64) error {
settings.transactor.publication = publication
return nil
}
func (settings privacyTestSettings) RecordPrivacyEvent(_ context.Context, event domain.PrivacyEvent) error {
settings.transactor.history = append(settings.transactor.history, event)
settings.transactor.sequence = append(settings.transactor.sequence, "history")
return nil
}
type privacyTestView struct {
outbound.PrivacyViewRepository
transactor *privacyTestTransactor
}
func (view privacyTestView) CloseForVisibility(_ context.Context, candidateID, organizationID uuid.UUID, at time.Time) error {
view.transactor.closureCalls = append(view.transactor.closureCalls, privacyClosureCall{
candidateID: candidateID, organizationID: organizationID, at: at,
})
view.transactor.sequence = append(view.transactor.sequence, "close")
return nil
}
type privacyTestOutbox struct {
outbound.OutboxWriter
transactor *privacyTestTransactor
}
func (outbox privacyTestOutbox) Append(_ context.Context, events ...domain.DomainEvent) error {
if outbox.transactor.outboxError != nil {
return outbox.transactor.outboxError
}
outbox.transactor.outboxEvents = append(outbox.transactor.outboxEvents, events...)
outbox.transactor.sequence = append(outbox.transactor.sequence, "outbox")
return nil
}