Skip to content

Commit

Permalink
Test pass
Browse files Browse the repository at this point in the history
  • Loading branch information
Rethakgetse-Manaka committed Jun 22, 2024
1 parent c1683d7 commit d23e629
Show file tree
Hide file tree
Showing 3 changed files with 112 additions and 108 deletions.
1 change: 0 additions & 1 deletion occupi-backend/pkg/database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,6 @@ func GetUserBookings(ctx *gin.Context, db *mongo.Client, email string) ([]models
logrus.Error(err)
return nil, err
}
fmt.Println("Here")
bookings = append(bookings, booking)
}
return bookings, nil
Expand Down
16 changes: 16 additions & 0 deletions occupi-backend/pkg/middleware/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,3 +144,19 @@ func AttachRateLimitMiddleware(ginRouter *gin.Engine) {
// Apply the middleware to the router
ginRouter.Use(middleware)
}

// MockAuthMiddleware simulates an authenticated user for testing purposes
func MockAuthMiddleware() gin.HandlerFunc {
return func(ctx *gin.Context) {
_, err := ctx.Cookie("token")
if err == nil {
// Simulate adding a user to the context
ctx.Set("user", map[string]interface{}{
"id": "test-user-id",
"email": "[email protected]",
"role": "user",
})
}
ctx.Next()
}
}
203 changes: 96 additions & 107 deletions occupi-backend/tests/handlers_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package tests

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
Expand All @@ -19,133 +20,121 @@ import (
"github.com/COS301-SE-2024/occupi/occupi-backend/pkg/constants"
"github.com/COS301-SE-2024/occupi/occupi-backend/pkg/database"
"github.com/COS301-SE-2024/occupi/occupi-backend/pkg/middleware"
"github.com/COS301-SE-2024/occupi/occupi-backend/pkg/models"
"github.com/COS301-SE-2024/occupi/occupi-backend/pkg/router"
"github.com/COS301-SE-2024/occupi/occupi-backend/pkg/utils"
// "github.com/stretchr/testify/mock"
)

