Files
lincodex/backend/internal/domain/organization_test.go
T

390 lines
20 KiB
Go

package domain
import (
"bytes"
"errors"
"fmt"
"log/slog"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
var organizationTestTime = time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC)
func completeOrganizationProfileInput() OrganizationProfileInput {
return OrganizationProfileInput{
Name: "ООО Пример Платежи",
Description: "Платежный сервис для малого бизнеса.\nСобственное ядро платежей.",
Sphere: "Платежи и финансовые сервисы",
Contacts: OrganizationContactsInput{
Website: "https://payments.example.com/careers?team=core",
Email: "careers@payments.example.com",
Phone: "+74950000000",
Telegram: "@payments_careers",
},
Representatives: []OrganizationRepresentativeInput{{Name: "Анна Тестова", JobTitle: "Руководитель по подбору"}},
}
}
func mustOrganizationProfile(t *testing.T, input OrganizationProfileInput) OrganizationProfile {
t.Helper()
profile, err := NewOrganizationProfile(input)
if err != nil {
t.Fatalf("NewOrganizationProfile() error = %v", err)
}
return profile
}
func TestNewOrganizationProfileAcceptsACompleteAndAMinimalProfile(t *testing.T) {
profile := mustOrganizationProfile(t, completeOrganizationProfileInput())
if profile.Name() != "ООО Пример Платежи" || profile.Sphere() != "Платежи и финансовые сервисы" ||
profile.Contacts().Website() != "https://payments.example.com/careers?team=core" ||
profile.Contacts().Phone() != "+74950000000" || profile.Contacts().Telegram() != "@payments_careers" ||
profile.Contacts().Email() != "careers@payments.example.com" {
t.Fatalf("profile = %+v, want the given values", profile)
}
if representatives := profile.Representatives(); len(representatives) != 1 || representatives[0].Name() != "Анна Тестова" ||
representatives[0].JobTitle() != "Руководитель по подбору" {
t.Fatalf("representatives = %v, want the given one", representatives)
}
minimal := mustOrganizationProfile(t, OrganizationProfileInput{Name: "A"})
if minimal.Description() != "" || minimal.Sphere() != "" || minimal.Contacts() != (OrganizationContacts{}) || len(minimal.Representatives()) != 0 {
t.Fatalf("minimal profile = %+v, want every optional field unset", minimal)
}
}
func TestNewOrganizationProfileNormalizesDescriptionLineBreaks(t *testing.T) {
input := completeOrganizationProfileInput()
input.Description = "first\r\nsecond"
if got := mustOrganizationProfile(t, input).Description(); got != "first\nsecond" {
t.Fatalf("Description() = %q, want CRLF stored as LF", got)
}
input.Description = "first\rsecond"
if _, err := NewOrganizationProfile(input); !errors.Is(err, ErrInvalidOrganization) {
t.Fatalf("NewOrganizationProfile(lone CR) error = %v, want ErrInvalidOrganization", err)
}
}
func TestNewOrganizationProfileNamesTheFieldThatBreaksARule(t *testing.T) {
longName := strings.Repeat("я", maxOrganizationNameRunes+1)
for _, test := range []struct {
name string
change func(*OrganizationProfileInput)
pointer string
}{
{"empty name", func(in *OrganizationProfileInput) { in.Name = "" }, "/name"},
{"name with a leading space", func(in *OrganizationProfileInput) { in.Name = " ООО" }, "/name"},
{"name with a trailing tab", func(in *OrganizationProfileInput) { in.Name = "ООО\t" }, "/name"},
{"name with a line break", func(in *OrganizationProfileInput) { in.Name = "ООО\nПример" }, "/name"},
{"name with a line separator", func(in *OrganizationProfileInput) { in.Name = "ООО\u2028Пример" }, "/name"},
{"name over 200 characters", func(in *OrganizationProfileInput) { in.Name = longName }, "/name"},
{"name that is not UTF-8", func(in *OrganizationProfileInput) { in.Name = "ООО\xff" }, "/name"},
{"description with a leading line break", func(in *OrganizationProfileInput) { in.Description = "\nтекст" }, "/description"},
{"description with a control character", func(in *OrganizationProfileInput) { in.Description = "текст\x07" }, "/description"},
{"description over 2000 characters", func(in *OrganizationProfileInput) {
in.Description = strings.Repeat("я", maxOrganizationDescriptionRunes+1)
}, "/description"},
{"sphere with a line break", func(in *OrganizationProfileInput) { in.Sphere = "Платежи\nи сервисы" }, "/sphere"},
{"website over http", func(in *OrganizationProfileInput) { in.Contacts.Website = "http://payments.example.com" }, "/contacts/website"},
{"website in capitals scheme", func(in *OrganizationProfileInput) { in.Contacts.Website = "HTTPS://payments.example.com" }, "/contacts/website"},
{"website with credentials", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://user:secret@payments.example.com" }, "/contacts/website"},
{"website with a port", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://payments.example.com:8443" }, "/contacts/website"},
{"website with an IPv4 address", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://10.0.0.5/admin" }, "/contacts/website"},
{"website with an IPv6 address", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://[::1]/" }, "/contacts/website"},
{"website with a short numeric host", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://127.1" }, "/contacts/website"},
{"website with a hexadecimal host", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://0x7f.0x1" }, "/contacts/website"},
{"website without a dot", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://localhost/" }, "/contacts/website"},
{"website with a space", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://payments.example.com/a b" }, "/contacts/website"},
{"website with an empty label", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://payments..example.com" }, "/contacts/website"},
{"website with a hyphen-led label", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://-payments.example.com" }, "/contacts/website"},
{"website with an underscore", func(in *OrganizationProfileInput) { in.Contacts.Website = "https://pay_ments.example.com" }, "/contacts/website"},
{"website over 300 characters", func(in *OrganizationProfileInput) {
in.Contacts.Website = "https://payments.example.com/" + strings.Repeat("a", 300)
}, "/contacts/website"},
{"email without a domain dot", func(in *OrganizationProfileInput) { in.Contacts.Email = "careers@payments" }, "/contacts/email"},
{"email with a display name", func(in *OrganizationProfileInput) { in.Contacts.Email = "HR <careers@payments.example.com>" }, "/contacts/email"},
{"phone without a plus", func(in *OrganizationProfileInput) { in.Contacts.Phone = "74950000000" }, "/contacts/phone"},
{"phone with spaces", func(in *OrganizationProfileInput) { in.Contacts.Phone = "+7 495 000 00 00" }, "/contacts/phone"},
{"phone with a leading zero country code", func(in *OrganizationProfileInput) { in.Contacts.Phone = "+04950000000" }, "/contacts/phone"},
{"telegram without an at sign", func(in *OrganizationProfileInput) { in.Contacts.Telegram = "payments_careers" }, "/contacts/telegram"},
{"telegram that is too short", func(in *OrganizationProfileInput) { in.Contacts.Telegram = "@abc" }, "/contacts/telegram"},
{"eleven representatives", func(in *OrganizationProfileInput) {
in.Representatives = make([]OrganizationRepresentativeInput, maxOrganizationRepresentatives+1)
for index := range in.Representatives {
in.Representatives[index] = OrganizationRepresentativeInput{Name: "Имя", JobTitle: "Должность"}
}
}, "/representatives"},
{"representative with an empty name", func(in *OrganizationProfileInput) {
in.Representatives = []OrganizationRepresentativeInput{{Name: "Анна", JobTitle: "HR"}, {Name: "", JobTitle: "HR"}}
}, "/representatives/1/name"},
{"representative with a padded job title", func(in *OrganizationProfileInput) {
in.Representatives = []OrganizationRepresentativeInput{{Name: "Анна", JobTitle: " HR"}}
}, "/representatives/0/job_title"},
} {
t.Run(test.name, func(t *testing.T) {
input := completeOrganizationProfileInput()
test.change(&input)
_, err := NewOrganizationProfile(input)
if !errors.Is(err, ErrInvalidOrganization) {
t.Fatalf("NewOrganizationProfile() error = %v, want ErrInvalidOrganization", err)
}
var fieldError *OrganizationFieldError
if !errors.As(err, &fieldError) || fieldError.Pointer != test.pointer {
t.Fatalf("NewOrganizationProfile() error = %v, want the pointer %s", err, test.pointer)
}
})
}
}
func TestOrganizationFieldErrorDoesNotQuoteTheSubmittedValue(t *testing.T) {
const secret = "Конфиденциальная Фамилия"
input := completeOrganizationProfileInput()
input.Representatives = []OrganizationRepresentativeInput{{Name: secret, JobTitle: " " + secret}}
_, err := NewOrganizationProfile(input)
if err == nil || strings.Contains(err.Error(), secret) {
t.Fatalf("NewOrganizationProfile() error = %v, want an error without the submitted value", err)
}
}
func TestNewOrganizationProfileAcceptsInternationalizedAndPathWebsites(t *testing.T) {
for _, website := range []string{
"https://example.com",
"https://пример.рф/vacancies",
"https://xn--e1afmkfd.xn--p1ai",
"https://careers.example.co.uk/a/b?c=d#e",
} {
input := OrganizationProfileInput{Name: "A", Contacts: OrganizationContactsInput{Website: website}}
if _, err := NewOrganizationProfile(input); err != nil {
t.Fatalf("NewOrganizationProfile(%q) error = %v, want it accepted", website, err)
}
}
}
func TestOrganizationProfileCopiesItsRepresentatives(t *testing.T) {
profile := mustOrganizationProfile(t, completeOrganizationProfileInput())
representatives := profile.Representatives()
representatives[0] = OrganizationRepresentative{}
if profile.Representatives()[0].Name() != "Анна Тестова" {
t.Fatal("changing the returned slice changed the profile")
}
}
func TestOrganizationProfileEqualTellsAChangeFromNoChange(t *testing.T) {
base := completeOrganizationProfileInput()
profile := mustOrganizationProfile(t, base)
if !profile.Equal(mustOrganizationProfile(t, base)) {
t.Fatal("equal inputs give unequal profiles")
}
for name, change := range map[string]func(*OrganizationProfileInput){
"name": func(in *OrganizationProfileInput) { in.Name = "Другое имя" },
"description": func(in *OrganizationProfileInput) { in.Description = "" },
"contact": func(in *OrganizationProfileInput) { in.Contacts.Phone = "" },
"representative": func(in *OrganizationProfileInput) { in.Representatives[0].JobTitle = "Директор" },
"list length": func(in *OrganizationProfileInput) { in.Representatives = nil },
} {
input := base
input.Representatives = append([]OrganizationRepresentativeInput(nil), base.Representatives...)
change(&input)
if profile.Equal(mustOrganizationProfile(t, input)) {
t.Fatalf("a changed %s still compares equal", name)
}
}
}
func TestNewOrganizationStartsAtE0WhateverTheProfileLooksLike(t *testing.T) {
profile := mustOrganizationProfile(t, completeOrganizationProfileInput())
organization, err := NewOrganization(profile, organizationTestTime)
if err != nil {
t.Fatalf("NewOrganization() error = %v", err)
}
verification := organization.Verification()
if verification.Level() != OrganizationVerificationE0 || verification.Basis() != OrganizationBasisConfirmedEmail ||
!verification.ChangedAt().Equal(organizationTestTime) {
t.Fatalf("verification = %s %s %s, want e0 on the confirmed email at the creation time",
verification.Level(), verification.Basis(), verification.ChangedAt())
}
if organization.Version() != 1 || organization.ID().Version() != 7 || !organization.CreatedAt().Equal(organizationTestTime) ||
!organization.UpdatedAt().Equal(organizationTestTime) {
t.Fatalf("organization = %v, want version 1, a UUIDv7, and the creation time", organization)
}
if _, err := NewOrganization(OrganizationProfile{}, organizationTestTime); !errors.Is(err, ErrInvalidOrganization) {
t.Fatalf("NewOrganization(zero profile) error = %v, want ErrInvalidOrganization", err)
}
if _, err := NewOrganization(profile, time.Time{}); !errors.Is(err, ErrInvalidOrganization) {
t.Fatalf("NewOrganization(zero time) error = %v, want ErrInvalidOrganization", err)
}
}
func TestApplyProfileKeepsTheVerificationVersionAndIdentity(t *testing.T) {
organization, err := NewOrganization(mustOrganizationProfile(t, OrganizationProfileInput{Name: "Старое имя"}), organizationTestTime)
if err != nil {
t.Fatalf("NewOrganization() error = %v", err)
}
later := organizationTestTime.Add(time.Hour)
updated, err := organization.ApplyProfile(mustOrganizationProfile(t, completeOrganizationProfileInput()), later)
if err != nil {
t.Fatalf("ApplyProfile() error = %v", err)
}
if updated.ID() != organization.ID() || updated.Version() != organization.Version() || updated.Verification() != organization.Verification() ||
!updated.CreatedAt().Equal(organizationTestTime) || !updated.UpdatedAt().Equal(later) {
t.Fatalf("updated = %v, want the same identity, version, and verification and the new update time", updated)
}
if updated.Profile().Name() != "ООО Пример Платежи" || organization.Profile().Name() != "Старое имя" {
t.Fatal("ApplyProfile changed the receiver or did not apply the profile")
}
// Clock skew between instances never moves the update time backwards.
skewed, err := updated.ApplyProfile(updated.Profile(), organizationTestTime)
if err != nil || !skewed.UpdatedAt().Equal(later) {
t.Fatalf("ApplyProfile(earlier time) = %v, %v, want the last update time kept", skewed.UpdatedAt(), err)
}
if _, err := organization.ApplyProfile(OrganizationProfile{}, later); !errors.Is(err, ErrInvalidOrganization) {
t.Fatalf("ApplyProfile(zero profile) error = %v, want ErrInvalidOrganization", err)
}
if _, err := (Organization{}).ApplyProfile(updated.Profile(), later); !errors.Is(err, ErrInvalidOrganization) {
t.Fatalf("ApplyProfile on a zero organization error = %v, want ErrInvalidOrganization", err)
}
}
func TestRestoreOrganizationVerificationAllowsOnlyTheBasesOfALevel(t *testing.T) {
for _, test := range []struct {
level, basis string
ok bool
}{
{"e0", "confirmed_email", true},
{"e1", "corporate_domain", true},
{"e2", "requisites_and_authority", true},
{"e3", "manual_review", true},
{"e3", "partner_status", true},
{"e0", "corporate_domain", false},
{"e1", "confirmed_email", false},
{"e2", "manual_review", false},
{"e4", "manual_review", false},
{"", "", false},
} {
_, err := RestoreOrganizationVerification(test.level, test.basis, organizationTestTime)
if (err == nil) != test.ok || (err != nil && !errors.Is(err, ErrInvalidOrganization)) {
t.Fatalf("RestoreOrganizationVerification(%q, %q) error = %v, want ok = %v", test.level, test.basis, err, test.ok)
}
}
if _, err := RestoreOrganizationVerification("e0", "confirmed_email", time.Time{}); !errors.Is(err, ErrInvalidOrganization) {
t.Fatalf("RestoreOrganizationVerification(zero time) error = %v, want ErrInvalidOrganization", err)
}
}
func TestVerificationLevelMapsToTheQuotaTiersOfThePolicy(t *testing.T) {
for level, want := range map[OrganizationVerificationLevel]OrganizationTier{
OrganizationVerificationE0: OrganizationTierE0,
OrganizationVerificationE1: OrganizationTierE1,
OrganizationVerificationE2: OrganizationTierE2,
} {
if tier, ok := level.QuotaTier(); !ok || tier != want {
t.Fatalf("%s.QuotaTier() = %q, %v, want %q", level, tier, ok, want)
}
}
if _, ok := OrganizationVerificationE3.QuotaTier(); ok {
t.Fatal("e3 has a quota tier, but the PRD gives it a separate policy")
}
}
func TestRestoreOrganizationRejectsARowChangedOutsideTheApplication(t *testing.T) {
valid := func() StoredOrganization {
return StoredOrganization{
ID: uuid.New(), Name: "ООО Пример", Version: 1,
VerificationLevel: "e0", VerificationBasis: "confirmed_email", VerificationChangedAt: organizationTestTime,
CreatedAt: organizationTestTime, UpdatedAt: organizationTestTime,
}
}
if _, err := RestoreOrganization(valid()); err != nil {
t.Fatalf("RestoreOrganization(valid) error = %v", err)
}
for name, change := range map[string]func(*StoredOrganization){
"nil ID": func(s *StoredOrganization) { s.ID = uuid.Nil },
"empty name": func(s *StoredOrganization) { s.Name = "" },
"version zero": func(s *StoredOrganization) { s.Version = 0 },
"unknown level": func(s *StoredOrganization) { s.VerificationLevel = "e9" },
"basis of another level": func(s *StoredOrganization) { s.VerificationBasis = "manual_review" },
"update before creation": func(s *StoredOrganization) { s.UpdatedAt = organizationTestTime.Add(-time.Second) },
"invalid website": func(s *StoredOrganization) { s.Website = "http://example.com" },
"too many representative": func(s *StoredOrganization) { s.Representatives = make([]StoredRepresentative, 11) },
} {
stored := valid()
change(&stored)
if _, err := RestoreOrganization(stored); !errors.Is(err, ErrInvalidOrganization) {
t.Fatalf("RestoreOrganization(%s) error = %v, want ErrInvalidOrganization", name, err)
}
}
}
func TestCandidateCardHoldsTheProfileAndTheLevelOnly(t *testing.T) {
organization, err := NewOrganization(mustOrganizationProfile(t, completeOrganizationProfileInput()), organizationTestTime)
if err != nil {
t.Fatalf("NewOrganization() error = %v", err)
}
card := organization.CandidateCard()
if card.ID() != organization.ID() || !card.Profile().Equal(organization.Profile()) || card.VerificationLevel() != OrganizationVerificationE0 {
t.Fatalf("card = %+v, want the id, the profile, and the level of the organization", card)
}
}
func TestRepresentativesAndOrganizationsAreRedactedInLogsAndFormatting(t *testing.T) {
const name = "Конфиденциальная Фамилия"
profile := mustOrganizationProfile(t, OrganizationProfileInput{
Name: "ООО Пример",
Representatives: []OrganizationRepresentativeInput{{Name: name, JobTitle: "Руководитель"}},
})
organization, err := NewOrganization(profile, organizationTestTime)
if err != nil {
t.Fatalf("NewOrganization() error = %v", err)
}
representative := profile.Representatives()[0]
type enclosing struct {
Representative OrganizationRepresentative
Hidden []OrganizationRepresentative
}
wrapped := enclosing{Representative: representative, Hidden: profile.Representatives()}
var logs bytes.Buffer
for _, logger := range []*slog.Logger{slog.New(slog.NewTextHandler(&logs, nil)), slog.New(slog.NewJSONHandler(&logs, nil))} {
logger.Info("organization", "representative", representative, "organization", organization)
}
output := fmt.Sprintf("%v %+v %#v %s %v %+v", representative, representative, representative, representative, wrapped, wrapped) + logs.String()
for _, secret := range []string{name, "Руководитель"} {
if strings.Contains(output, secret) {
t.Fatalf("printing a representative exposes %q: %s", secret, output)
}
}
if !strings.Contains(logs.String(), `"verification_level":"e0"`) {
t.Fatalf("logs = %s, want the organization logged by id, version, and level", logs.String())
}
}
func TestRestoreOrganizationSummaryValidatesTheNameAndTheLevel(t *testing.T) {
id := uuid.New()
if summary, err := RestoreOrganizationSummary(id, "ООО Пример", "e1"); err != nil || summary.ID() != id ||
summary.Name() != "ООО Пример" || summary.VerificationLevel() != OrganizationVerificationE1 {
t.Fatalf("RestoreOrganizationSummary() = %+v, %v, want the stored values", summary, err)
}
for _, test := range []struct {
id uuid.UUID
name, level string
}{
{uuid.Nil, "ООО", "e0"},
{id, "", "e0"},
{id, " ООО", "e0"},
{id, "ООО", "e5"},
} {
if _, err := RestoreOrganizationSummary(test.id, test.name, test.level); !errors.Is(err, ErrInvalidOrganization) {
t.Fatalf("RestoreOrganizationSummary(%v, %q, %q) error = %v, want ErrInvalidOrganization", test.id, test.name, test.level, err)
}
}
}