From 32468fe2838db9cdc359b6691d81f14b3096eba9 Mon Sep 17 00:00:00 2001 From: kene Date: Wed, 29 Jan 2025 10:58:41 +0100 Subject: [PATCH] tests: admin users completed --- Makefile | 2 +- database/database.go | 3 +- routes/admin_users.go | 2 +- tests/admin_users_test.go | 96 +++++++++++++++++++++++++++++++++++++++ tests/data.go | 34 ++++++++++---- tests/main.go | 4 +- 6 files changed, 125 insertions(+), 16 deletions(-) create mode 100644 tests/admin_users_test.go diff --git a/Makefile b/Makefile index c6a3d47..78e4a27 100644 --- a/Makefile +++ b/Makefile @@ -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 . \ No newline at end of file diff --git a/database/database.go b/database/database.go index efe882a..b75f43d 100644 --- a/database/database.go +++ b/database/database.go @@ -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) @@ -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\";") @@ -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 diff --git a/routes/admin_users.go b/routes/admin_users.go index 5ff315f..182c947 100644 --- a/routes/admin_users.go +++ b/routes/admin_users.go @@ -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 diff --git a/tests/admin_users_test.go b/tests/admin_users_test.go new file mode 100644 index 0000000..085b020 --- /dev/null +++ b/tests/admin_users_test.go @@ -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) +} diff --git a/tests/data.go b/tests/data.go index eedf619..f765b62 100644 --- a/tests/data.go +++ b/tests/data.go @@ -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 @@ -28,8 +28,8 @@ func TestVerifiedUser(db *gorm.DB, activeSub ...bool) models.User { email := "testverifieduser@example.com" user := models.User{ - Email: email, - Password: MASTER_PASSWORD, + Email: email, + Password: MASTER_PASSWORD, IsEmailVerified: true, } if len(activeSub) > 0 { @@ -44,10 +44,10 @@ func TestVerifiedUser(db *gorm.DB, activeSub ...bool) models.User { func TestAuthor(db *gorm.DB, another ...bool) models.User { email := "testauthormail@example.com" 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 { @@ -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() @@ -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(¬ification, notification) return notification -} \ No newline at end of file +} + +// ADMIN TEST DATA +func TestAdmin(db *gorm.DB) models.User { + email := "testadmin@example.com" + + user := models.User{ + Email: email, + Password: MASTER_PASSWORD, + IsStaff: true, + IsSuperuser: true, + IsEmailVerified: true, + } + db.FirstOrCreate(&user, models.User{Email: user.Email}) + return user +} diff --git a/tests/main.go b/tests/main.go index 6c9efee..2dab8c2 100644 --- a/tests/main.go +++ b/tests/main.go @@ -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 }