Files
lincodex/backend/internal/usecase/notification/inbox_test.go
T

246 lines
8.8 KiB
Go

package notification
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func TestInboxServiceStoreInvitationDeliveredDeduplicatesRecipientEvent(t *testing.T) {
t.Parallel()
repository := &memoryInboxRepository{}
service := newInboxTestService(t, repository, &memoryInboxResolver{}, time.Now)
input := inboxTestEntryInput()
created, err := service.StoreInvitationDelivered(context.Background(), input)
if err != nil || !created {
t.Fatalf("StoreInvitationDelivered(first) = %t, %v, want true, nil", created, err)
}
created, err = service.StoreInvitationDelivered(context.Background(), input)
if err != nil || created {
t.Fatalf("StoreInvitationDelivered(retry) = %t, %v, want false, nil", created, err)
}
if len(repository.entries) != 1 {
t.Fatalf("stored entries = %d, want one", len(repository.entries))
}
changed := input
changed.SourceID = uuid.New()
if _, err := service.StoreInvitationDelivered(context.Background(), changed); !errors.Is(err, outbound.ErrNotificationInboxEventConflict) {
t.Fatalf("StoreInvitationDelivered(changed replay) error = %v, want ErrNotificationInboxEventConflict", err)
}
}
func TestInboxServiceListRechecksContentAndFallsBackSafely(t *testing.T) {
t.Parallel()
first := mustInboxTestEntry(t, inboxTestEntryInput())
secondInput := inboxTestEntryInput()
secondInput.RecipientUserID = first.RecipientUserID()
secondInput.OrganizationID = first.OrganizationID()
secondInput.EventID = uuid.New()
second := mustInboxTestEntry(t, secondInput)
wrongOrganizationInput := inboxTestEntryInput()
wrongOrganizationInput.RecipientUserID = first.RecipientUserID()
wrongOrganizationInput.EventID = uuid.New()
wrongOrganizationInput.OrganizationID = uuid.New()
wrongOrganization := mustInboxTestEntry(t, wrongOrganizationInput)
repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{first, second, wrongOrganization}}
resolver := &memoryInboxResolver{unavailable: map[uuid.UUID]bool{second.EventID(): true}}
service := newInboxTestService(t, repository, resolver, time.Now)
orgID := first.OrganizationID()
page, err := service.List(context.Background(), InboxListRequest{
RecipientUserID: first.RecipientUserID(), OrganizationID: &orgID, Limit: 10,
})
if err != nil {
t.Fatalf("List() error = %v", err)
}
if len(page.Items) != 2 {
t.Fatalf("List() returned %d items, want 2", len(page.Items))
}
if page.Items[0].Content == nil || page.Items[0].ContentUnavailable {
t.Fatalf("visible item = %+v, want current content", page.Items[0])
}
if page.Items[1].Content != nil || !page.Items[1].ContentUnavailable {
t.Fatalf("hidden item = %+v, want safe fallback without source content", page.Items[1])
}
if resolver.calls != 2 {
t.Fatalf("resolver calls = %d, want one current visibility check per returned item", resolver.calls)
}
}
func TestInboxServiceListRejectsRepositoryRowsOutsideRecipientScope(t *testing.T) {
t.Parallel()
entry := mustInboxTestEntry(t, inboxTestEntryInput())
repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{entry}, ignoreListScope: true}
service := newInboxTestService(t, repository, &memoryInboxResolver{}, time.Now)
_, err := service.List(context.Background(), InboxListRequest{
RecipientUserID: uuid.New(), OrganizationID: uuidPointer(entry.OrganizationID()), Limit: 10,
})
if !errors.Is(err, ErrInboxUnavailable) {
t.Fatalf("List(out-of-scope repository row) error = %v, want ErrInboxUnavailable", err)
}
}
func TestInboxServiceMarkReadPersistsAndKeepsFirstTime(t *testing.T) {
t.Parallel()
entry := mustInboxTestEntry(t, inboxTestEntryInput())
firstRead := time.Date(2026, time.October, 8, 13, 0, 0, 1000, time.UTC)
secondRead := firstRead.Add(time.Hour)
clockCalls := 0
clock := func() time.Time {
clockCalls++
if clockCalls == 1 {
return firstRead
}
return secondRead
}
repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{entry}}
service := newInboxTestService(t, repository, &memoryInboxResolver{}, clock)
for range 2 {
read, err := service.MarkRead(context.Background(), entry.RecipientUserID(), entry.OrganizationID(), entry.EventID())
if err != nil {
t.Fatalf("MarkRead() error = %v", err)
}
got, isRead := read.ReadAt()
if !isRead || !got.Equal(firstRead.UTC().Truncate(time.Microsecond)) {
t.Fatalf("ReadAt() = %s, %t, want the first read time", got, isRead)
}
}
}
func TestNewInboxContentRejectsExternalOrAmbiguousLinks(t *testing.T) {
t.Parallel()
tests := []struct {
name string
path string
}{
{name: "external URL", path: "https://example.test/invitation"},
{name: "protocol-relative URL", path: "//example.test/invitation"},
{name: "query string", path: "/candidate/invitations?token=secret"},
{name: "fragment", path: "/candidate/invitations#current"},
{name: "backslash", path: `/candidate\\invitations`},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
if _, err := NewInboxContent("Приглашение", "Проверьте новое приглашение.", test.path); !errors.Is(err, ErrInboxUnavailable) {
t.Fatalf("NewInboxContent() error = %v, want ErrInboxUnavailable", err)
}
})
}
}
func newInboxTestService(
t *testing.T,
repository outbound.NotificationInboxRepository,
resolver InboxContentResolver,
clock func() time.Time,
) *InboxService {
t.Helper()
service, err := NewInboxService(repository, resolver, clock)
if err != nil {
t.Fatalf("NewInboxService() error = %v", err)
}
return service
}
func inboxTestEntryInput() domain.NotificationInboxEntryInput {
return domain.NotificationInboxEntryInput{
EventID: uuid.New(), RecipientUserID: uuid.New(), OrganizationID: uuid.New(),
EventType: domain.NotificationInboxInvitationDelivered, SchemaVersion: 1,
SourceType: domain.NotificationInboxSourceInvitation, SourceID: uuid.New(),
OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC),
}
}
func mustInboxTestEntry(t *testing.T, input domain.NotificationInboxEntryInput) domain.NotificationInboxEntry {
t.Helper()
entry, err := domain.NewNotificationInboxEntry(input)
if err != nil {
t.Fatalf("NewNotificationInboxEntry() error = %v", err)
}
return entry
}
func uuidPointer(value uuid.UUID) *uuid.UUID { return &value }
type memoryInboxRepository struct {
entries []domain.NotificationInboxEntry
ignoreListScope bool
}
func (repository *memoryInboxRepository) Store(_ context.Context, entry domain.NotificationInboxEntry) (bool, error) {
for _, existing := range repository.entries {
if existing.RecipientUserID() != entry.RecipientUserID() || existing.EventID() != entry.EventID() {
continue
}
if !sameInboxEvent(existing, entry) {
return false, outbound.ErrNotificationInboxEventConflict
}
return false, nil
}
repository.entries = append(repository.entries, entry)
return true, nil
}
func (repository *memoryInboxRepository) List(_ context.Context, query outbound.NotificationInboxListQuery) (outbound.NotificationInboxPage, error) {
page := outbound.NotificationInboxPage{}
for _, entry := range repository.entries {
if !repository.ignoreListScope && (entry.RecipientUserID() != query.RecipientUserID || (query.OrganizationID != nil && entry.OrganizationID() != *query.OrganizationID)) {
continue
}
page.Items = append(page.Items, entry)
}
return page, nil
}
func (repository *memoryInboxRepository) MarkRead(
_ context.Context,
recipientUserID uuid.UUID,
organizationID uuid.UUID,
eventID uuid.UUID,
at time.Time,
) (domain.NotificationInboxEntry, error) {
for index, entry := range repository.entries {
if entry.RecipientUserID() != recipientUserID || entry.OrganizationID() != organizationID || entry.EventID() != eventID {
continue
}
read, err := entry.MarkRead(at)
if err != nil {
return domain.NotificationInboxEntry{}, err
}
repository.entries[index] = read
return read, nil
}
return domain.NotificationInboxEntry{}, outbound.ErrNotificationInboxEntryNotFound
}
func sameInboxEvent(left, right domain.NotificationInboxEntry) bool {
return left.OrganizationID() == right.OrganizationID() && left.EventType() == right.EventType() &&
left.SchemaVersion() == right.SchemaVersion() && left.SourceType() == right.SourceType() &&
left.SourceID() == right.SourceID() && left.OccurredAt().Equal(right.OccurredAt())
}
type memoryInboxResolver struct {
unavailable map[uuid.UUID]bool
calls int
}
func (resolver *memoryInboxResolver) Resolve(_ context.Context, entry domain.NotificationInboxEntry) (InboxContent, error) {
resolver.calls++
if resolver.unavailable[entry.EventID()] {
return InboxContent{}, ErrInboxContentUnavailable
}
return NewInboxContent("Приглашение", "Проверьте новое приглашение.", "/candidate/invitations")
}