RezinaLMS-BackEnd/internal/services/referrals/service_test.go

88 lines
2.5 KiB
Go

package referrals
import (
dbgen "Rezina-Backend/gen/db"
"Rezina-Backend/internal/domain"
"context"
"errors"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"math"
"testing"
)
type fakeStore struct {
Store
existing string
created string
attempts int
collision bool
count int64
apply dbgen.ApplyReferralCodeParams
}
func (s *fakeStore) GetReferralCode(context.Context, int64) (string, error) {
if s.existing != "" {
return s.existing, nil
}
return "", pgx.ErrNoRows
}
func (s *fakeStore) CreateReferralCode(_ context.Context, p dbgen.CreateReferralCodeParams) (string, error) {
s.attempts++
s.created = p.Code
if s.collision && s.attempts == 1 {
return "", &pgconn.PgError{Code: "23505"}
}
return p.Code, nil
}
func (s *fakeStore) ApplyReferralCode(_ context.Context, p dbgen.ApplyReferralCodeParams) (int64, error) {
s.apply = p
return s.count, nil
}
func TestStableCodeAndCollisionRetry(t *testing.T) {
existing := &fakeStore{existing: "ABCDEF0123456789"}
code, err := NewService(existing).Code(context.Background(), 42)
if err != nil || code != existing.existing || existing.attempts != 0 {
t.Fatalf("existing code: %q %v", code, err)
}
fresh := &fakeStore{collision: true}
code, err = NewService(fresh).Code(context.Background(), 42)
if err != nil || fresh.attempts != 2 {
t.Fatalf("retry: %d %v", fresh.attempts, err)
}
if _, err := domain.NormalizeReferralCode(code); err != nil {
t.Fatal(err)
}
}
func TestApplyValidationAndAttribution(t *testing.T) {
store := &fakeStore{count: 1}
svc := NewService(store)
if err := svc.Apply(context.Background(), 42, " abcdef0123456789 "); err != nil {
t.Fatal(err)
}
if store.apply.Code != "ABCDEF0123456789" || store.apply.ReferredUserID != 42 {
t.Fatalf("wrong attribution: %+v", store.apply)
}
store.count = 0
if err := svc.Apply(context.Background(), 42, "ABCDEF0123456789"); !errors.Is(err, domain.ErrInvalidReferralCode) {
t.Fatalf("ineligible: %v", err)
}
for _, invalid := range []string{"", "short", "ABCDEF012345678!", "?BCDEF0123456789"} {
if err := svc.Apply(context.Background(), 42, invalid); !errors.Is(err, domain.ErrInvalidReferralCode) {
t.Errorf("accepted %q", invalid)
}
}
}
func TestCommissionPercent(t *testing.T) {
for _, v := range []float64{0, 5, 10.25, 100} {
if _, err := CommissionPercent(v); err != nil {
t.Errorf("%v: %v", v, err)
}
}
for _, v := range []float64{-1, 100.01, 1.001, math.NaN(), math.Inf(1)} {
if _, err := CommissionPercent(v); !errors.Is(err, ErrInvalidCommissionPercent) {
t.Errorf("accepted %v", v)
}
}
}