Skip to content

Commit

Permalink
tests: admin users completed
Browse files Browse the repository at this point in the history
  • Loading branch information
kayprogrammer committed Jan 29, 2025
1 parent b3a3c4d commit 32468fe
Show file tree
Hide file tree
Showing 6 changed files with 125 additions and 16 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ logsp:
docker-compose -f docker-compose-prod.yml logs

test:
go test -timeout 30m ./tests -v -count=1 -run TestProfiles
go test -timeout 30m ./tests -v -count=1 -run TestAdminUsers

swag:
swag init --md .
3 changes: 1 addition & 2 deletions database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ func CreateTables(db *gorm.DB) {
}

func DropTables(db *gorm.DB) {
// Drop Tables
models := Models()
for _, model := range models {
db.Migrator().DropTable(model)
Expand Down Expand Up @@ -101,7 +100,6 @@ func ConnectDb(cfg config.Config, loggedOpts ...bool) *gorm.DB {
} else {
db.Logger = logger.Default.LogMode(logger.Error)
}
log.Println("Running Migrations")

// Add UUID extension
result := db.Exec("CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";")
Expand All @@ -111,6 +109,7 @@ func ConnectDb(cfg config.Config, loggedOpts ...bool) *gorm.DB {

// Add Migrations
if os.Getenv("ENVIRONMENT") != "test" {
log.Println("Running Migrations")
MakeMigrations(db)
}
return db
Expand Down
2 changes: 1 addition & 1 deletion routes/admin_users.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func (ep Endpoint) AdminGetUsers(c *fiber.Ctx) error {
accountType = (*choices.AccType)(&acctType)
accountType.IsValid()
if !accountType.IsValid() {
return c.Status(400).JSON(utils.RequestErr(utils.ERR_INVALID_PARAM, "Invalid account type"))
return c.Status(400).JSON(utils.InvalidParamErr("Invalid account type!"))
}
if acctType == "ADMIN" {
staff = &truthy
Expand Down
96 changes: 96 additions & 0 deletions tests/admin_users_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package tests

import (
"fmt"
"testing"

"github.com/LitPad/backend/models"
"github.com/LitPad/backend/models/choices"
"github.com/LitPad/backend/schemas"
"github.com/gofiber/fiber/v2"
"github.com/stretchr/testify/assert"
"gorm.io/gorm"
)

func getUsers(t *testing.T, app *fiber.App, db *gorm.DB, baseUrl string, token string) {
t.Run("Reject Users Fetch Due to Invalid Account Type", func(t *testing.T) {
url := fmt.Sprintf("%s?account_type=invalid-account-type", baseUrl)
res := ProcessTestGetOrDelete(app, url, "GET", token)
// Assert Status code
assert.Equal(t, 400, res.StatusCode)

// Parse and assert body
body := ParseResponseBody(t, res.Body).(map[string]interface{})
assert.Equal(t, "failure", body["status"])
assert.Equal(t, "Invalid account type!", body["message"])
})

t.Run("Accept Users Fetch", func(t *testing.T) {
TestVerifiedUser(db)
res := ProcessTestGetOrDelete(app, baseUrl, "GET", token)
// Assert Status code
assert.Equal(t, 200, res.StatusCode)

// Parse and assert body
body := ParseResponseBody(t, res.Body).(map[string]interface{})
assert.Equal(t, "success", body["status"])
assert.Equal(t, "Profiles fetched successfully", body["message"])
})
}

func updateUserRole(t *testing.T, app *fiber.App, db *gorm.DB, baseUrl string, admin models.User, token string) {
data := schemas.UpdateUserRoleSchema{AccountType: choices.ACCTYPE_READER}

t.Run("Reject Role Update Due to Invalid Username", func(t *testing.T) {
url := fmt.Sprintf("%s/invalid-username", baseUrl)
res := ProcessJsonTestBody(t, app, url, "PUT", data, token)
// Assert Status code
assert.Equal(t, 404, res.StatusCode)

// Parse and assert body
body := ParseResponseBody(t, res.Body).(map[string]interface{})
assert.Equal(t, "failure", body["status"])
assert.Equal(t, "User Not Found", body["message"])
})

t.Run("Accept Role Update Due to Valid Username", func(t *testing.T) {
url := fmt.Sprintf("%s/%s", baseUrl, admin.Username)
res := ProcessJsonTestBody(t, app, url, "PUT", data, token)
// Assert Status code
assert.Equal(t, 200, res.StatusCode)

// Parse and assert body
body := ParseResponseBody(t, res.Body).(map[string]interface{})
assert.Equal(t, "success", body["status"])
assert.Equal(t, "User details updated successfully!", body["message"])
})
}

func toggleUserActivation(t *testing.T, app *fiber.App, db *gorm.DB, baseUrl string, token string) {
user := TestUser(db)

t.Run("Accept User Activation Toggle", func(t *testing.T) {
url := fmt.Sprintf("%s/%s/toggle-activation", baseUrl, user.Username)
res := ProcessTestGetOrDelete(app, url, "GET", token)
// Assert Status code
assert.Equal(t, 200, res.StatusCode)

// Parse and assert body
body := ParseResponseBody(t, res.Body).(map[string]interface{})
assert.Equal(t, "success", body["status"])
assert.Equal(t, "User deactivated successfully", body["message"])
})
}

func TestAdminUsers(t *testing.T) {
app := fiber.New()
db := Setup(t, app)
admin := TestAdmin(db)
token := AccessToken(db, admin)
baseUrl := "/api/v1/admin/users"

// Run Admin Users Endpoint Tests
getUsers(t, app, db, baseUrl, token)
updateUserRole(t, app, db, baseUrl, admin, token)
toggleUserActivation(t, app, db, baseUrl, token)
}
34 changes: 24 additions & 10 deletions tests/data.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ func TestUser(db *gorm.DB) models.User {
db.Where("email = ?", email).Delete(&models.User{})

user := models.User{
Email: email,
Password: MASTER_PASSWORD,
Email: email,
Password: MASTER_PASSWORD,
}
db.Create(&user)
return user
Expand All @@ -28,8 +28,8 @@ func TestVerifiedUser(db *gorm.DB, activeSub ...bool) models.User {
email := "[email protected]"

user := models.User{
Email: email,
Password: MASTER_PASSWORD,
Email: email,
Password: MASTER_PASSWORD,
IsEmailVerified: true,
}
if len(activeSub) > 0 {
Expand All @@ -44,10 +44,10 @@ func TestVerifiedUser(db *gorm.DB, activeSub ...bool) models.User {
func TestAuthor(db *gorm.DB, another ...bool) models.User {
email := "[email protected]"
user := models.User{
Email: email,
Password: MASTER_PASSWORD,
Email: email,
Password: MASTER_PASSWORD,
IsEmailVerified: true,
AccountType: choices.ACCTYPE_AUTHOR,
AccountType: choices.ACCTYPE_AUTHOR,
}

if len(another) > 0 {
Expand All @@ -57,7 +57,6 @@ func TestAuthor(db *gorm.DB, another ...bool) models.User {
return user
}


func JwtData(db *gorm.DB, user models.User) models.User {
access := routes.GenerateAccessToken(user.ID)
refresh := routes.GenerateRefreshToken()
Expand Down Expand Up @@ -125,9 +124,24 @@ func ParagraphCommentData(db *gorm.DB, chapter models.Chapter, user models.User)

func NotificationData(db *gorm.DB, sender models.User, receiver models.User) models.Notification {
notification := models.Notification{
SenderID: sender.ID, ReceiverID: receiver.ID,
SenderID: sender.ID, ReceiverID: receiver.ID,
Ntype: choices.NT_FOLLOWING, Text: "This is a test notification",
}
db.FirstOrCreate(&notification, notification)
return notification
}
}

// ADMIN TEST DATA
func TestAdmin(db *gorm.DB) models.User {
email := "[email protected]"

user := models.User{
Email: email,
Password: MASTER_PASSWORD,
IsStaff: true,
IsSuperuser: true,
IsEmailVerified: true,
}
db.FirstOrCreate(&user, models.User{Email: user.Email})
return user
}
4 changes: 2 additions & 2 deletions tests/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,10 @@ func Setup(t *testing.T, app *fiber.App) *gorm.DB {
db := SetupTestDatabase(t)

routes.SetupRoutes(app, db)
t.Logf("Making Database Migrations....")
t.Log("Dropping & Creating Tables...")
database.DropTables(db)
database.CreateTables(db)
t.Logf("Database Migrations Made successfully")
t.Log("Tables Created Successfully")
return db
}

Expand Down

0 comments on commit 32468fe

Please sign in to comment.