Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test/backend/unit testing & integration testing #83

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
201 changes: 92 additions & 109 deletions occupi-backend/tests/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
Expand All @@ -24,128 +25,110 @@ import (
// "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
}
func TestViewBookingsHandler(t *testing.T) {
// Load environment variables from .env file
if err := godotenv.Load("../.env"); err != nil {
t.Fatal("Error loading .env file: ", err)
}

// 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)
}
// setup logger to log all server interactions
utils.SetupLogger()

// TestRegister tests the user registration endpoint.
func TestRegister(t *testing.T) {
mockUtils := new(MockUtils)
mockMail := new(MockMail)
// connect to the database
db := database.ConnectToDatabase()

// 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)
// set gin run mode
gin.SetMode("test")

// 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)
// Create a Gin router
r := gin.Default()

// Register the route
router.OccupiRouter(r, db)

token, _, _ := authenticator.GenerateToken("[email protected]", constants.Basic)

w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/ping-auth", nil)
req.AddCookie(&http.Cookie{Name: "token", Value: token})

r.ServeHTTP(w, req)

assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(
t,
"{\"data\":null,\"message\":\"pong -> I am alive and kicking and you are auth'd\",\"status\":200}",
strings.ReplaceAll(w.Body.String(), "-\\u003e", "->"),
)

// Store the cookies from the login response
cookies := req.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 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"])
}
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)
}

// 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"}
// Add the stored cookies to the request
for _, cookie := range cookies {
req.AddCookie(cookie)
}

// 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)
// Create a response recorder to record the response
rr := httptest.NewRecorder()

// Record the HTTP response.
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"])
}
// Serve the request
r.ServeHTTP(rr, req)

// 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"}
// Check the status code is what we expect
assert.Equal(t, tc.expectedStatusCode, float64(rr.Code), "handler returned wrong status code")

// 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)
// Define the expected response
expectedResponse := gin.H{
"message": tc.expectedMessage,
"data": make([]map[string]interface{}, tc.expectedBookings), // Adjust expected data length
"status": tc.expectedStatusCode,
}

// Record the HTTP response.
rr := httptest.NewRecorder()
// Create the handler.
handler := http.HandlerFunc(handlers.VerifyOTP)
handler.ServeHTTP(rr, req)
// 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)
}

// Assert the response status code.
assert.Equal(t, http.StatusBadRequest, rr.Code)
// 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")
})
}
}


// 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)

// Record the HTTP response.
rr := httptest.NewRecorder()
// Create the handler.
handler := http.HandlerFunc(handlers.VerifyOTP)
handler.ServeHTTP(rr, req)

// Assert the response status code.
assert.Equal(t, http.StatusBadRequest, rr.Code)

}*/

func TestPingRoute(t *testing.T) {
// Load environment variables from .env file
if err := godotenv.Load("../.env"); err != nil {
Expand Down
Loading