Files
lincodex/backend/internal/adapter/secondary/postgres/organizations_test.go
T

133 lines
6.2 KiB
Go

package postgres
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgconn"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// organizationDetailMarker stands for a row value that a PostgreSQL detail
// can quote, such as the name of a representative.
const organizationDetailMarker = "Failing row contains (Анна Тестова, Руководитель)"
func TestMapOrganizationErrorRecognizesOrganizationConstraints(t *testing.T) {
for _, test := range []struct {
code string
constraint string
want error
}{
{code: uniqueViolationCode, constraint: "memberships_user_id_organization_id_key", want: outbound.ErrMembershipExists},
{code: foreignKeyViolationCode, constraint: "memberships_organization_id_fkey", want: outbound.ErrOrganizationNotFound},
{code: foreignKeyViolationCode, constraint: "memberships_user_id_fkey", want: outbound.ErrUserNotFound},
{code: foreignKeyViolationCode, constraint: "organization_representatives_organization_id_fkey", want: outbound.ErrOrganizationNotFound},
} {
err := mapOrganizationError(&pgconn.PgError{Code: test.code, ConstraintName: test.constraint, Detail: organizationDetailMarker})
if !errors.Is(err, test.want) {
t.Fatalf("mapOrganizationError(%s %s) = %v, want %v", test.code, test.constraint, err, test.want)
}
if !strings.Contains(err.Error(), test.constraint) || strings.Contains(err.Error(), "Failing row") {
t.Fatalf("mapOrganizationError(%s) = %v, want the constraint name and no detail", test.constraint, err)
}
}
}
func TestMapOrganizationErrorDropsDetailOfOtherErrors(t *testing.T) {
// A CHECK violation that the domain should have prevented keeps only the
// SQLSTATE and the constraint, never the failing row with its names.
err := mapOrganizationError(&pgconn.PgError{Code: checkViolationCode, ConstraintName: "organization_representatives_name_format", Detail: organizationDetailMarker})
var stateError sqlStateError
if !errors.As(err, &stateError) || stateError.SQLState() != checkViolationCode {
t.Fatalf("mapOrganizationError() = %v, want SQLSTATE %s", err, checkViolationCode)
}
if strings.Contains(err.Error(), "Анна") || strings.Contains(err.Error(), "Failing row") {
t.Fatalf("mapOrganizationError() = %v, want no row values", err)
}
if err := mapOrganizationError(&pgconn.PgError{Code: deadlockDetectedCode}); !errors.Is(err, outbound.ErrTransactionConflict) {
t.Fatalf("mapOrganizationError(deadlock) = %v, want ErrTransactionConflict", err)
}
if err := mapOrganizationError(context.Canceled); !errors.Is(err, context.Canceled) {
t.Fatalf("mapOrganizationError(context.Canceled) = %v, want the original error", err)
}
}
func TestOrganizationRepositoriesRejectInvalidInputBeforeQuerying(t *testing.T) {
// A repository without queries proves that no statement runs.
organizations := organizationRepository{}
memberships := membershipRepository{}
ctx := t.Context()
if err := organizations.CreateWithOwner(ctx, domain.Organization{}, domain.Membership{}); !errors.Is(err, domain.ErrInvalidOrganization) {
t.Fatalf("CreateWithOwner(zero organization) error = %v, want ErrInvalidOrganization", err)
}
if err := memberships.Insert(ctx, domain.Membership{}); !errors.Is(err, domain.ErrInvalidMembership) {
t.Fatalf("Insert(zero membership) error = %v, want ErrInvalidMembership", err)
}
if _, err := organizations.UpdateProfile(ctx, uuid.New(), domain.Organization{}); !errors.Is(err, domain.ErrInvalidOrganization) {
t.Fatalf("UpdateProfile(zero organization) error = %v, want ErrInvalidOrganization", err)
}
if _, err := organizations.ListForUser(ctx, outbound.OrganizationListQuery{}); !errors.Is(err, domain.ErrInvalidMembership) {
t.Fatalf("ListForUser(zero query) error = %v, want ErrInvalidMembership", err)
}
}
func TestManagerRoleNamesFollowTheDomainRule(t *testing.T) {
if got := managerRoleNames(); len(got) != 1 || got[0] != string(domain.OrganizationRoleOwner) {
t.Fatalf("managerRoleNames() = %v, want only the owner", got)
}
}
func TestOrganizationCreationSnapshotRoundTripsDomainResult(t *testing.T) {
at := time.Date(2026, 8, 15, 10, 30, 0, 123456789, time.UTC)
profile, err := domain.NewOrganizationProfile(domain.OrganizationProfileInput{
Name: "ООО Пример", Description: "Описание", Sphere: "Платежи",
Contacts: domain.OrganizationContactsInput{
Website: "https://example.com", Email: "careers@example.com", Phone: "+74951234567", Telegram: "@example",
},
Representatives: []domain.OrganizationRepresentativeInput{{Name: "Анна Тестова", JobTitle: "Директор"}},
})
if err != nil {
t.Fatalf("NewOrganizationProfile() error = %v", err)
}
company, err := domain.NewOrganization(profile, at)
if err != nil {
t.Fatalf("NewOrganization() error = %v", err)
}
owner, err := domain.NewOwnerMembership(company.ID(), uuid.New(), at)
if err != nil {
t.Fatalf("NewOwnerMembership() error = %v", err)
}
result := outbound.OrganizationCreationResult{Organization: company, Owner: owner}
snapshot := creationSnapshotFromDomain(result)
encoded, err := json.Marshal(snapshot)
if err != nil {
t.Fatalf("Marshal(snapshot) error = %v", err)
}
var decoded organizationCreationSnapshot
if err := json.Unmarshal(encoded, &decoded); err != nil {
t.Fatalf("Unmarshal(snapshot) error = %v", err)
}
got, err := decoded.domainResult()
if err != nil {
t.Fatalf("domainResult() error = %v", err)
}
if got.Organization.ID() != company.ID() || got.Organization.Version() != company.Version() ||
!got.Organization.Profile().Equal(company.Profile()) ||
got.Organization.Verification().Level() != domain.OrganizationVerificationE0 ||
got.Organization.Verification().Basis() != domain.OrganizationBasisConfirmedEmail ||
!got.Organization.CreatedAt().Equal(at) || got.Owner.ID() != owner.ID() || got.Owner.UserID() != owner.UserID() ||
got.Owner.OrganizationID() != company.ID() || got.Owner.Role() != domain.OrganizationRoleOwner || !got.Owner.GrantsAccess() {
t.Fatal("creation snapshot did not preserve the original organization and owner result")
}
if len(encoded) > maxOrganizationCreationSnapshotBytes {
t.Fatalf("snapshot size = %d, want at most %d bytes", len(encoded), maxOrganizationCreationSnapshotBytes)
}
}