Files
lincodex/backend/internal/adapter/primary/http/v1/invitation_test.go
T

194 lines
8.6 KiB
Go

package v1
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
invitationusecase "lincodex/backend/internal/usecase/invitation"
)
func invitationTestTerms() api.InvitationTerms {
provided := api.NewInvitationPackageItemProvidedInvitationPackageItem(api.InvitationPackageItemProvided{
Status: api.InvitationPackageItemProvidedStatusProvided, Description: "Quarterly bonus",
})
notProvided := api.NewInvitationPackageItemNotProvidedInvitationPackageItem(api.InvitationPackageItemNotProvided{
Status: api.InvitationPackageItemNotProvidedStatusNotProvided,
})
terms := api.InvitationTerms{
RoleTitle: "Middle Go developer", Specialization: "backend", Grade: "middle", OfferType: api.InvitationOfferTypeFullTime,
Tasks: []api.NeedTaskText{"Build the payout service"}, Team: "Six engineers", TechStack: []api.SkillName{"Go"},
WorkFormats: []api.WorkFormat{api.WorkFormatRemote},
CommunicationMethod: api.InvitationCommunicationMethod{Channel: api.InvitationCommunicationChannelEmail},
Salary: api.SalaryRange{SalaryFrom: 100000, SalaryTo: 140000, Currency: api.CurrencyCodeRUB, Period: api.SalaryPeriodMonth, TaxBasis: api.SalaryTaxBasisNet},
Package: api.InvitationPackage{Bonus: provided, Equipment: notProvided, Training: notProvided, HealthInsurance: notProvided},
}
terms.Location.SetToNull()
terms.CommunicationMethod.Details.SetToNull()
return terms
}
// The request terms and the response terms are the same value: a response can
// be sent back unchanged, and a nullable term keeps its meaning both ways.
func TestInvitationTermsSurviveTheRequestResponseRoundTrip(t *testing.T) {
request := invitationTestTerms()
converted := invitationTermsFromRequest(request)
if err := converted.Validate(); err != nil {
t.Fatalf("converted terms are invalid: %v", err)
}
if converted.Location != nil || converted.CommunicationMethod.Details != nil {
t.Fatalf("null terms were mapped to values: %+v", converted)
}
if converted.Package.Bonus.Status != domain.InvitationPackageProvided || converted.Package.Bonus.Description == nil ||
converted.Package.Equipment.Status != domain.InvitationPackageNotProvided || converted.Package.Equipment.Description != nil {
t.Fatalf("package mapped wrongly: %+v", converted.Package)
}
encodedRequest, err := json.Marshal(request)
if err != nil {
t.Fatalf("marshal request terms: %v", err)
}
encodedResponse, err := json.Marshal(invitationTermsResponse(converted))
if err != nil {
t.Fatalf("marshal response terms: %v", err)
}
if string(encodedRequest) != string(encodedResponse) {
t.Fatalf("response terms differ from the request terms:\n%s\n%s", encodedRequest, encodedResponse)
}
}
func TestInvitationResponseNeverCarriesACandidateIdentifierOrAContact(t *testing.T) {
candidateID := uuid.Must(uuid.NewV7())
organizationID := uuid.Must(uuid.NewV7())
policyID, err := domain.NewPolicyVersionID()
if err != nil {
t.Fatalf("NewPolicyVersionID() error = %v", err)
}
now := time.Date(2026, time.October, 9, 10, 0, 0, 0, time.UTC)
draft, err := domain.NewInvitationDraft(domain.NewInvitationDraftInput{
ID: uuid.Must(uuid.NewV7()), OrganizationID: organizationID, CandidateID: candidateID, ActorID: uuid.Must(uuid.NewV7()),
PolicyVersionID: policyID, At: now,
Content: domain.InvitationDraftContent{ResponsePeriod: 7, Terms: invitationTermsFromRequest(invitationTestTerms())},
})
if err != nil {
t.Fatalf("NewInvitationDraft() error = %v", err)
}
view := domain.OrganizationInvitationView{
InvitationSnapshot: draft.Snapshot(), CandidateHandle: "cv1_" + strings.Repeat("A", 43),
SalaryFit: domain.InvitationSalaryNotAvailable, ContactAccess: domain.InvitationContactAccessNone,
}
for name, response := range map[string]any{
"invitation": organizationInvitationResponse(view),
"summary": organizationInvitationSummary(view),
} {
encoded, err := json.Marshal(response)
if err != nil {
t.Fatalf("marshal %s: %v", name, err)
}
text := string(encoded)
if strings.Contains(text, candidateID.String()) {
t.Errorf("%s carries the candidate identifier: %s", name, text)
}
for _, field := range []string{"email", "phone", "telegram", "full_name", "salary_minimum", "candidate_id"} {
if strings.Contains(text, `"`+field+`":`) {
t.Errorf("%s carries the field %s: %s", name, field, text)
}
}
if !strings.Contains(text, `"candidate_handle":"cv1_`) {
t.Errorf("%s does not name the candidate by the card handle: %s", name, text)
}
}
encoded, _ := json.Marshal(organizationInvitationResponse(view))
for _, want := range []string{`"state":"draft"`, `"version":1`, `"terms_version":1`, `"response_deadline_at":null`, `"salary_fit":"not_available"`, `"contact_access":{"status":"not_granted","fields":[]}`, `"need":null`} {
if !strings.Contains(string(encoded), want) {
t.Errorf("draft response lacks %s: %s", want, encoded)
}
}
}
func TestInvitationFailuresMapToTheContractStatuses(t *testing.T) {
ctx := context.Background()
field := &domain.InvitationFieldError{Pointer: "/terms/salary/salary_to", Reason: "x"}
create := func(err error) any {
response, unexpected := invitationCreateFailure(ctx, err)
if unexpected != nil {
return unexpected
}
return fmt.Sprintf("%T", response)
}
update := func(err error) any {
response, unexpected := invitationUpdateFailure(ctx, err)
if unexpected != nil {
return unexpected
}
return fmt.Sprintf("%T", response)
}
tests := []struct {
name string
err error
wantCreate string
wantUpdate string
}{
{"forbidden", invitationusecase.ErrForbidden, "*api.CreateOrganizationInvitationForbidden", "*api.UpdateOrganizationInvitationForbidden"},
{"not an owner", fmt.Errorf("wrapped: %w", outbound.ErrOrganizationManagerRequired), "*api.CreateOrganizationInvitationForbidden", "*api.UpdateOrganizationInvitationForbidden"},
{"unknown organization", outbound.ErrOrganizationNotFound, "*api.CreateOrganizationInvitationNotFound", "*api.UpdateOrganizationInvitationNotFound"},
{"unknown invitation", outbound.ErrInvitationNotFound, "*api.CreateOrganizationInvitationNotFound", "*api.UpdateOrganizationInvitationNotFound"},
{"field error", fmt.Errorf("wrapped: %w", field), "*api.CreateOrganizationInvitationBadRequest", "*api.UpdateOrganizationInvitationBadRequest"},
{"stale version", domain.ErrInvitationVersionConflict, "", "*api.UpdateOrganizationInvitationPreconditionFailed"},
{"not a draft", domain.ErrInvitationNotDraft, "", "*api.UpdateOrganizationInvitationConflict"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if test.wantCreate != "" {
if got := create(test.err); got != test.wantCreate {
t.Errorf("create failure = %v, want %s", got, test.wantCreate)
}
}
if got := update(test.err); got != test.wantUpdate {
t.Errorf("update failure = %v, want %s", got, test.wantUpdate)
}
})
}
if got := create(invitationusecase.ErrIdempotencyKeyReused); got != "*api.CreateOrganizationInvitationUnprocessableEntity" {
t.Errorf("reused key = %v, want 422", got)
}
// An error without a public meaning is left to the responder, which logs
// it and answers with a fixed 500.
if _, passedOn := create(errors.New("storage failed")).(error); !passedOn {
t.Error("an unknown failure produced a public response instead of reaching the responder")
}
}
func TestInvitationCursorIsBoundToActorAndOrganization(t *testing.T) {
actorID, organizationID := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7())
position := outbound.InvitationListPosition{
CreatedAt: time.Date(2026, time.October, 9, 10, 0, 0, 123456000, time.UTC), InvitationID: uuid.Must(uuid.NewV7()),
}
cursor, err := encodeInvitationCursor(actorID, organizationID, position)
if err != nil {
t.Fatalf("encodeInvitationCursor() error = %v", err)
}
decoded, err := decodeInvitationCursor(cursor, actorID, organizationID)
if err != nil || !decoded.CreatedAt.Equal(position.CreatedAt) || decoded.InvitationID != position.InvitationID {
t.Fatalf("decodeInvitationCursor() = %+v, %v; want the same position", decoded, err)
}
for name, test := range map[string]struct{ actor, organization uuid.UUID }{
"another actor": {uuid.Must(uuid.NewV7()), organizationID}, "another organization": {actorID, uuid.Must(uuid.NewV7())},
} {
if _, err := decodeInvitationCursor(cursor, test.actor, test.organization); err == nil {
t.Errorf("a cursor of %s was accepted", name)
}
}
if _, err := decodeInvitationCursor(cursor+"A", actorID, organizationID); err == nil {
t.Error("a cursor with trailing data was accepted")
}
}