65 lines
2.4 KiB
Go
65 lines
2.4 KiB
Go
package httpserver
|
|
|
|
import (
|
|
"Rezina-Backend/internal/domain"
|
|
"Rezina-Backend/internal/repository"
|
|
"Rezina-Backend/internal/services/examprep"
|
|
"context"
|
|
"github.com/gofiber/fiber/v2"
|
|
"net/http/httptest"
|
|
"testing"
|
|
)
|
|
|
|
type purchaseAccessStore struct {
|
|
*repository.Store
|
|
tier domain.ContentAccessTier
|
|
published bool
|
|
ownedCourse int64
|
|
checkedCourse int64
|
|
}
|
|
|
|
func (s *purchaseAccessStore) CourseContentAccess(context.Context, string, int64) (domain.CourseContentAccess, error) {
|
|
return domain.CourseContentAccess{CourseID: 12, Tier: s.tier, Published: s.published}, nil
|
|
}
|
|
func (s *purchaseAccessStore) HasCoursePurchase(_ context.Context, userID, courseID int64) (bool, error) {
|
|
s.checkedCourse = courseID
|
|
return userID == 42 && courseID == s.ownedCourse, nil
|
|
}
|
|
|
|
func TestCoursePurchaseGate(t *testing.T) {
|
|
for _, tt := range []struct {
|
|
name string
|
|
tier domain.ContentAccessTier
|
|
owned int64
|
|
published bool
|
|
role domain.Role
|
|
status int
|
|
}{
|
|
{"free preview", domain.ContentAccessFree, 0, true, domain.RoleStudent, 204},
|
|
{"unpaid", domain.ContentAccessPremium, 0, true, domain.RoleStudent, 403},
|
|
{"owns course", domain.ContentAccessPremium, 12, true, domain.RoleStudent, 204},
|
|
{"another course purchase", domain.ContentAccessPremium, 99, true, domain.RoleStudent, 403},
|
|
{"hidden content", domain.ContentAccessFree, 12, false, domain.RoleStudent, 404},
|
|
{"staff", domain.ContentAccessPremium, 0, false, domain.RoleAdmin, 204},
|
|
{"open learner", domain.ContentAccessPremium, 0, true, domain.RoleOpenLearner, 204},
|
|
} {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
store := &purchaseAccessStore{tier: tt.tier, published: tt.published, ownedCourse: tt.owned}
|
|
app := &App{examPrepSvc: examprep.NewService(store)}
|
|
server := fiber.New()
|
|
server.Get("/lessons/:id", func(c *fiber.Ctx) error { c.Locals("role", tt.role); c.Locals("user_id", int64(42)); return c.Next() }, app.RequireCoursePurchase(), func(c *fiber.Ctx) error { return c.SendStatus(204) })
|
|
response, err := server.Test(httptest.NewRequest("GET", "/lessons/7", nil))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer response.Body.Close()
|
|
if response.StatusCode != tt.status {
|
|
t.Fatalf("got %d want %d", response.StatusCode, tt.status)
|
|
}
|
|
if tt.tier == domain.ContentAccessFree && store.checkedCourse != 0 {
|
|
t.Fatal("free preview checked purchase")
|
|
}
|
|
})
|
|
}
|
|
}
|