/*
// Mock for utils.GenerateOTP
type MockUtils struct {
mock.Mock
}
// GenerateOTP simulates the generation of a One Time Password (OTP) for testing purposes.
func (m *MockUtils) GenerateOTP() (string, error) {
args := m.Called()
return args.String(0), args.Error(1)
}
// Mock for mail.SendMail
type MockMail struct {
mock.Mock
}
// SendMail simulates the sending of an email for testing purposes.
func (m *MockMail) SendMail(to, subject, body string) error {
args := m.Called(to, subject, body)
return args.Error(0)
}
// TestRegister tests the user registration endpoint.
func TestRegister(t *testing.T) {
mockUtils := new(MockUtils)
mockMail := new(MockMail)
func TestViewBookingsHandler(t *testing.T) {
// Load environment variables from .env file
if err := godotenv.Load("../.env"); err != nil {
t.Fatal(fmt.Printf("Error loading .env file with error as %s", err))
}

// Mock the GenerateOTP method to return a specific OTP.
mockUtils.On("GenerateOTP").Return("123456", nil)
// Mock the SendMail method to simulate sending an email.
mockMail.On("SendMail", "[email protected]", "Your OTP for Email Verification", "Your OTP is: 123456").Return(nil)
// setup logger to log all server interactions
utils.SetupLogger()

// Create a new HTTP request to register a user.
reqBody := `{"email":"[email protected]"}`
req, err := http.NewRequest("POST", "/register", bytes.NewBufferString(reqBody))
assert.NoError(t, err)
// connect to the database
db := database.ConnectToDatabase()

// Record the HTTP response.
rr := httptest.NewRecorder()
// Create the handler with mocked dependencies.
handler := handlers.Register(mockUtils.GenerateOTP, mockMail.SendMail)
handler.ServeHTTP(rr, req)
// Assert the response status code.
assert.Equal(t, http.StatusOK, rr.Code)
// Assert that the mocked methods were called as expected.
mockUtils.AssertExpectations(t)
mockMail.AssertExpectations(t)
// Decode and verify the response body.
var response map[string]string
err = json.NewDecoder(rr.Body).Decode(&response)
assert.NoError(t, err)
assert.Equal(t, "Registration successful! Please check your email for the OTP to verify your account.", response["message"])
}
// set gin run mode
gin.SetMode("test")

// TestVerifyOTP tests the OTP verification endpoint.
func TestVerifyOTP(t *testing.T) {
// Add a test user with a known OTP.
handlers.Users["[email protected]"] = models.User{Email: "[email protected]", Token: "123456"}
// Create a Gin router
ginRouter := gin.Default()

// Create a new HTTP request to verify OTP.
reqBody := `{"email":"[email protected]", "otp":"123456"}`
req, err := http.NewRequest("POST", "/verify-otp", bytes.NewBufferString(reqBody))
assert.NoError(t, err)
// Register routes
router.OccupiRouter(ginRouter, db)

// Record the HTTP response.
// Create a request user
loginPayload := models.RequestUser{
Email: "[email protected]",
Password: "Dycroc911$",
}
// Marshal the payload into JSON
jsonPayload, err := json.Marshal(loginPayload)
if err != nil {
t.Fatalf("Error marshaling login payload: %v", err)
}
// Simulate login
req, err := http.NewRequest("POST", "/auth/login", bytes.NewBuffer(jsonPayload))
if err != nil {
t.Fatal(fmt.Printf("Error creating login request: %v", err))
}
req.Header.Set("Content-Type", "application/json")
rr := httptest.NewRecorder()
// Create the handler.
handler := http.HandlerFunc(handlers.VerifyOTP)
handler.ServeHTTP(rr, req)
// Assert the response status code.
assert.Equal(t, http.StatusOK, rr.Code)
// Decode and verify the response body.
var response map[string]string
err = json.NewDecoder(rr.Body).Decode(&response)
assert.NoError(t, err)
assert.Equal(t, "Email verified successfully!", response["message"])
}
// TestVerifyOTP_InvalidOTP tests OTP verification with an invalid OTP.
func TestVerifyOTP_InvalidOTP(t *testing.T) {
// Add a test user with a known OTP.
handlers.Users["[email protected]"] = models.User{Email: "[email protected]", Token: "123456"}
// Create a new HTTP request with an incorrect OTP.
reqBody := `{"email":"[email protected]", "otp":"654321"}`
req, err := http.NewRequest("POST", "/verify-otp", bytes.NewBufferString(reqBody))
assert.NoError(t, err)
ginRouter.ServeHTTP(rr, req)
assert.Equal(t, http.StatusOK, rr.Code, "login handler returned wrong status code")

// Store the cookies from the login response
cookies := rr.Result().Cookies()

// Define test cases
testCases := []struct {
name string
email string
expectedStatusCode float64
expectedMessage string
expectedBookings int
}{
{
name: "Valid Request",
email: "[email protected]",
expectedStatusCode: float64(http.StatusOK),
expectedMessage: "Successfully fetched bookings!",
expectedBookings: 2,
},
{
name: "Invalid Request",
email: "",
expectedStatusCode: float64(http.StatusBadRequest),
expectedMessage: "Invalid request payload",
expectedBookings: 0,
},
}

// Record the HTTP response.
rr := httptest.NewRecorder()
// Create the handler.
handler := http.HandlerFunc(handlers.VerifyOTP)
handler.ServeHTTP(rr, req)
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Create a request to pass to the handler
req, err := http.NewRequest("GET", "/api/view-bookings?email="+tc.email, nil)
if err != nil {
t.Fatal(err)
}

// Assert the response status code.
assert.Equal(t, http.StatusBadRequest, rr.Code)
}
// Add the stored cookies to the request
for _, cookie := range cookies {
req.AddCookie(cookie)
}

// Create a response recorder to record the response
rr := httptest.NewRecorder()

// TestVerifyOTP_EmailNotRegistered tests OTP verification for an unregistered email.
func TestVerifyOTP_EmailNotRegistered(t *testing.T) {
// Create a new HTTP request with an unregistered email.
reqBody := `{"email":"[email protected]", "otp":"123456"}`
req, err := http.NewRequest("POST", "/verify-otp", bytes.NewBufferString(reqBody))
assert.NoError(t, err)
// Serve the request
ginRouter.ServeHTTP(rr, req)

// Record the HTTP response.
rr := httptest.NewRecorder()
// Create the handler.
handler := http.HandlerFunc(handlers.VerifyOTP)
handler.ServeHTTP(rr, req)
// Check the status code is what we expect
assert.Equal(t, tc.expectedStatusCode, float64(rr.Code), "handler returned wrong status code")

// Assert the response status code.
assert.Equal(t, http.StatusBadRequest, rr.Code)
// Define the expected response
expectedResponse := gin.H{
"message": tc.expectedMessage,
"data": make([]map[string]interface{}, tc.expectedBookings), // Adjust expected data length
"status": tc.expectedStatusCode,
}

}*/
// Unmarshal the actual response
var actualResponse gin.H
if err := json.Unmarshal(rr.Body.Bytes(), &actualResponse); err != nil {
t.Fatalf("could not unmarshal response: %v", err)
}

// Compare the responses
assert.Equal(t, expectedResponse["message"], actualResponse["message"], "handler returned unexpected message")
assert.Equal(t, expectedResponse["status"], actualResponse["status"], "handler returned unexpected status")
})
}
}
func TestPingRoute(t *testing.T) {
// Load environment variables from .env file
if err := godotenv.Load("../.env"); err != nil {
Expand Down

0 comments on commit d23e629

Please sign in to comment.