Skip to content

Commit

Permalink
Merge pull request #246 from COS301-SE-2024/test/backend/coverage-dat…
Browse files Browse the repository at this point in the history
…abase-functions

Test/backend/coverage database functions
  • Loading branch information
waveyboym authored Jul 27, 2024
2 parents 52f7d13 + 33f6c2a commit 3ce7a98
Show file tree
Hide file tree
Showing 17 changed files with 767 additions and 27 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build-python.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Build Python App
name: Build Python App 🏗️

on:
pull_request:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/deploy-docs.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Deploy Docs site to Live site
name: Build 🏗️ and Deploy Documentation 🛳️

on:
push:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/deploy-golang-develop.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Build and Deploy Dev golang
name: Build 🏗️ and Deploy Golang App 🛳️ to Develop 🚈

on:
push:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/deploy-golang-prod.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Build and Deploy Prod golang
name: Build🏗️ and Deploy Golang App 🛳️ to Prod 🚝

on:
push:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/deploy-landing-page.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Deploy Landing page
name: Build 🏗️ and Deploy Landing Page 🛳️

on:
push:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/deploy-python.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Build and Deploy Python App
name: Build 🏗️ and Deploy Python App 🛳️

on:
push:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/deploy-web-develop.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Deploy Develop Dashboard
name: Build 🏗️ and Deploy Web 🛳️ to Develop 🚈

on:
push:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/deploy-web-prod.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Deploy Prod Dashboard
name: Build 🏗️ and Deploy 🛳️ Web App to Production 🚝

on:
push:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/lint-test-build-golang.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Lint, Test and Build golang
name: Lint🌸, Test🧪 and Build🏗️ golang

on:
pull_request:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/lint-test-build-web.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Lint, Test, Build Web
name: Lint🌸, Test🧪, Build🏗️ Web

on:
pull_request:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/lint-test-mobile.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Lint and Test Mobile
name: Lint🌸 and Test🧪 Mobile

on:
pull_request:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/test-and-cov.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Test Web, Mobile and API and generate coverage report
name: Test🧪 Web💻, Mobile📱 and API🔌 and generate coverage report📋

