RezinaLMS-BackEnd/internal/web_server/subscription_access_test.go

55 lines
1.7 KiB
Go

package httpserver
import (
"Rezina-Backend/internal/domain"
"Rezina-Backend/internal/ports"
"Rezina-Backend/internal/services/subscriptions"
"context"
"github.com/gofiber/fiber/v2"
"net/http/httptest"
"testing"
)
type accessSubscriptionStore struct {
ports.SubscriptionStore
active bool
calls int
}
func (s *accessSubscriptionStore) HasActiveSubscriptionByCategory(_ context.Context, userID int64, category string) (bool, error) {
s.calls++
if userID != 42 || category != "EDUCATION" {
panic("incorrect subscription scope")
}
return s.active, nil
}
func TestLearningSubscriptionGate(t *testing.T) {
for _, tc := range []struct {
name string
role domain.Role
active bool
status, calls int
}{
{"unsubscribed GET", domain.RoleStudent, false, 403, 1},
{"subscribed GET", domain.RoleStudent, true, 204, 1},
{"admin", domain.RoleAdmin, false, 204, 0},
{"open learner", domain.RoleOpenLearner, false, 204, 0},
} {
t.Run(tc.name, func(t *testing.T) {
store := &accessSubscriptionStore{active: tc.active}
app := &App{subscriptionsSvc: subscriptions.NewService(store, nil)}
server := fiber.New()
server.Get("/exam-prep/practices", func(c *fiber.Ctx) error { c.Locals("role", tc.role); c.Locals("user_id", int64(42)); return c.Next() }, app.RequireExamPrepSubscription(), func(c *fiber.Ctx) error { return c.SendStatus(204) })
response, err := server.Test(httptest.NewRequest("GET", "/exam-prep/practices", nil))
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
if response.StatusCode != tc.status || store.calls != tc.calls {
t.Fatalf("status=%d calls=%d, want status=%d calls=%d", response.StatusCode, store.calls, tc.status, tc.calls)
}
})
}
}