Skip to content

Commit

Permalink
fixed all the tests i could
Browse files Browse the repository at this point in the history
  • Loading branch information
garrettladley committed Feb 4, 2024
1 parent fc14ad0 commit 2ab675b
Show file tree
Hide file tree
Showing 16 changed files with 288 additions and 138 deletions.
20 changes: 10 additions & 10 deletions backend/src/controllers/club.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,58 +17,58 @@ func NewClubController(clubService services.ClubServiceInterface) *ClubControlle
return &ClubController{clubService: clubService}
}

func (l *ClubController) GetAllClubs(c *fiber.Ctx) error {
func (cl *ClubController) GetAllClubs(c *fiber.Ctx) error {
defaultLimit := 10
defaultPage := 1

clubs, err := l.clubService.GetClubs(c.Query("limit", strconv.Itoa(defaultLimit)), c.Query("page", strconv.Itoa(defaultPage)))
clubs, err := cl.clubService.GetClubs(c.Query("limit", strconv.Itoa(defaultLimit)), c.Query("page", strconv.Itoa(defaultPage)))
if err != nil {
return err.FiberError(c)
}

return c.Status(fiber.StatusOK).JSON(clubs)
}

func (l *ClubController) CreateClub(c *fiber.Ctx) error {
func (cl *ClubController) CreateClub(c *fiber.Ctx) error {
var clubBody models.CreateClubRequestBody
if err := c.BodyParser(&clubBody); err != nil {
return errors.FailedToParseRequestBody.FiberError(c)
}

club, err := l.clubService.CreateClub(clubBody)
club, err := cl.clubService.CreateClub(clubBody)
if err != nil {
return err.FiberError(c)
}

return c.Status(fiber.StatusCreated).JSON(club)
}

func (l *ClubController) GetClub(c *fiber.Ctx) error {
club, err := l.clubService.GetClub(c.Params("id"))
func (cl *ClubController) GetClub(c *fiber.Ctx) error {
club, err := cl.clubService.GetClub(c.Params("id"))
if err != nil {
return err.FiberError(c)
}

return c.Status(fiber.StatusOK).JSON(club)
}

func (l *ClubController) UpdateClub(c *fiber.Ctx) error {
func (cl *ClubController) UpdateClub(c *fiber.Ctx) error {
var clubBody models.UpdateClubRequestBody

if err := c.BodyParser(&clubBody); err != nil {
return errors.FailedToParseRequestBody.FiberError(c)
}

updatedClub, err := l.clubService.UpdateClub(c.Params("id"), clubBody)
updatedClub, err := cl.clubService.UpdateClub(c.Params("id"), clubBody)
if err != nil {
return err.FiberError(c)
}

return c.Status(fiber.StatusOK).JSON(updatedClub)
}

func (l *ClubController) DeleteClub(c *fiber.Ctx) error {
err := l.clubService.DeleteClub(c.Params("id"))
func (cl *ClubController) DeleteClub(c *fiber.Ctx) error {
err := cl.clubService.DeleteClub(c.Params("id"))
if err != nil {
return err.FiberError(c)
}
Expand Down
26 changes: 21 additions & 5 deletions backend/src/database/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
)

func ConfigureDB(settings config.Settings) (*gorm.DB, error) {
db, err := EstablishConn(settings.Database.WithDb())
db, err := EstablishConn(settings.Database.WithDb(), WithLoggerInfo())
if err != nil {
return nil, err
}
Expand All @@ -22,12 +22,26 @@ func ConfigureDB(settings config.Settings) (*gorm.DB, error) {
return db, nil
}

func EstablishConn(dsn string) (*gorm.DB, error) {
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
type OptionalFunc func(gorm.Config) gorm.Config

func WithLoggerInfo() OptionalFunc {
return func(gormConfig gorm.Config) gorm.Config {
gormConfig.Logger = logger.Default.LogMode(logger.Info)
return gormConfig
}
}

func EstablishConn(dsn string, opts ...OptionalFunc) (*gorm.DB, error) {
rootConfig := gorm.Config{
SkipDefaultTransaction: true,
TranslateError: true,
})
}

for _, opt := range opts {
rootConfig = opt(rootConfig)
}

db, err := gorm.Open(postgres.Open(dsn), &rootConfig)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -106,6 +120,8 @@ func createSuperUser(settings config.Settings, db *gorm.DB) error {
return err
}

SuperUserUUID = superUser.ID

superClub := SuperClub()

if err := tx.Create(&superClub).Error; err != nil {
Expand Down
3 changes: 3 additions & 0 deletions backend/src/database/super.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ import (
"github.com/GenerateNU/sac/backend/src/config"
"github.com/GenerateNU/sac/backend/src/errors"
"github.com/GenerateNU/sac/backend/src/models"
"github.com/google/uuid"
)

var SuperUserUUID uuid.UUID

func SuperUser(superUserSettings config.SuperUserSettings) (*models.User, *errors.Error) {
passwordHash, err := auth.ComputePasswordHash(superUserSettings.Password)
if err != nil {
Expand Down
3 changes: 1 addition & 2 deletions backend/src/models/club.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ type Club struct {
Parent *uuid.UUID `gorm:"foreignKey:Parent" json:"-" validate:"uuid4"`
Tag []Tag `gorm:"many2many:club_tags;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"-" validate:"-"`
// User
Admin []User `gorm:"many2many:user_club_admins;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"-" validate:"required"`
Member []User `gorm:"many2many:user_club_members;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"-" validate:"required"`
Follower []User `gorm:"many2many:user_club_followers;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"-" validate:"-"`
IntendedApplicant []User `gorm:"many2many:user_club_intended_applicants;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"-" validate:"-"`
Expand All @@ -56,7 +57,6 @@ type CreateClubRequestBody struct {
Name string `json:"name" validate:"required,max=255"`
Preview string `json:"preview" validate:"required,max=255"`
Description string `json:"description" validate:"required,http_url,mongo_url,max=255"` // MongoDB URL
NumMembers int `json:"num_members" validate:"required,min=1"`
IsRecruiting bool `json:"is_recruiting" validate:"required"`
RecruitmentCycle RecruitmentCycle `gorm:"type:varchar(255);default:always" json:"recruitment_cycle" validate:"required,max=255,oneof=fall spring fallSpring always"`
RecruitmentType RecruitmentType `gorm:"type:varchar(255);default:unrestricted" json:"recruitment_type" validate:"required,max=255,oneof=unrestricted tryout application"`
Expand All @@ -68,7 +68,6 @@ type UpdateClubRequestBody struct {
Name string `json:"name" validate:"omitempty,max=255"`
Preview string `json:"preview" validate:"omitempty,max=255"`
Description string `json:"description" validate:"omitempty,http_url,mongo_url,max=255"` // MongoDB URL
NumMembers int `json:"num_members" validate:"omitempty,min=1"`
IsRecruiting bool `json:"is_recruiting" validate:"omitempty"`
RecruitmentCycle RecruitmentCycle `gorm:"type:varchar(255);default:always" json:"recruitment_cycle" validate:"required,max=255,oneof=fall spring fallSpring always"`
RecruitmentType RecruitmentType `gorm:"type:varchar(255);default:unrestricted" json:"recruitment_type" validate:"required,max=255,oneof=unrestricted tryout application"`
Expand Down
1 change: 1 addition & 0 deletions backend/src/models/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ type User struct {
Year Year `gorm:"type:smallint" json:"year" validate:"required,min=1,max=6"`

Tag []Tag `gorm:"many2many:user_tags;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"-" validate:"-"`
Admin []Club `gorm:"many2many:user_club_admins;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"-" validate:"-"`
Member []Club `gorm:"many2many:user_club_members;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"-" validate:"-"`
Follower []Club `gorm:"many2many:user_club_followers;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"-" validate:"-"`
IntendedApplicant []Club `gorm:"many2many:user_club_intended_applicants;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"-" validate:"-"`
Expand Down
9 changes: 9 additions & 0 deletions backend/src/transactions/category_tag.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,15 @@ import (
)

func GetTagsByCategory(db *gorm.DB, categoryID uuid.UUID, limit int, offset int) ([]models.Tag, *errors.Error) {
var category models.Category

if err := db.Where("id = ?", categoryID).First(&category).Error; err != nil {
if stdliberrors.Is(err, gorm.ErrRecordNotFound) {
return nil, &errors.CategoryNotFound
}
return nil, &errors.FailedToGetCategory
}

var tags []models.Tag
if err := db.Where("category_id = ?", categoryID).Limit(limit).Offset(offset).Find(&tags).Error; err != nil {
return nil, &errors.FailedToGetTags
Expand Down
15 changes: 9 additions & 6 deletions backend/tests/api/category_tag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ func TestGetCategoryTagsWorks(t *testing.T) {
h.TestRequest{
Method: fiber.MethodGet,
Path: fmt.Sprintf("/api/v1/categories/%s/tags", categoryUUID),
Role: &models.Super,
}.TestOnStatusAndDB(t, &appAssert,
h.TesterWithStatus{
Status: fiber.StatusOK,
Expand All @@ -78,6 +79,7 @@ func TestGetCategoryTagsFailsCategoryBadRequest(t *testing.T) {
h.TestRequest{
Method: fiber.MethodGet,
Path: fmt.Sprintf("/api/v1/categories/%s/tags", badRequest),
Role: &models.Super,
}.TestOnError(t, &appAssert, errors.FailedToValidateID)
}

Expand All @@ -92,17 +94,13 @@ func TestGetCategoryTagsFailsCategoryNotFound(t *testing.T) {
h.TestRequest{
Method: fiber.MethodGet,
Path: fmt.Sprintf("/api/v1/categories/%s/tags", uuid),
Role: &models.Super,
}.TestOnErrorAndDB(t, &appAssert, h.ErrorWithTester{
Error: errors.CategoryNotFound,
Tester: func(app h.TestApp, assert *assert.A, resp *http.Response) {
var category models.Category
err := app.Conn.Where("id = ?", uuid).First(&category).Error
assert.Error(err)

var respBody []map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&respBody)
assert.NilError(err)
assert.Equal(0, len(respBody))
assert.Assert(err != nil)
},
}).Close()
}
Expand All @@ -113,6 +111,7 @@ func TestGetCategoryTagWorks(t *testing.T) {
h.TestRequest{
Method: fiber.MethodGet,
Path: fmt.Sprintf("/api/v1/categories/%s/tags/%s", categoryUUID, tagUUID),
Role: &models.Super,
}.TestOnStatusAndDB(t, &existingAppAssert,
h.TesterWithStatus{
Status: fiber.StatusOK,
Expand All @@ -138,6 +137,7 @@ func TestGetCategoryTagFailsCategoryBadRequest(t *testing.T) {
h.TestRequest{
Method: fiber.MethodGet,
Path: fmt.Sprintf("/api/v1/categories/%s/tags/%s", badRequest, tagUUID),
Role: &models.Super,
}.TestOnError(t, &appAssert, errors.FailedToValidateID)
}

Expand All @@ -159,6 +159,7 @@ func TestGetCategoryTagFailsTagBadRequest(t *testing.T) {
h.TestRequest{
Method: fiber.MethodGet,
Path: fmt.Sprintf("/api/v1/categories/%s/tags/%s", categoryUUID, badRequest),
Role: &models.Super,
}.TestOnError(t, &appAssert, errors.FailedToValidateID)
}

Expand All @@ -171,6 +172,7 @@ func TestGetCategoryTagFailsCategoryNotFound(t *testing.T) {
h.TestRequest{
Method: fiber.MethodGet,
Path: fmt.Sprintf("/api/v1/categories/%s/tags/%s", uuid.New(), tagUUID),
Role: &models.Super,
}.TestOnError(t, &appAssert, errors.TagNotFound).Close()
}

Expand All @@ -180,5 +182,6 @@ func TestGetCategoryTagFailsTagNotFound(t *testing.T) {
h.TestRequest{
Method: fiber.MethodGet,
Path: fmt.Sprintf("/api/v1/categories/%s/tags/%s", categoryUUID, uuid.New()),
Role: &models.Super,
}.TestOnError(t, &appAssert, errors.TagNotFound).Close()
}
23 changes: 19 additions & 4 deletions backend/tests/api/category_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ func CreateSampleCategory(t *testing.T, existingAppAssert *h.ExistingAppAssert)
Method: fiber.MethodPost,
Path: "/api/v1/categories/",
Body: SampleCategoryFactory(),
Role: &models.Super,
}.TestOnStatusAndDB(t, existingAppAssert,
h.TesterWithStatus{
Status: fiber.StatusCreated,
Expand Down Expand Up @@ -107,6 +108,7 @@ func TestCreateCategoryIgnoresid(t *testing.T) {
"id": 12,
"name": "Foo",
},
Role: &models.Super,
}.TestOnStatusAndDB(t, nil,
h.TesterWithStatus{
Status: fiber.StatusCreated,
Expand Down Expand Up @@ -142,6 +144,7 @@ func TestCreateCategoryFailsIfNameIsNotString(t *testing.T) {
Body: &map[string]interface{}{
"name": 1231,
},
Role: &models.Super,
}.TestOnErrorAndDB(t, nil,
h.ErrorWithTester{
Error: errors.FailedToParseRequestBody,
Expand All @@ -155,6 +158,7 @@ func TestCreateCategoryFailsIfNameIsMissing(t *testing.T) {
Method: fiber.MethodPost,
Path: "/api/v1/categories/",
Body: &map[string]interface{}{},
Role: &models.Super,
}.TestOnErrorAndDB(t, nil,
h.ErrorWithTester{
Error: errors.FailedToValidateCategory,
Expand All @@ -178,6 +182,7 @@ func TestCreateCategoryFailsIfCategoryWithThatNameAlreadyExists(t *testing.T) {
Method: fiber.MethodPost,
Path: "/api/v1/categories/",
Body: &modifiedSampleCategoryBody,
Role: &models.Super,
}.TestOnErrorAndDB(t, &existingAppAssert,
h.ErrorWithTester{
Error: errors.CategoryAlreadyExists,
Expand All @@ -193,8 +198,9 @@ func TestGetCategoryWorks(t *testing.T) {
existingAppAssert, uuid := CreateSampleCategory(t, nil)

h.TestRequest{
Method: "GET",
Method: fiber.MethodGet,
Path: fmt.Sprintf("/api/v1/categories/%s", uuid),
Role: &models.Super,
}.TestOnStatusAndDB(t, &existingAppAssert,
h.TesterWithStatus{
Status: fiber.StatusOK,
Expand All @@ -216,25 +222,28 @@ func TestGetCategoryFailsBadRequest(t *testing.T) {

for _, badRequest := range badRequests {
h.TestRequest{
Method: "GET",
Method: fiber.MethodGet,
Path: fmt.Sprintf("/api/v1/categories/%s", badRequest),
Role: &models.Super,
}.TestOnError(t, nil, errors.FailedToValidateID).Close()
}
}

func TestGetCategoryFailsNotFound(t *testing.T) {
h.TestRequest{
Method: "GET",
Method: fiber.MethodGet,
Path: fmt.Sprintf("/api/v1/categories/%s", uuid.New()),
Role: &models.Super,
}.TestOnError(t, nil, errors.CategoryNotFound).Close()
}

func TestGetCategoriesWorks(t *testing.T) {
existingAppAssert, _ := CreateSampleCategory(t, nil)

h.TestRequest{
Method: "GET",
Method: fiber.MethodGet,
Path: "/api/v1/categories/",
Role: &models.Super,
}.TestOnStatusAndDB(t, &existingAppAssert,
h.TesterWithStatus{
Status: fiber.StatusOK,
Expand Down Expand Up @@ -304,6 +313,7 @@ func TestUpdateCategoryWorks(t *testing.T) {
Method: fiber.MethodPatch,
Path: fmt.Sprintf("/api/v1/categories/%s", uuid),
Body: &category,
Role: &models.Super,
}.TestOnStatusAndDB(t, &existingAppAssert,
h.TesterWithStatus{
Status: fiber.StatusOK,
Expand All @@ -326,6 +336,7 @@ func TestUpdateCategoryWorksWithSameDetails(t *testing.T) {
Method: fiber.MethodPatch,
Path: fmt.Sprintf("/api/v1/categories/%s", uuid),
Body: &category,
Role: &models.Super,
}.TestOnStatusAndDB(t, &existingAppAssert,
h.TesterWithStatus{
Status: fiber.StatusOK,
Expand All @@ -348,6 +359,7 @@ func TestUpdateCategoryFailsBadRequest(t *testing.T) {
Method: fiber.MethodPatch,
Path: fmt.Sprintf("/api/v1/categories/%s", badRequest),
Body: SampleCategoryFactory(),
Role: &models.Super,
}.TestOnError(t, nil, errors.FailedToValidateID).Close()
}
}
Expand All @@ -358,6 +370,7 @@ func TestDeleteCategoryWorks(t *testing.T) {
h.TestRequest{
Method: fiber.MethodDelete,
Path: fmt.Sprintf("/api/v1/categories/%s", uuid),
Role: &models.Super,
}.TestOnStatusAndDB(t, &existingAppAssert,
h.TesterWithStatus{
Status: fiber.StatusNoContent,
Expand All @@ -381,6 +394,7 @@ func TestDeleteCategoryFailsBadRequest(t *testing.T) {
h.TestRequest{
Method: fiber.MethodDelete,
Path: fmt.Sprintf("/api/v1/categories/%s", badRequest),
Role: &models.Super,
}.TestOnErrorAndDB(t, &existingAppAssert,
h.ErrorWithTester{
Error: errors.FailedToValidateID,
Expand All @@ -398,6 +412,7 @@ func TestDeleteCategoryFailsNotFound(t *testing.T) {
h.TestRequest{
Method: fiber.MethodDelete,
Path: fmt.Sprintf("/api/v1/categories/%s", uuid.New()),
Role: &models.Super,
}.TestOnErrorAndDB(t, &existingAppAssert,
h.ErrorWithTester{
Error: errors.CategoryNotFound,
Expand Down
Loading

0 comments on commit 2ab675b

Please sign in to comment.