on:
push:
Expand Down
18 changes: 4 additions & 14 deletions occupi-backend/pkg/database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,10 @@ func ConfirmCheckIn(ctx *gin.Context, appsession *models.AppSession, checkIn mod
// Save the check-in to the database
collection := appsession.DB.Database(configs.GetMongoDBName()).Collection("RoomBooking")

// Find the booking by bookingId, roomId, and creator
// Find the booking by bookingId, occupiId, and creator
filter := bson.M{
"_id": checkIn.BookingID,
"creator": checkIn.Creator,
"occupiId": checkIn.BookingID,
"creator": checkIn.Creator,
}

update := bson.M{"$set": bson.M{"checkedIn": true}}
Expand Down Expand Up @@ -154,7 +154,7 @@ func BookingExists(ctx *gin.Context, appsession *models.AppSession, id string) b
// Check if the booking exists in the database
collection := appsession.DB.Database(configs.GetMongoDBName()).Collection("RoomBooking")

filter := bson.M{"_id": id}
filter := bson.M{"occupiId": id}
var existingbooking models.Booking
err := collection.FindOne(ctx, filter).Decode(&existingbooking)
if err != nil {
Expand Down Expand Up @@ -395,11 +395,6 @@ func CheckIfNextVerificationDateIsDue(ctx *gin.Context, appsession *models.AppSe
if !time.Now().After(userData.NextVerificationDate) {
return false, nil
}
_, err := UpdateVerificationStatusTo(ctx, appsession, email, false)
if err != nil {
logrus.Error(err)
return false, err
}
return true, nil
}

Expand All @@ -419,11 +414,6 @@ func CheckIfNextVerificationDateIsDue(ctx *gin.Context, appsession *models.AppSe
if !time.Now().After(user.NextVerificationDate) {
return false, nil
}
_, err = UpdateVerificationStatusTo(ctx, appsession, email, false)
if err != nil {
logrus.Error(err)
return false, err
}
return true, nil
}

Expand Down
2 changes: 1 addition & 1 deletion occupi-backend/pkg/handlers/api_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ func BookRoom(ctx *gin.Context, appsession *models.AppSession) {
return
}

ctx.JSON(http.StatusOK, utils.SuccessResponse(http.StatusOK, "Successfully booked!", booking.RoomID))
ctx.JSON(http.StatusOK, utils.SuccessResponse(http.StatusOK, "Successfully booked!", booking.OccupiID))
}

func CancelBooking(ctx *gin.Context, appsession *models.AppSession) {
Expand Down
7 changes: 7 additions & 0 deletions occupi-backend/pkg/handlers/auth_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,13 @@ func PreLoginAccountChecks(ctx *gin.Context, appsession *models.AppSession, emai
return false, err
}

// update verification status in database to false
_, err = database.UpdateVerificationStatusTo(ctx, appsession, email, false)
if err != nil {
ctx.JSON(http.StatusInternalServerError, utils.InternalServerError())
return false, err
}

// check if the users ip address is logging in from a known location
isIPValid, unrecognizedLogger, err := database.CheckIfUserIsLoggingInFromKnownLocation(ctx, appsession, email, utils.GetClientIP(ctx))

Expand Down
194 changes: 194 additions & 0 deletions occupi-backend/tests/cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,105 @@ import (
"github.com/COS301-SE-2024/occupi/occupi-backend/pkg/models"
)

func TestSaveBooking_WithCache(t *testing.T) {
// Create database connection and Cache
db := configs.ConnectToDatabase(constants.AdminDBAccessOption)
Cache := configs.CreateCache()

// Create a new ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
w := httptest.NewRecorder()

// Create a response writer and context
ctx, _ := gin.CreateTestContext(w)

// Create a new AppSession with the Cache
appSession := &models.AppSession{
DB: db,
Cache: Cache,
}

booking := models.Booking{
OccupiID: "OCCUPI01",
}

success, err := database.SaveBooking(ctx, appSession, booking)
assert.True(t, success)
assert.Nil(t, err)

// Verify the booking is in the Cache
cachedBooking1, err := Cache.Get(cache.RoomBookingKey(booking.OccupiID))
assert.Nil(t, err)
assert.NotNil(t, cachedBooking1)

// sleep for 2 * Cache expiry time to ensure the Cache expires
time.Sleep(time.Duration(configs.GetCacheEviction()) * 2 * time.Second)

// Verify the booking is not in the Cache
cachedBooking2, err := Cache.Get(cache.UserKey(booking.OccupiID))
assert.NotNil(t, err)
assert.Nil(t, cachedBooking2)
}

func TestConfirmCheckin_WithCache(t *testing.T) {
// Create database connection and Cache
db := configs.ConnectToDatabase(constants.AdminDBAccessOption)
Cache := configs.CreateCache()

// Create a new ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
w := httptest.NewRecorder()

// Create a response writer and context
ctx, _ := gin.CreateTestContext(w)

// Create a new AppSession with the Cache
appSession := &models.AppSession{
DB: db,
Cache: Cache,
}

checkin := models.CheckIn{
BookingID: "ROOM01",
Creator: "[email protected]",
}

booking := models.Booking{
OccupiID: checkin.BookingID,
Creator: checkin.Creator,
CheckedIn: false,
}

collection := db.Database(configs.GetMongoDBName()).Collection("RoomBooking")
_, err := collection.InsertOne(ctx, booking)

assert.Nil(t, err)

// marshall and add the booking to cache
bookingData, err := bson.Marshal(booking)

assert.Nil(t, err)

err = Cache.Set(cache.RoomBookingKey(booking.OccupiID), bookingData)

assert.Nil(t, err)

success, err := database.ConfirmCheckIn(ctx, appSession, checkin)
assert.True(t, success)
assert.Nil(t, err)

// Verify the booking is in the Cache
cachedBooking1, err := Cache.Get(cache.RoomBookingKey(checkin.BookingID))
assert.Nil(t, err)
assert.NotNil(t, cachedBooking1)

// sleep for 2 * Cache expiry time to ensure the Cache expires
time.Sleep(time.Duration(configs.GetCacheEviction()) * 2 * time.Second)

// Verify the booking is not in the Cache
cachedBooking2, err := Cache.Get(cache.UserKey(checkin.BookingID))
assert.NotNil(t, err)
assert.Nil(t, cachedBooking2)
}

func TestEmailExistsPerformance(t *testing.T) {
email := "[email protected]"

Expand Down Expand Up @@ -112,6 +211,101 @@ func TestEmailExists_WithCache(t *testing.T) {
assert.NotNil(t, cachedUser)
}

func TestBookingExistsPerformance(t *testing.T) {
id := "OCCUPI0101"

// Create database connection and Cache
db := configs.ConnectToDatabase(constants.AdminDBAccessOption)
Cache := configs.CreateCache()

// Create a new ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
w := httptest.NewRecorder()

// Create a response writer and context
ctx, _ := gin.CreateTestContext(w)

// Create a new AppSession with the Cache
appsessionWithCache := &models.AppSession{
DB: db,
Cache: Cache,
}
// Create a new AppSession without the Cache
appsessionWithoutCache := &models.AppSession{
DB: db,
Cache: nil,
}

// Mock the DB response
collection := db.Database(configs.GetMongoDBName()).Collection("RoomBooking")
bookingStruct := models.Booking{
OccupiID: id,
}
_, err := collection.InsertOne(ctx, bookingStruct)
if err != nil {
t.Fatalf("Failed to insert test booking into database: %v", err)
}

// Test performance with Cache
startTime := time.Now()
for i := 0; i < 1000; i++ {
database.BookingExists(ctx, appsessionWithCache, id)
}
durationWithCache := time.Since(startTime)

// Test performance without Cache
startTime = time.Now()
for i := 0; i < 1000; i++ {
database.BookingExists(ctx, appsessionWithoutCache, id)
}
durationWithoutCache := time.Since(startTime)

// Assert that the Cache improves the speed
if durationWithoutCache <= durationWithCache {
t.Errorf("Cache did not improve performance: duration with Cache %v, duration without Cache %v", durationWithCache, durationWithoutCache)
}
}

func TestBookingExists_WithCache(t *testing.T) {
id := "OCCUPI0101"
// Create database connection and Cache
db := configs.ConnectToDatabase(constants.AdminDBAccessOption)
Cache := configs.CreateCache()

// Create a new ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
w := httptest.NewRecorder()

// Create a response writer and context
ctx, _ := gin.CreateTestContext(w)

// Create a new AppSession with the Cache
appSession := &models.AppSession{
DB: db,
Cache: Cache,
}

// Mock the DB response
collection := db.Database(configs.GetMongoDBName()).Collection("RoomBooking")
bookingStruct := models.Booking{
OccupiID: id,
}
_, err := collection.InsertOne(ctx, bookingStruct)
if err != nil {
t.Fatalf("Failed to insert test booking into database: %v", err)
}

// call the function to test
exists := database.BookingExists(ctx, appSession, id)

// Verify the response
assert.True(t, exists)

// Verify the booking is in the Cache
cachedBooking, err := Cache.Get(cache.RoomBookingKey(id))

assert.Nil(t, err)
assert.NotNil(t, cachedBooking)
}

func TestAddUser_WithCache(t *testing.T) {
// Create database connection and Cache
db := configs.ConnectToDatabase(constants.AdminDBAccessOption)
Expand Down
Loading

0 comments on commit 3ce7a98

Please sign in to comment.