From ee27f51b92619ecc7dd1e258846f3b3eaf0f0b46 Mon Sep 17 00:00:00 2001 From: Devansh-bit Date: Sun, 17 Dec 2023 07:59:48 +0530 Subject: [PATCH 01/13] refactor: Moved session hijack detection to utils --- controllers/mentor.go | 13 ++----------- controllers/project_reg.go | 13 ++----------- controllers/project_update.go | 14 ++------------ controllers/student.go | 26 ++++---------------------- utils/log.go | 24 ++++++++++++++++++++++-- 5 files changed, 32 insertions(+), 58 deletions(-) diff --git a/controllers/mentor.go b/controllers/mentor.go index 2685d2e3..87b874bc 100644 --- a/controllers/mentor.go +++ b/controllers/mentor.go @@ -71,17 +71,8 @@ func RegisterMentor(w http.ResponseWriter, r *http.Request) { // Check if the JWT login username is the same as the mentor's given username login_username := r.Context().Value(middleware.LOGIN_CTX_USERNAME_KEY).(string) - if reqFields.Username != login_username { - utils.LogWarn( - r, - fmt.Sprintf( - "POSSIBLE SESSION HIJACKING\nJWT Username: %s, Given Username: %s", - login_username, - reqFields.Username, - ), - ) - - utils.RespondWithHTTPMessage(r, w, http.StatusUnauthorized, "Login username and given username do not match.") + err = utils.DetectSessionHijackAndRespond(r, w, reqFields.Username, login_username, "Login username and given username do not match.") + if err != nil { return } diff --git a/controllers/project_reg.go b/controllers/project_reg.go index dc3e2777..458247a8 100644 --- a/controllers/project_reg.go +++ b/controllers/project_reg.go @@ -46,17 +46,8 @@ func RegisterProject(w http.ResponseWriter, r *http.Request) { login_username := r.Context().Value(middleware.LoginCtxKey(middleware.LOGIN_CTX_USERNAME_KEY)) - if reqFields.MentorUsername != login_username { - utils.LogWarn( - r, - fmt.Sprintf( - "POSSIBLE SESSION HIJACKING\nJWT Username: %s, Given Username: %s", - login_username, - reqFields.MentorUsername, - ), - ) - - utils.RespondWithHTTPMessage(r, w, http.StatusUnauthorized, "Login username and mentor username do not match.") + err = utils.DetectSessionHijackAndRespond(r, w, reqFields.MentorUsername, login_username.(string), "Login username and mentor username do not match.") + if err != nil { return } diff --git a/controllers/project_update.go b/controllers/project_update.go index 8820f07e..22795d68 100644 --- a/controllers/project_update.go +++ b/controllers/project_update.go @@ -9,7 +9,6 @@ import ( "github.com/kossiitkgp/kwoc-backend/v2/models" "github.com/kossiitkgp/kwoc-backend/v2/utils" - "github.com/rs/zerolog/log" "gorm.io/gorm" ) @@ -48,17 +47,8 @@ func UpdateProject(w http.ResponseWriter, r *http.Request) { login_username := r.Context().Value(middleware.LoginCtxKey(middleware.LOGIN_CTX_USERNAME_KEY)) - if reqFields.MentorUsername != login_username { - log.Warn().Msgf( - "%s %s %s\n%s %s", - r.Method, - r.RequestURI, - "POSSIBLE SESSION HIJACKING.", - fmt.Sprintf("JWT Username: %s", login_username), - fmt.Sprintf("Given Username: %s", reqFields.MentorUsername), - ) - - utils.RespondWithHTTPMessage(r, w, http.StatusUnauthorized, "Login username and mentor username do not match.") + err = utils.DetectSessionHijackAndRespond(r, w, reqFields.MentorUsername, login_username.(string), "Login username and mentor username do not match.") + if err != nil { return } diff --git a/controllers/student.go b/controllers/student.go index b1948b01..c5ad104c 100644 --- a/controllers/student.go +++ b/controllers/student.go @@ -78,17 +78,8 @@ func RegisterStudent(w http.ResponseWriter, r *http.Request) { // Check if the JWT login username is the same as the student's given username login_username := r.Context().Value(middleware.LOGIN_CTX_USERNAME_KEY).(string) - if reqFields.Username != login_username { - utils.LogWarn( - r, - fmt.Sprintf( - "POSSIBLE SESSION HIJACKING\nJWT Username: %s, Given Username: %s", - login_username, - reqFields.Username, - ), - ) - - utils.RespondWithHTTPMessage(r, w, http.StatusUnauthorized, "Login username and given username do not match.") + err = utils.DetectSessionHijackAndRespond(r, w, reqFields.Username, login_username, "Login username and given username do not match.") + if err != nil { return } @@ -183,17 +174,8 @@ func StudentBlogLink(w http.ResponseWriter, r *http.Request) { // Check if the JWT login username is the same as the student's given username login_username := r.Context().Value(middleware.LOGIN_CTX_USERNAME_KEY).(string) - if reqFields.Username != login_username { - utils.LogWarn( - r, - fmt.Sprintf( - "POSSIBLE SESSION HIJACKING\nJWT Username: %s, Given Username: %s", - login_username, - reqFields.Username, - ), - ) - - utils.RespondWithHTTPMessage(r, w, http.StatusUnauthorized, "Login username and given username do not match.") + err = utils.DetectSessionHijackAndRespond(r, w, reqFields.Username, login_username, "Login username and given username do not match.") + if err != nil { return } diff --git a/utils/log.go b/utils/log.go index 4c0743a3..a33676d2 100644 --- a/utils/log.go +++ b/utils/log.go @@ -1,11 +1,14 @@ package utils import ( - "net/http" - + "errors" + "fmt" "github.com/rs/zerolog/log" + "net/http" ) +var SessionHijackError = errors.New("Session hijack detected") + func LogErr(r *http.Request, err error, errMsg string) { log.Err(err).Msgf( "%s %s: %s", @@ -42,3 +45,20 @@ func LogWarnAndRespond(r *http.Request, w http.ResponseWriter, warning string, s LogWarn(r, warning) RespondWithHTTPMessage(r, w, statusCode, warning) } + +func DetectSessionHijackAndRespond(r *http.Request, w http.ResponseWriter, request_username string, login_username string, message string) error { + if request_username != login_username { + LogWarn( + r, + fmt.Sprintf( + "POSSIBLE SESSION HIJACKING\nJWT Username: %s, Given Username: %s", + login_username, + request_username, + ), + ) + + RespondWithHTTPMessage(r, w, http.StatusUnauthorized, message) + return SessionHijackError + } + return nil +} From e448fc001b9c086ec164a02e1153070f77b3e43e Mon Sep 17 00:00:00 2001 From: Devansh-bit Date: Sun, 17 Dec 2023 18:43:52 +0530 Subject: [PATCH 02/13] fix: remove tests for disabled endpoints --- controllers/mentor_test.go | 103 +++++++++++++++++++++++++------------ 1 file changed, 69 insertions(+), 34 deletions(-) diff --git a/controllers/mentor_test.go b/controllers/mentor_test.go index 56615249..e6875325 100644 --- a/controllers/mentor_test.go +++ b/controllers/mentor_test.go @@ -28,6 +28,27 @@ func createMentorRegRequest(reqFields *controllers.RegisterMentorReqFields) *htt return req } +func createMentorUpdateRequest(reqFields *controllers.UpdateMentorReqFields) *http.Request { + reqBody, _ := json.Marshal(reqFields) + + req, _ := http.NewRequest( + "PUT", + "/mentor/form/", + bytes.NewReader(reqBody), + ) + + return req +} + +var testMentor = models.Mentor { + Name: "TestMentor", + Email: "test@test.com", + Username: "someuser", +} + +// Mentor Registration Endpoint Disabled + +/* // Test unauthenticated request to /mentor/form/ func TestMentorRegNoAuth(t *testing.T) { testRequestNoAuth(t, "POST", "/mentor/form/") @@ -57,6 +78,18 @@ func TestMentorRegSessionHijacking(t *testing.T) { expectStatusCodeToBe(t, res, http.StatusUnauthorized) expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusUnauthorized, Message: "Login username and given username do not match."}) } +*/ + + +// Test unauthenticated request to /mentor/form/ [put] +func TestMentorUpdateNoAuth(t *testing.T) { + testRequestNoAuth(t, "PUT", "/mentor/form/") +} + +// Test request to /mentor/form/ [put] with invalid jwt +func TestMentorUpdateInvalidAuth(t *testing.T) { + testRequestInvalidAuth(t, "PUT", "/mentor/form/") +} // Test a new user registration request to /mentor/form/ with proper authentication and input func tMentorRegNewUser(db *gorm.DB, t *testing.T) { @@ -124,40 +157,42 @@ func tMentorRegAsStudent(db *gorm.DB, t *testing.T) { expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("The username `%s` already exists as a student.", testUsername)}) } -// Test requests to /mentor/form/ with proper authentication and input -func TestMentorRegOK(t *testing.T) { - // Set up a local test database path - db := setTestDB() - defer unsetTestDB() - - // Generate a jwt secret key for testing - setTestJwtSecretKey() - defer unsetTestJwtSecretKey() - - // New mentor registration test - t.Run( - "Test: new mentor registration.", - func(t *testing.T) { - tMentorRegNewUser(db, t) - }, - ) - - // Existing mentor registration test - t.Run( - "Test: existing mentor registration.", - func(t *testing.T) { - tMentorRegExistingUser(db, t) - }, - ) - - // Student registering as mentor test - t.Run( - "Test: Student registering as mentor.", - func(t *testing.T) { - tMentorRegAsStudent(db, t) - }, - ) -} +// Currently Disabled + +// // Test requests to /mentor/form/ with proper authentication and input +// func TestMentorRegOK(t *testing.T) { +// // Set up a local test database path +// db := setTestDB() +// defer unsetTestDB() + +// // Generate a jwt secret key for testing +// setTestJwtSecretKey() +// defer unsetTestJwtSecretKey() + +// // New mentor registration test +// t.Run( +// "Test: new mentor registration.", +// func(t *testing.T) { +// tMentorRegNewUser(db, t) +// }, +// ) + +// // Existing mentor registration test +// t.Run( +// "Test: existing mentor registration.", +// func(t *testing.T) { +// tMentorRegExistingUser(db, t) +// }, +// ) + +// // Student registering as mentor test +// t.Run( +// "Test: Student registering as mentor.", +// func(t *testing.T) { +// tMentorRegAsStudent(db, t) +// }, +// ) +// } func createFetchMentorRequest() *http.Request { req, _ := http.NewRequest( From 607b2f85af4c02f21cf917d7de14e8b9d95224a9 Mon Sep 17 00:00:00 2001 From: Devansh-bit Date: Sun, 17 Dec 2023 20:09:00 +0530 Subject: [PATCH 03/13] fix: fixed test TestMentorDashboardOK --- controllers/mentor_test.go | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/controllers/mentor_test.go b/controllers/mentor_test.go index e6875325..9c96bda9 100644 --- a/controllers/mentor_test.go +++ b/controllers/mentor_test.go @@ -40,12 +40,6 @@ func createMentorUpdateRequest(reqFields *controllers.UpdateMentorReqFields) *ht return req } -var testMentor = models.Mentor { - Name: "TestMentor", - Email: "test@test.com", - Username: "someuser", -} - // Mentor Registration Endpoint Disabled /* @@ -349,23 +343,36 @@ func TestMentorDashboardOK(t *testing.T) { testProjects[1].Contributors = strings.TrimSuffix(testProjects[1].Contributors, ",") testProjects[3].Contributors = strings.TrimSuffix(testProjects[3].Contributors, ",") + db.Table("projects").Create(testProjects) for _, p := range testProjects { if (p.MentorId != int32(modelMentor.ID)) && (p.SecondaryMentorId != &mentorID) { continue } + if p.MentorId == int32(modelMentor.ID) { + p.Mentor = models.Mentor{ + Name: modelMentor.Name, + Username: modelMentor.Username, + } + } + if p.SecondaryMentorId == &mentorID { + p.SecondaryMentor = models.Mentor{ + Name: modelMentor.Name, + Username: modelMentor.Username, + } + } + pulls := make([]string, 0) if len(p.Pulls) > 0 { pulls = strings.Split(p.Pulls, ",") } - tags := make([]string, 0) if len(p.Tags) > 0 { tags = strings.Split(p.Tags, ",") } - projects = append(projects, controllers.ProjectInfo{ + Id: p.ID, Name: p.Name, Description: p.Description, RepoLink: p.RepoLink, @@ -397,7 +404,6 @@ func TestMentorDashboardOK(t *testing.T) { }) } - db.Table("projects").Create(testProjects) db.Table("students").Create(modelStudents) testMentor := controllers.MentorDashboard{ @@ -423,8 +429,8 @@ func TestMentorDashboardOK(t *testing.T) { expectStatusCodeToBe(t, res, http.StatusOK) if !reflect.DeepEqual(testMentor, resMentor) { - t.Fatalf("Incorrect data returned from /mentor/dashboard/") fmt.Printf("Expected mentor dashboard: %#v\n\n", testMentor) fmt.Printf("Received mentor dashboard: %#v\n", resMentor) + t.Fatalf("Incorrect data returned from /mentor/dashboard/") } } From 70b3c476e9220d06b72bd89f313044b610c4ed15 Mon Sep 17 00:00:00 2001 From: Devansh-bit Date: Sun, 17 Dec 2023 20:16:19 +0530 Subject: [PATCH 04/13] fix test TestFetchProjDetailsInvalidID --- controllers/project_fetch_test.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/controllers/project_fetch_test.go b/controllers/project_fetch_test.go index 9f29b0ec..1efe1f79 100644 --- a/controllers/project_fetch_test.go +++ b/controllers/project_fetch_test.go @@ -131,7 +131,16 @@ func TestFetchAllProjects(t *testing.T) { // Try fetching a project with an invalid id func TestFetchProjDetailsInvalidID(t *testing.T) { + setTestJwtSecretKey() + defer unsetTestJwtSecretKey() + + testUsername := getTestUsername() + testLoginFields := utils.LoginJwtFields{Username: testUsername} + + testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) + req := createFetchProjDetailsRequest("kekw") + req.Header.Add("Bearer", testJwt) res := executeRequest(req, nil) expectStatusCodeToBe(t, res, http.StatusBadRequest) From 62e2373723efefe00fbb6bda0806464410aefc82 Mon Sep 17 00:00:00 2001 From: Devansh-bit Date: Sun, 17 Dec 2023 20:20:42 +0530 Subject: [PATCH 05/13] fix: fixed test TestFetchProjDetailsDNE --- controllers/project_fetch_test.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/controllers/project_fetch_test.go b/controllers/project_fetch_test.go index 1efe1f79..b0d96e82 100644 --- a/controllers/project_fetch_test.go +++ b/controllers/project_fetch_test.go @@ -152,9 +152,20 @@ func TestFetchProjDetailsDNE(t *testing.T) { db := setTestDB() defer unsetTestDB() + // Generate a jwt secret key for testing + setTestJwtSecretKey() + defer unsetTestJwtSecretKey() + + // Test login fields + testUsername := getTestUsername() + testLoginFields := utils.LoginJwtFields{Username: testUsername} + + testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) + testProjId := rand.Int() req := createFetchProjDetailsRequest(testProjId) + req.Header.Add("Bearer", testJwt) res := executeRequest(req, db) expectStatusCodeToBe(t, res, http.StatusBadRequest) From abf589aed57880b77100c6ec6bc43407a4fbfd8f Mon Sep 17 00:00:00 2001 From: Devansh-bit Date: Sun, 17 Dec 2023 21:05:36 +0530 Subject: [PATCH 06/13] fix: Fixed test TestFetchProjDetailsOK and removed obsolete test TestFetchProjDetailsUnapproved --- controllers/project_fetch_test.go | 31 +++++++++++++++---------------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/controllers/project_fetch_test.go b/controllers/project_fetch_test.go index b0d96e82..3210ed72 100644 --- a/controllers/project_fetch_test.go +++ b/controllers/project_fetch_test.go @@ -172,33 +172,32 @@ func TestFetchProjDetailsDNE(t *testing.T) { expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("Project with id `%d` does not exist.", testProjId)}) } -// Try to fetch an unapproved project -func TestFetchProjDetailsUnapproved(t *testing.T) { +// Try to fetch a valid project +func TestFetchProjDetailsOK(t *testing.T) { db := setTestDB() defer unsetTestDB() - testProj := generateTestProjects(1, false, false)[0] - - _ = db.Table("projects").Create(&testProj) - - req := createFetchProjDetailsRequest(1) - res := executeRequest(req, db) + // Generate a jwt secret key for testing + setTestJwtSecretKey() + defer unsetTestJwtSecretKey() - expectStatusCodeToBe(t, res, http.StatusBadRequest) - expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("Project with id `%d` does not exist.", 1)}) -} + // Test login fields + testUsername := getTestUsername() + testLoginFields := utils.LoginJwtFields{Username: testUsername} -// Try to fetch a valid project -func TestFetchProjDetailsOK(t *testing.T) { - db := setTestDB() - defer unsetTestDB() + testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) testProjects := generateTestProjects(5, false, true) + for i, proj := range testProjects { + proj.Mentor = models.Mentor{Username: testUsername} + testProjects[i] = proj + } _ = db.Table("projects").Create(testProjects) for i, proj := range testProjects { - req := createFetchProjDetailsRequest(i + 1) + req := createFetchProjDetailsRequest(proj.ID) + req.Header.Add("Bearer", testJwt) res := executeRequest(req, db) var resProj controllers.Project From 1457f62b07f03092e8ae140ab349fb6c9bff54cb Mon Sep 17 00:00:00 2001 From: Devansh-bit Date: Sun, 17 Dec 2023 21:15:17 +0530 Subject: [PATCH 07/13] fix: remove tests for disabled endpoint --- controllers/project_reg_test.go | 241 ++++++++++++++++---------------- 1 file changed, 119 insertions(+), 122 deletions(-) diff --git a/controllers/project_reg_test.go b/controllers/project_reg_test.go index 2692756e..02ed1cc6 100644 --- a/controllers/project_reg_test.go +++ b/controllers/project_reg_test.go @@ -1,32 +1,13 @@ package controllers_test import ( - "bytes" - "encoding/json" "fmt" "math/rand" - "net/http" "strings" - "testing" "github.com/kossiitkgp/kwoc-backend/v2/controllers" - "github.com/kossiitkgp/kwoc-backend/v2/utils" - - "gorm.io/gorm" ) -func createProjctRegRequest(reqFields *controllers.RegisterProjectReqFields) *http.Request { - reqBody, _ := json.Marshal(reqFields) - - req, _ := http.NewRequest( - "POST", - "/project/", - bytes.NewReader(reqBody), - ) - - return req -} - func createTestProjectRegFields(mentorUsername string, secondaryMentorUsername string) *controllers.RegisterProjectReqFields { return &controllers.RegisterProjectReqFields{ Name: fmt.Sprintf("YANGJF-%d", rand.Int()), @@ -40,138 +21,154 @@ func createTestProjectRegFields(mentorUsername string, secondaryMentorUsername s } } +/* +----------DISABLE TESTS FOR DISABLED ENDPOINTS-------------- +*/ + +// func createProjctRegRequest(reqFields *controllers.RegisterProjectReqFields) *http.Request { +// reqBody, _ := json.Marshal(reqFields) + +// req, _ := http.NewRequest( +// "POST", +// "/project/", +// bytes.NewReader(reqBody), +// ) + +// return req +// } + // Test unauthenticated request to /project/ -func TestProjectRegNoAuth(t *testing.T) { - testRequestNoAuth(t, "POST", "/project/") -} +// func TestProjectRegNoAuth(t *testing.T) { +// testRequestNoAuth(t, "POST", "/project/") +// } -// Test request to /project/ with invalid jwt -func TestProjectRegInvalidAuth(t *testing.T) { - testRequestInvalidAuth(t, "POST", "/project/") -} +// // Test request to /project/ with invalid jwt +// func TestProjectRegInvalidAuth(t *testing.T) { +// testRequestInvalidAuth(t, "POST", "/project/") +// } // Test request to /project/ with session hijacking attempt -func TestProjectRegSessionHijacking(t *testing.T) { - // Generate a jwt secret key for testing - setTestJwtSecretKey() - defer unsetTestJwtSecretKey() +// func TestProjectRegSessionHijacking(t *testing.T) { +// // Generate a jwt secret key for testing +// setTestJwtSecretKey() +// defer unsetTestJwtSecretKey() - testLoginFields := utils.LoginJwtFields{Username: "someuser"} +// testLoginFields := utils.LoginJwtFields{Username: "someuser"} - someuserJwt, _ := utils.GenerateLoginJwtString(testLoginFields) +// someuserJwt, _ := utils.GenerateLoginJwtString(testLoginFields) - reqFields := controllers.RegisterProjectReqFields{MentorUsername: "anotheruser"} +// reqFields := controllers.RegisterProjectReqFields{MentorUsername: "anotheruser"} - req := createProjctRegRequest(&reqFields) - req.Header.Add("Bearer", someuserJwt) +// req := createProjctRegRequest(&reqFields) +// req.Header.Add("Bearer", someuserJwt) - res := executeRequest(req, nil) +// res := executeRequest(req, nil) - expectStatusCodeToBe(t, res, http.StatusUnauthorized) - expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusUnauthorized, Message: "Login username and mentor username do not match."}) -} +// expectStatusCodeToBe(t, res, http.StatusUnauthorized) +// expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusUnauthorized, Message: "Login username and mentor username do not match."}) +// } // Test a request to /project/ with non-existent mentors -func TestProjectRegInvalidMentor(t *testing.T) { - // Set up a local test database path - db := setTestDB() - defer unsetTestDB() +// func TestProjectRegInvalidMentor(t *testing.T) { +// // Set up a local test database path +// db := setTestDB() +// defer unsetTestDB() - // Generate a jwt secret key for testing - setTestJwtSecretKey() - defer unsetTestJwtSecretKey() +// // Generate a jwt secret key for testing +// setTestJwtSecretKey() +// defer unsetTestJwtSecretKey() - // Register a test mentor - testUsername := getTestUsername() - testLoginFields := utils.LoginJwtFields{Username: testUsername} +// // Register a test mentor +// testUsername := getTestUsername() +// testLoginFields := utils.LoginJwtFields{Username: testUsername} - testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) +// testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) - // --- TEST PROJECT REGISTRATION WITH INVALID PRIMARY MENTOR --- - projectReqFields := createTestProjectRegFields(testUsername, "") +// // --- TEST PROJECT REGISTRATION WITH INVALID PRIMARY MENTOR --- +// projectReqFields := createTestProjectRegFields(testUsername, "") - projectReq := createProjctRegRequest(projectReqFields) - projectReq.Header.Add("Bearer", testJwt) +// projectReq := createProjctRegRequest(projectReqFields) +// projectReq.Header.Add("Bearer", testJwt) - projectRes := executeRequest(projectReq, db) +// projectRes := executeRequest(projectReq, db) - expectStatusCodeToBe(t, projectRes, http.StatusBadRequest) - expectResponseJSONBodyToBe(t, projectRes, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("Error: Mentor `%s` does not exist.", testUsername)}) - // --- TEST PROJECT REGISTRATION WITH INVALID PRIMARY MENTOR --- -} +// expectStatusCodeToBe(t, projectRes, http.StatusBadRequest) +// expectResponseJSONBodyToBe(t, projectRes, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("Error: Mentor `%s` does not exist.", testUsername)}) +// // --- TEST PROJECT REGISTRATION WITH INVALID PRIMARY MENTOR --- +// } // Test a new project registration request to /project/ with proper authentication and input -func tProjectRegNew(db *gorm.DB, testUsername string, testJwt string, t *testing.T) { - projectReqFields := createTestProjectRegFields(testUsername, "") +// func tProjectRegNew(db *gorm.DB, testUsername string, testJwt string, t *testing.T) { +// projectReqFields := createTestProjectRegFields(testUsername, "") - projectReq := createProjctRegRequest(projectReqFields) - projectReq.Header.Add("Bearer", testJwt) +// projectReq := createProjctRegRequest(projectReqFields) +// projectReq.Header.Add("Bearer", testJwt) - projectRes := executeRequest(projectReq, db) +// projectRes := executeRequest(projectReq, db) - expectStatusCodeToBe(t, projectRes, http.StatusOK) - expectResponseJSONBodyToBe(t, projectRes, utils.HTTPMessage{StatusCode: http.StatusOK, Message: "Success."}) -} +// expectStatusCodeToBe(t, projectRes, http.StatusOK) +// expectResponseJSONBodyToBe(t, projectRes, utils.HTTPMessage{StatusCode: http.StatusOK, Message: "Success."}) +// } -// Test an existing project registration request to /project/ with proper authentication and input -func tProjectRegExisting(db *gorm.DB, testUsername string, testJwt string, t *testing.T) { - projectReqFields := createTestProjectRegFields(testUsername, "") +// // Test an existing project registration request to /project/ with proper authentication and input +// func tProjectRegExisting(db *gorm.DB, testUsername string, testJwt string, t *testing.T) { +// projectReqFields := createTestProjectRegFields(testUsername, "") - projectReq := createProjctRegRequest(projectReqFields) - projectReq.Header.Add("Bearer", testJwt) +// projectReq := createProjctRegRequest(projectReqFields) +// projectReq.Header.Add("Bearer", testJwt) - _ = executeRequest(projectReq, db) +// _ = executeRequest(projectReq, db) - // Execute the same request again - projectReq = createProjctRegRequest(projectReqFields) - projectReq.Header.Add("Bearer", testJwt) +// // Execute the same request again +// projectReq = createProjctRegRequest(projectReqFields) +// projectReq.Header.Add("Bearer", testJwt) - projectRes := executeRequest(projectReq, db) +// projectRes := executeRequest(projectReq, db) - expectStatusCodeToBe(t, projectRes, http.StatusBadRequest) - expectResponseJSONBodyToBe(t, projectRes, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("Error: Project `%s` already exists.", projectReqFields.RepoLink)}) -} +// expectStatusCodeToBe(t, projectRes, http.StatusBadRequest) +// expectResponseJSONBodyToBe(t, projectRes, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("Error: Project `%s` already exists.", projectReqFields.RepoLink)}) +// } // Test requests to /project/ with proper authentication and input -func TestProjectRegOK(t *testing.T) { - // Set up a local test database path - db := setTestDB() - defer unsetTestDB() - - // Generate a jwt secret key for testing - setTestJwtSecretKey() - defer unsetTestJwtSecretKey() - - // Register a test mentor - testUsername := getTestUsername() - testLoginFields := utils.LoginJwtFields{ - Username: testUsername, - } - - testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) - - mentorReqFields := controllers.RegisterMentorReqFields{ - Username: testUsername, - Email: "testuser@example.com", - } - - mentorReq := createMentorRegRequest(&mentorReqFields) - mentorReq.Header.Add("Bearer", testJwt) - _ = executeRequest(mentorReq, db) - - // New project registration test - t.Run( - "Test: new project registration.", - func(t *testing.T) { - tProjectRegNew(db, testUsername, testJwt, t) - }, - ) - - // Existing project registration test - t.Run( - "Test: existing project registration.", - func(t *testing.T) { - tProjectRegExisting(db, testUsername, testJwt, t) - }, - ) -} +// func TestProjectRegOK(t *testing.T) { +// // Set up a local test database path +// db := setTestDB() +// defer unsetTestDB() + +// // Generate a jwt secret key for testing +// setTestJwtSecretKey() +// defer unsetTestJwtSecretKey() + +// // Register a test mentor +// testUsername := getTestUsername() +// testLoginFields := utils.LoginJwtFields{ +// Username: testUsername, +// } + +// testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) + +// mentorReqFields := controllers.RegisterMentorReqFields{ +// Username: testUsername, +// Email: "testuser@example.com", +// } + +// mentorReq := createMentorRegRequest(&mentorReqFields) +// mentorReq.Header.Add("Bearer", testJwt) +// _ = executeRequest(mentorReq, db) + +// // New project registration test +// t.Run( +// "Test: new project registration.", +// func(t *testing.T) { +// tProjectRegNew(db, testUsername, testJwt, t) +// }, +// ) + +// // Existing project registration test +// t.Run( +// "Test: existing project registration.", +// func(t *testing.T) { +// tProjectRegExisting(db, testUsername, testJwt, t) +// }, +// ) +// } From d314cf941b1999c5c5843ef8c216e8957b13c15d Mon Sep 17 00:00:00 2001 From: Devansh-bit Date: Sun, 17 Dec 2023 22:09:20 +0530 Subject: [PATCH 08/13] fix: disabled tests for disabled endpoints. fix test TestProjectUpdateOK --- controllers/mentor_test.go | 11 +- controllers/project_update.go | 12 +- controllers/project_update_test.go | 55 +++---- controllers/student_test.go | 231 +++++++++++++++-------------- 4 files changed, 165 insertions(+), 144 deletions(-) diff --git a/controllers/mentor_test.go b/controllers/mentor_test.go index 9c96bda9..fda3dd84 100644 --- a/controllers/mentor_test.go +++ b/controllers/mentor_test.go @@ -134,15 +134,16 @@ func tMentorRegAsStudent(db *gorm.DB, t *testing.T) { testLoginFields := utils.LoginJwtFields{Username: testUsername} testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) - studentFields := controllers.RegisterStudentReqFields{Username: testUsername} + // studentFields := controllers.RegisterStudentReqFields{Username: testUsername} - req := createStudentRegRequest(&studentFields) - req.Header.Add("Bearer", testJwt) + // req := createStudentRegRequest(&studentFields) + // req.Header.Add("Bearer", testJwt) - _ = executeRequest(req, db) + // _ = executeRequest(req, db) + db.Table("students").Create(&models.Student{Username: testUsername}) mentorFields := controllers.RegisterMentorReqFields{Username: testUsername} - req = createMentorRegRequest(&mentorFields) + req := createMentorRegRequest(&mentorFields) req.Header.Add("Bearer", testJwt) res := executeRequest(req, db) diff --git a/controllers/project_update.go b/controllers/project_update.go index 22795d68..8dc1ec82 100644 --- a/controllers/project_update.go +++ b/controllers/project_update.go @@ -104,7 +104,7 @@ func UpdateProject(w http.ResponseWriter, r *http.Request) { tx = db.Table("mentors").Where("username = ?", reqFields.SecondaryMentorUsername).First(&secondaryMentor) - if tx.Error != nil && err != gorm.ErrRecordNotFound { + if tx.Error != nil && tx.Error != gorm.ErrRecordNotFound { utils.LogErrAndRespond( r, w, @@ -114,6 +114,16 @@ func UpdateProject(w http.ResponseWriter, r *http.Request) { ) return } + if tx.Error == gorm.ErrRecordNotFound { + utils.LogErrAndRespond( + r, + w, + err, + fmt.Sprintf("Secondary mentor `%s` does not exist.", reqFields.SecondaryMentorUsername), + http.StatusBadRequest, + ) + return + } } updatedProj := &models.Project{ diff --git a/controllers/project_update_test.go b/controllers/project_update_test.go index ac4abb3c..be553388 100644 --- a/controllers/project_update_test.go +++ b/controllers/project_update_test.go @@ -80,10 +80,26 @@ func tProjectUpdateNonExistent(db *gorm.DB, testUsername string, testJwt string, func tProjectUpdateExistent(db *gorm.DB, testUsername string, testJwt string, t *testing.T) { // Register a test project projRegFields := createTestProjectRegFields(testUsername, "") - projRegReq := createProjctRegRequest(projRegFields) - projRegReq.Header.Add("Bearer", testJwt) - - _ = executeRequest(projRegReq, db) + // projRegReq := createProjctRegRequest(projRegFields) + // projRegReq.Header.Add("Bearer", testJwt) + + // _ = executeRequest(projRegReq, db) + db.Create(&models.Project{ + Name: projRegFields.Name, + Description: projRegFields.Description, + Tags: strings.Join(projRegFields.Tags, ","), + RepoLink: projRegFields.RepoLink, + CommChannel: projRegFields.CommChannel, + ReadmeLink: projRegFields.ReadmeLink, + ProjectStatus: true, + + Mentor: models.Mentor{ + Username: projRegFields.MentorUsername, + }, + SecondaryMentor: models.Mentor{ + Username: projRegFields.SecondaryMentorUsername, + }, + }) // Create updated fields projUpdateFields := &controllers.UpdateProjectReqFields{ @@ -155,14 +171,6 @@ func tProjectUpdateExistent(db *gorm.DB, testUsername string, testJwt string, t if updatedProj.SecondaryMentor.Username != projUpdateFields.SecondaryMentorUsername { t.Errorf("Project secondary mentor username did not get updated\n Expected: `%s`. Received: `%s`", projUpdateFields.SecondaryMentorUsername, updatedProj.SecondaryMentor.Username) } - - if updatedProj.SecondaryMentor.Name != "Secondary, Test" { - t.Errorf("Project secondary mentor name did not get updated\n Expected: `%s`. Received: `%s`", "Secondary, Test", updatedProj.SecondaryMentor.Name) - } - - if updatedProj.SecondaryMentor.Email != "testusersecond@example.com" { - t.Errorf("Project secondary mentor email did not get updated\n Expected: `%s`. Received: `%s`", "testusersecond@example.com", updatedProj.SecondaryMentor.Email) - } } // Test requests to /project/ with proper authentication and input @@ -188,26 +196,23 @@ func TestProjectUpdateOK(t *testing.T) { Email: "testuser@example.com", } - mentorReq := createMentorRegRequest(&mentorReqFields) - mentorReq.Header.Add("Bearer", testJwt) - _ = executeRequest(mentorReq, db) - - // Register a test secondary mentor - testLoginFields = utils.LoginJwtFields{ - Username: "testSecondary", - } - - secondaryJwt, _ := utils.GenerateLoginJwtString(testLoginFields) + db.Table("mentors").Create(&models.Mentor{ + Username: mentorReqFields.Username, + Email: mentorReqFields.Email, + }) + // Register a secondary test mentor mentorReqFields = controllers.RegisterMentorReqFields{ Username: "testSecondary", Name: "Secondary, Test", Email: "testusersecond@example.com", } - mentorReq = createMentorRegRequest(&mentorReqFields) - mentorReq.Header.Add("Bearer", secondaryJwt) - _ = executeRequest(mentorReq, db) + db.Table("mentors").Create(&models.Mentor{ + Username: mentorReqFields.Username, + Name: mentorReqFields.Name, + Email: mentorReqFields.Email, + }) // Non-existent project update test t.Run( diff --git a/controllers/student_test.go b/controllers/student_test.go index 76f07078..701a94e3 100644 --- a/controllers/student_test.go +++ b/controllers/student_test.go @@ -17,148 +17,152 @@ import ( "gorm.io/gorm" ) -func createStudentRegRequest(reqFields *controllers.RegisterStudentReqFields) *http.Request { - reqBody, _ := json.Marshal(reqFields) +/* +----------DISABLE TESTS FOR DISABLED ENDPOINTS-------------- +*/ - req, _ := http.NewRequest( - "POST", - "/student/form/", - bytes.NewReader(reqBody), - ) +// func createStudentRegRequest(reqFields *controllers.RegisterStudentReqFields) *http.Request { +// reqBody, _ := json.Marshal(reqFields) - return req -} +// req, _ := http.NewRequest( +// "POST", +// "/student/form/", +// bytes.NewReader(reqBody), +// ) + +// return req +// } // Test unauthenticated request to /student/form/ -func TestStudentRegNoAuth(t *testing.T) { - testRequestNoAuth(t, "POST", "/student/form/") -} +// func TestStudentRegNoAuth(t *testing.T) { +// testRequestNoAuth(t, "POST", "/student/form/") +// } -// Test request to /student/form/ with invalid jwt -func TestStudentRegInvalidAuth(t *testing.T) { - testRequestInvalidAuth(t, "POST", "/student/form/") -} +// // Test request to /student/form/ with invalid jwt +// func TestStudentRegInvalidAuth(t *testing.T) { +// testRequestInvalidAuth(t, "POST", "/student/form/") +// } // Test request to /student/form/ with session hijacking attempt -func TestStudentRegSessionHijacking(t *testing.T) { - // Generate a jwt secret key for testing - setTestJwtSecretKey() +// func TestStudentRegSessionHijacking(t *testing.T) { +// // Generate a jwt secret key for testing +// setTestJwtSecretKey() - testLoginFields := utils.LoginJwtFields{Username: "someuser"} +// testLoginFields := utils.LoginJwtFields{Username: "someuser"} - someuserJwt, _ := utils.GenerateLoginJwtString(testLoginFields) +// someuserJwt, _ := utils.GenerateLoginJwtString(testLoginFields) - reqFields := controllers.RegisterStudentReqFields{Username: "anotheruser"} +// reqFields := controllers.RegisterStudentReqFields{Username: "anotheruser"} - req := createStudentRegRequest(&reqFields) - req.Header.Add("Bearer", someuserJwt) +// req := createStudentRegRequest(&reqFields) +// req.Header.Add("Bearer", someuserJwt) - res := executeRequest(req, nil) +// res := executeRequest(req, nil) - expectStatusCodeToBe(t, res, http.StatusUnauthorized) - expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusUnauthorized, Message: "Login username and given username do not match."}) -} +// expectStatusCodeToBe(t, res, http.StatusUnauthorized) +// expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusUnauthorized, Message: "Login username and given username do not match."}) +// } -// Test a new user registration request to /student/form/ with proper authentication and input -func tStudentRegNewUser(db *gorm.DB, t *testing.T) { - // Test login fields - testUsername := getTestUsername() - testLoginFields := utils.LoginJwtFields{Username: testUsername} +// // Test a new user registration request to /student/form/ with proper authentication and input +// func tStudentRegNewUser(db *gorm.DB, t *testing.T) { +// // Test login fields +// testUsername := getTestUsername() +// testLoginFields := utils.LoginJwtFields{Username: testUsername} - testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) - reqFields := controllers.RegisterStudentReqFields{Username: testUsername} +// testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) +// reqFields := controllers.RegisterStudentReqFields{Username: testUsername} - req := createStudentRegRequest(&reqFields) - req.Header.Add("Bearer", testJwt) +// req := createStudentRegRequest(&reqFields) +// req.Header.Add("Bearer", testJwt) - res := executeRequest(req, db) +// res := executeRequest(req, db) - expectStatusCodeToBe(t, res, http.StatusOK) - expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusOK, Message: "Student registration successful."}) -} +// expectStatusCodeToBe(t, res, http.StatusOK) +// expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusOK, Message: "Student registration successful."}) +// } -// Test an existing user registration request to /student/form/ with proper authentication and input -func tStudentRegExistingUser(db *gorm.DB, t *testing.T) { - // Test login fields - testUsername := getTestUsername() - testLoginFields := utils.LoginJwtFields{Username: testUsername} +// // Test an existing user registration request to /student/form/ with proper authentication and input +// func tStudentRegExistingUser(db *gorm.DB, t *testing.T) { +// // Test login fields +// testUsername := getTestUsername() +// testLoginFields := utils.LoginJwtFields{Username: testUsername} - testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) - reqFields := controllers.RegisterStudentReqFields{Username: testUsername} +// testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) +// reqFields := controllers.RegisterStudentReqFields{Username: testUsername} - req := createStudentRegRequest(&reqFields) - req.Header.Add("Bearer", testJwt) +// req := createStudentRegRequest(&reqFields) +// req.Header.Add("Bearer", testJwt) - _ = executeRequest(req, db) +// _ = executeRequest(req, db) - // Execute the same request again - req = createStudentRegRequest(&reqFields) - req.Header.Add("Bearer", testJwt) +// // Execute the same request again +// req = createStudentRegRequest(&reqFields) +// req.Header.Add("Bearer", testJwt) - res := executeRequest(req, db) +// res := executeRequest(req, db) - expectStatusCodeToBe(t, res, http.StatusBadRequest) - expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("Student `%s` already exists.", testUsername)}) -} +// expectStatusCodeToBe(t, res, http.StatusBadRequest) +// expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("Student `%s` already exists.", testUsername)}) +// } -// Test an existing mentor registration request to /student/form/ with proper authentication and input -func tStudentRegAsMentor(db *gorm.DB, t *testing.T) { - // Test login fields - testUsername := getTestUsername() - testLoginFields := utils.LoginJwtFields{Username: testUsername} +// // Test an existing mentor registration request to /student/form/ with proper authentication and input +// func tStudentRegAsMentor(db *gorm.DB, t *testing.T) { +// // Test login fields +// testUsername := getTestUsername() +// testLoginFields := utils.LoginJwtFields{Username: testUsername} - testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) - mentorFields := controllers.RegisterMentorReqFields{Username: testUsername} +// testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) +// mentorFields := controllers.RegisterMentorReqFields{Username: testUsername} - req := createMentorRegRequest(&mentorFields) - req.Header.Add("Bearer", testJwt) +// req := createMentorRegRequest(&mentorFields) +// req.Header.Add("Bearer", testJwt) - _ = executeRequest(req, db) +// _ = executeRequest(req, db) - studentsFields := controllers.RegisterStudentReqFields{Username: testUsername} - req = createStudentRegRequest(&studentsFields) - req.Header.Add("Bearer", testJwt) +// studentsFields := controllers.RegisterStudentReqFields{Username: testUsername} +// req = createStudentRegRequest(&studentsFields) +// req.Header.Add("Bearer", testJwt) - res := executeRequest(req, db) +// res := executeRequest(req, db) - expectStatusCodeToBe(t, res, http.StatusBadRequest) - expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("The username `%s` already exists as a mentor.", testUsername)}) -} +// expectStatusCodeToBe(t, res, http.StatusBadRequest) +// expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("The username `%s` already exists as a mentor.", testUsername)}) +// } // Test requests to /student/form/ with proper authentication and input -func TestStudentRegOK(t *testing.T) { - // Set up a local test database path - db := setTestDB() - defer unsetTestDB() - - // Generate a jwt secret key for testing - setTestJwtSecretKey() - defer unsetTestJwtSecretKey() - - // New student registration test - t.Run( - "Test: new student registration.", - func(t *testing.T) { - tStudentRegNewUser(db, t) - }, - ) - - // Existing student registration test - t.Run( - "Test: existing student registration.", - func(t *testing.T) { - tStudentRegExistingUser(db, t) - }, - ) - - // Mentor registering as student test - t.Run( - "Test: Mentor registering as student.", - func(t *testing.T) { - tStudentRegAsMentor(db, t) - }, - ) -} +// func TestStudentRegOK(t *testing.T) { +// // Set up a local test database path +// db := setTestDB() +// defer unsetTestDB() + +// // Generate a jwt secret key for testing +// setTestJwtSecretKey() +// defer unsetTestJwtSecretKey() + +// // New student registration test +// t.Run( +// "Test: new student registration.", +// func(t *testing.T) { +// tStudentRegNewUser(db, t) +// }, +// ) + +// // Existing student registration test +// t.Run( +// "Test: existing student registration.", +// func(t *testing.T) { +// tStudentRegExistingUser(db, t) +// }, +// ) + +// // Mentor registering as student test +// t.Run( +// "Test: Mentor registering as student.", +// func(t *testing.T) { +// tStudentRegAsMentor(db, t) +// }, +// ) +// } func createStudentBlogLinkRequest(reqFields *controllers.StudentBlogLinkReqFields) *http.Request { reqBody, _ := json.Marshal(reqFields) @@ -210,16 +214,17 @@ func tStudentBlogLinkExistingUser(db *gorm.DB, t *testing.T) { testLoginFields := utils.LoginJwtFields{Username: testUsername} testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) - reqFieldsReg := controllers.RegisterStudentReqFields{Username: testUsername} + // reqFieldsReg := controllers.RegisterStudentReqFields{Username: testUsername} - req := createStudentRegRequest(&reqFieldsReg) - req.Header.Add("Bearer", testJwt) + // req := createStudentRegRequest(&reqFieldsReg) + // req.Header.Add("Bearer", testJwt) - _ = executeRequest(req, db) + // _ = executeRequest(req, db) + db.Table("students").Create(&models.Student{Username: testUsername}) // Execute the bloglink request reqFields := controllers.StudentBlogLinkReqFields{Username: testUsername, BlogLink: "https://grugbrain.dev/"} - req = createStudentBlogLinkRequest(&reqFields) + req := createStudentBlogLinkRequest(&reqFields) req.Header.Add("Bearer", testJwt) res := executeRequest(req, db) From 9969dd749190226852dde4ccadd65ba5adcc4867 Mon Sep 17 00:00:00 2001 From: Devansh-bit Date: Sun, 17 Dec 2023 22:23:19 +0530 Subject: [PATCH 09/13] fix linting errors --- controllers/mentor_test.go | 151 ++++++++++++++++++------------------- 1 file changed, 74 insertions(+), 77 deletions(-) diff --git a/controllers/mentor_test.go b/controllers/mentor_test.go index fda3dd84..3004cca8 100644 --- a/controllers/mentor_test.go +++ b/controllers/mentor_test.go @@ -1,7 +1,6 @@ package controllers_test import ( - "bytes" "encoding/json" "fmt" "net/http" @@ -13,32 +12,31 @@ import ( "github.com/kossiitkgp/kwoc-backend/v2/models" "github.com/kossiitkgp/kwoc-backend/v2/utils" - "gorm.io/gorm" ) -func createMentorRegRequest(reqFields *controllers.RegisterMentorReqFields) *http.Request { - reqBody, _ := json.Marshal(reqFields) +// func createMentorRegRequest(reqFields *controllers.RegisterMentorReqFields) *http.Request { +// reqBody, _ := json.Marshal(reqFields) - req, _ := http.NewRequest( - "POST", - "/mentor/form/", - bytes.NewReader(reqBody), - ) +// req, _ := http.NewRequest( +// "POST", +// "/mentor/form/", +// bytes.NewReader(reqBody), +// ) - return req -} +// return req +// } -func createMentorUpdateRequest(reqFields *controllers.UpdateMentorReqFields) *http.Request { - reqBody, _ := json.Marshal(reqFields) +// func createMentorUpdateRequest(reqFields *controllers.UpdateMentorReqFields) *http.Request { +// reqBody, _ := json.Marshal(reqFields) - req, _ := http.NewRequest( - "PUT", - "/mentor/form/", - bytes.NewReader(reqBody), - ) +// req, _ := http.NewRequest( +// "PUT", +// "/mentor/form/", +// bytes.NewReader(reqBody), +// ) - return req -} +// return req +// } // Mentor Registration Endpoint Disabled @@ -74,83 +72,82 @@ func TestMentorRegSessionHijacking(t *testing.T) { } */ - // Test unauthenticated request to /mentor/form/ [put] -func TestMentorUpdateNoAuth(t *testing.T) { - testRequestNoAuth(t, "PUT", "/mentor/form/") -} +// func TestMentorUpdateNoAuth(t *testing.T) { +// testRequestNoAuth(t, "PUT", "/mentor/form/") +// } -// Test request to /mentor/form/ [put] with invalid jwt -func TestMentorUpdateInvalidAuth(t *testing.T) { - testRequestInvalidAuth(t, "PUT", "/mentor/form/") -} +// // Test request to /mentor/form/ [put] with invalid jwt +// func TestMentorUpdateInvalidAuth(t *testing.T) { +// testRequestInvalidAuth(t, "PUT", "/mentor/form/") +// } -// Test a new user registration request to /mentor/form/ with proper authentication and input -func tMentorRegNewUser(db *gorm.DB, t *testing.T) { - // Test login fields - testUsername := getTestUsername() - testLoginFields := utils.LoginJwtFields{Username: testUsername} +// // Test a new user registration request to /mentor/form/ with proper authentication and input +// func tMentorRegNewUser(db *gorm.DB, t *testing.T) { +// // Test login fields +// testUsername := getTestUsername() +// testLoginFields := utils.LoginJwtFields{Username: testUsername} - testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) - reqFields := controllers.RegisterMentorReqFields{Username: testUsername} +// testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) +// reqFields := controllers.RegisterMentorReqFields{Username: testUsername} - req := createMentorRegRequest(&reqFields) - req.Header.Add("Bearer", testJwt) +// req := createMentorRegRequest(&reqFields) +// req.Header.Add("Bearer", testJwt) - res := executeRequest(req, db) +// res := executeRequest(req, db) - expectStatusCodeToBe(t, res, http.StatusOK) - expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusOK, Message: "Mentor registration successful."}) -} +// expectStatusCodeToBe(t, res, http.StatusOK) +// expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusOK, Message: "Mentor registration successful."}) +// } -// Test an existing user registration request to /mentor/form/ with proper authentication and input -func tMentorRegExistingUser(db *gorm.DB, t *testing.T) { - // Test login fields - testUsername := getTestUsername() - testLoginFields := utils.LoginJwtFields{Username: testUsername} +// // Test an existing user registration request to /mentor/form/ with proper authentication and input +// func tMentorRegExistingUser(db *gorm.DB, t *testing.T) { +// // Test login fields +// testUsername := getTestUsername() +// testLoginFields := utils.LoginJwtFields{Username: testUsername} - testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) - reqFields := controllers.RegisterMentorReqFields{Username: testUsername} +// testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) +// reqFields := controllers.RegisterMentorReqFields{Username: testUsername} - req := createMentorRegRequest(&reqFields) - req.Header.Add("Bearer", testJwt) +// req := createMentorRegRequest(&reqFields) +// req.Header.Add("Bearer", testJwt) - _ = executeRequest(req, db) +// _ = executeRequest(req, db) - // Execute the same request again - req = createMentorRegRequest(&reqFields) - req.Header.Add("Bearer", testJwt) +// // Execute the same request again +// req = createMentorRegRequest(&reqFields) +// req.Header.Add("Bearer", testJwt) - res := executeRequest(req, db) +// res := executeRequest(req, db) - expectStatusCodeToBe(t, res, http.StatusBadRequest) - expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("Mentor `%s` already exists.", testUsername)}) -} +// expectStatusCodeToBe(t, res, http.StatusBadRequest) +// expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("Mentor `%s` already exists.", testUsername)}) +// } -// Test an existing student registration request to /mentor/form/ with proper authentication and input -func tMentorRegAsStudent(db *gorm.DB, t *testing.T) { - // Test login fields - testUsername := getTestUsername() - testLoginFields := utils.LoginJwtFields{Username: testUsername} +// // Test an existing student registration request to /mentor/form/ with proper authentication and input +// func tMentorRegAsStudent(db *gorm.DB, t *testing.T) { +// // Test login fields +// testUsername := getTestUsername() +// testLoginFields := utils.LoginJwtFields{Username: testUsername} - testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) - // studentFields := controllers.RegisterStudentReqFields{Username: testUsername} +// testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) +// // studentFields := controllers.RegisterStudentReqFields{Username: testUsername} - // req := createStudentRegRequest(&studentFields) - // req.Header.Add("Bearer", testJwt) +// // req := createStudentRegRequest(&studentFields) +// // req.Header.Add("Bearer", testJwt) - // _ = executeRequest(req, db) - db.Table("students").Create(&models.Student{Username: testUsername}) +// // _ = executeRequest(req, db) +// db.Table("students").Create(&models.Student{Username: testUsername}) - mentorFields := controllers.RegisterMentorReqFields{Username: testUsername} - req := createMentorRegRequest(&mentorFields) - req.Header.Add("Bearer", testJwt) +// mentorFields := controllers.RegisterMentorReqFields{Username: testUsername} +// req := createMentorRegRequest(&mentorFields) +// req.Header.Add("Bearer", testJwt) - res := executeRequest(req, db) +// res := executeRequest(req, db) - expectStatusCodeToBe(t, res, http.StatusBadRequest) - expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("The username `%s` already exists as a student.", testUsername)}) -} +// expectStatusCodeToBe(t, res, http.StatusBadRequest) +// expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("The username `%s` already exists as a student.", testUsername)}) +// } // Currently Disabled @@ -363,7 +360,7 @@ func TestMentorDashboardOK(t *testing.T) { Username: modelMentor.Username, } } - + pulls := make([]string, 0) if len(p.Pulls) > 0 { pulls = strings.Split(p.Pulls, ",") From acce6b7a386692165360412b2a6b832477cf3e1d Mon Sep 17 00:00:00 2001 From: Devansh-bit Date: Sun, 17 Dec 2023 22:48:44 +0530 Subject: [PATCH 10/13] feat: added testMode to enable all routes --- cmd/backend.go | 2 +- controllers/common_test.go | 2 +- controllers/mentor_test.go | 217 ++++++++++++++--------------- controllers/project_reg_test.go | 234 ++++++++++++++++---------------- controllers/student_test.go | 220 +++++++++++++++--------------- server/router.go | 7 +- server/routes.go | 59 +++++--- 7 files changed, 376 insertions(+), 365 deletions(-) diff --git a/cmd/backend.go b/cmd/backend.go index 429460de..e01de018 100644 --- a/cmd/backend.go +++ b/cmd/backend.go @@ -58,7 +58,7 @@ func main() { } log.Info().Msg("Creating mux router") - router := server.NewRouter(db) + router := server.NewRouter(db, false) port := os.Getenv("BACKEND_PORT") if port == "" { diff --git a/controllers/common_test.go b/controllers/common_test.go index 26080bda..9feb6d3c 100644 --- a/controllers/common_test.go +++ b/controllers/common_test.go @@ -19,7 +19,7 @@ import ( // Ref: https://semaphoreci.com/community/tutorials/building-and-testing-a-rest-api-in-go-with-gorilla-mux-and-postgresql#h-writing-tests-for-the-api func executeRequest(req *http.Request, db *gorm.DB) *httptest.ResponseRecorder { rr := httptest.NewRecorder() - router := server.NewRouter(db) + router := server.NewRouter(db, true) router.ServeHTTP(rr, req) diff --git a/controllers/mentor_test.go b/controllers/mentor_test.go index 3004cca8..16b62967 100644 --- a/controllers/mentor_test.go +++ b/controllers/mentor_test.go @@ -1,8 +1,10 @@ package controllers_test import ( + "bytes" "encoding/json" "fmt" + "gorm.io/gorm" "net/http" "reflect" "strings" @@ -11,36 +13,20 @@ import ( "github.com/kossiitkgp/kwoc-backend/v2/controllers" "github.com/kossiitkgp/kwoc-backend/v2/models" "github.com/kossiitkgp/kwoc-backend/v2/utils" - ) -// func createMentorRegRequest(reqFields *controllers.RegisterMentorReqFields) *http.Request { -// reqBody, _ := json.Marshal(reqFields) - -// req, _ := http.NewRequest( -// "POST", -// "/mentor/form/", -// bytes.NewReader(reqBody), -// ) - -// return req -// } - -// func createMentorUpdateRequest(reqFields *controllers.UpdateMentorReqFields) *http.Request { -// reqBody, _ := json.Marshal(reqFields) +func createMentorRegRequest(reqFields *controllers.RegisterMentorReqFields) *http.Request { + reqBody, _ := json.Marshal(reqFields) -// req, _ := http.NewRequest( -// "PUT", -// "/mentor/form/", -// bytes.NewReader(reqBody), -// ) - -// return req -// } + req, _ := http.NewRequest( + "POST", + "/mentor/form/", + bytes.NewReader(reqBody), + ) -// Mentor Registration Endpoint Disabled + return req +} -/* // Test unauthenticated request to /mentor/form/ func TestMentorRegNoAuth(t *testing.T) { testRequestNoAuth(t, "POST", "/mentor/form/") @@ -70,121 +56,120 @@ func TestMentorRegSessionHijacking(t *testing.T) { expectStatusCodeToBe(t, res, http.StatusUnauthorized) expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusUnauthorized, Message: "Login username and given username do not match."}) } -*/ -// Test unauthenticated request to /mentor/form/ [put] -// func TestMentorUpdateNoAuth(t *testing.T) { -// testRequestNoAuth(t, "PUT", "/mentor/form/") -// } +//Test unauthenticated request to /mentor/form/ [put] +func TestMentorUpdateNoAuth(t *testing.T) { + testRequestNoAuth(t, "PUT", "/mentor/form/") +} -// // Test request to /mentor/form/ [put] with invalid jwt -// func TestMentorUpdateInvalidAuth(t *testing.T) { -// testRequestInvalidAuth(t, "PUT", "/mentor/form/") -// } +// Test request to /mentor/form/ [put] with invalid jwt +func TestMentorUpdateInvalidAuth(t *testing.T) { + testRequestInvalidAuth(t, "PUT", "/mentor/form/") +} -// // Test a new user registration request to /mentor/form/ with proper authentication and input -// func tMentorRegNewUser(db *gorm.DB, t *testing.T) { -// // Test login fields -// testUsername := getTestUsername() -// testLoginFields := utils.LoginJwtFields{Username: testUsername} +// Test a new user registration request to /mentor/form/ with proper authentication and input +func tMentorRegNewUser(db *gorm.DB, t *testing.T) { + // Test login fields + testUsername := getTestUsername() + testLoginFields := utils.LoginJwtFields{Username: testUsername} -// testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) -// reqFields := controllers.RegisterMentorReqFields{Username: testUsername} + testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) + reqFields := controllers.RegisterMentorReqFields{Username: testUsername} -// req := createMentorRegRequest(&reqFields) -// req.Header.Add("Bearer", testJwt) + req := createMentorRegRequest(&reqFields) + req.Header.Add("Bearer", testJwt) -// res := executeRequest(req, db) + res := executeRequest(req, db) -// expectStatusCodeToBe(t, res, http.StatusOK) -// expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusOK, Message: "Mentor registration successful."}) -// } + expectStatusCodeToBe(t, res, http.StatusOK) + expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusOK, Message: "Mentor registration successful."}) +} -// // Test an existing user registration request to /mentor/form/ with proper authentication and input -// func tMentorRegExistingUser(db *gorm.DB, t *testing.T) { -// // Test login fields -// testUsername := getTestUsername() -// testLoginFields := utils.LoginJwtFields{Username: testUsername} +// Test an existing user registration request to /mentor/form/ with proper authentication and input +func tMentorRegExistingUser(db *gorm.DB, t *testing.T) { + // Test login fields + testUsername := getTestUsername() + testLoginFields := utils.LoginJwtFields{Username: testUsername} -// testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) -// reqFields := controllers.RegisterMentorReqFields{Username: testUsername} + testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) + reqFields := controllers.RegisterMentorReqFields{Username: testUsername} -// req := createMentorRegRequest(&reqFields) -// req.Header.Add("Bearer", testJwt) + req := createMentorRegRequest(&reqFields) + req.Header.Add("Bearer", testJwt) -// _ = executeRequest(req, db) + _ = executeRequest(req, db) -// // Execute the same request again -// req = createMentorRegRequest(&reqFields) -// req.Header.Add("Bearer", testJwt) + // Execute the same request again + req = createMentorRegRequest(&reqFields) + req.Header.Add("Bearer", testJwt) -// res := executeRequest(req, db) + res := executeRequest(req, db) -// expectStatusCodeToBe(t, res, http.StatusBadRequest) -// expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("Mentor `%s` already exists.", testUsername)}) -// } + expectStatusCodeToBe(t, res, http.StatusBadRequest) + expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("Mentor `%s` already exists.", testUsername)}) +} -// // Test an existing student registration request to /mentor/form/ with proper authentication and input -// func tMentorRegAsStudent(db *gorm.DB, t *testing.T) { -// // Test login fields -// testUsername := getTestUsername() -// testLoginFields := utils.LoginJwtFields{Username: testUsername} +// Test an existing student registration request to /mentor/form/ with proper authentication and input +func tMentorRegAsStudent(db *gorm.DB, t *testing.T) { + // Test login fields + testUsername := getTestUsername() + testLoginFields := utils.LoginJwtFields{Username: testUsername} -// testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) -// // studentFields := controllers.RegisterStudentReqFields{Username: testUsername} + testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) + // studentFields := controllers.RegisterStudentReqFields{Username: testUsername} -// // req := createStudentRegRequest(&studentFields) -// // req.Header.Add("Bearer", testJwt) + // req := createStudentRegRequest(&studentFields) + // req.Header.Add("Bearer", testJwt) -// // _ = executeRequest(req, db) -// db.Table("students").Create(&models.Student{Username: testUsername}) + // _ = executeRequest(req, db) + db.Table("students").Create(&models.Student{Username: testUsername}) -// mentorFields := controllers.RegisterMentorReqFields{Username: testUsername} -// req := createMentorRegRequest(&mentorFields) -// req.Header.Add("Bearer", testJwt) + mentorFields := controllers.RegisterMentorReqFields{Username: testUsername} + req := createMentorRegRequest(&mentorFields) + req.Header.Add("Bearer", testJwt) -// res := executeRequest(req, db) + res := executeRequest(req, db) -// expectStatusCodeToBe(t, res, http.StatusBadRequest) -// expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("The username `%s` already exists as a student.", testUsername)}) -// } + expectStatusCodeToBe(t, res, http.StatusBadRequest) + expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("The username `%s` already exists as a student.", testUsername)}) +} // Currently Disabled -// // Test requests to /mentor/form/ with proper authentication and input -// func TestMentorRegOK(t *testing.T) { -// // Set up a local test database path -// db := setTestDB() -// defer unsetTestDB() - -// // Generate a jwt secret key for testing -// setTestJwtSecretKey() -// defer unsetTestJwtSecretKey() - -// // New mentor registration test -// t.Run( -// "Test: new mentor registration.", -// func(t *testing.T) { -// tMentorRegNewUser(db, t) -// }, -// ) - -// // Existing mentor registration test -// t.Run( -// "Test: existing mentor registration.", -// func(t *testing.T) { -// tMentorRegExistingUser(db, t) -// }, -// ) - -// // Student registering as mentor test -// t.Run( -// "Test: Student registering as mentor.", -// func(t *testing.T) { -// tMentorRegAsStudent(db, t) -// }, -// ) -// } +// Test requests to /mentor/form/ with proper authentication and input +func TestMentorRegOK(t *testing.T) { + // Set up a local test database path + db := setTestDB() + defer unsetTestDB() + + // Generate a jwt secret key for testing + setTestJwtSecretKey() + defer unsetTestJwtSecretKey() + + // New mentor registration test + t.Run( + "Test: new mentor registration.", + func(t *testing.T) { + tMentorRegNewUser(db, t) + }, + ) + + // Existing mentor registration test + t.Run( + "Test: existing mentor registration.", + func(t *testing.T) { + tMentorRegExistingUser(db, t) + }, + ) + + // Student registering as mentor test + t.Run( + "Test: Student registering as mentor.", + func(t *testing.T) { + tMentorRegAsStudent(db, t) + }, + ) +} func createFetchMentorRequest() *http.Request { req, _ := http.NewRequest( diff --git a/controllers/project_reg_test.go b/controllers/project_reg_test.go index 02ed1cc6..4ad68b3e 100644 --- a/controllers/project_reg_test.go +++ b/controllers/project_reg_test.go @@ -1,11 +1,17 @@ package controllers_test import ( + "bytes" + "encoding/json" "fmt" + "gorm.io/gorm" "math/rand" + "net/http" "strings" + "testing" "github.com/kossiitkgp/kwoc-backend/v2/controllers" + "github.com/kossiitkgp/kwoc-backend/v2/utils" ) func createTestProjectRegFields(mentorUsername string, secondaryMentorUsername string) *controllers.RegisterProjectReqFields { @@ -21,154 +27,150 @@ func createTestProjectRegFields(mentorUsername string, secondaryMentorUsername s } } -/* -----------DISABLE TESTS FOR DISABLED ENDPOINTS-------------- -*/ +func createProjctRegRequest(reqFields *controllers.RegisterProjectReqFields) *http.Request { + reqBody, _ := json.Marshal(reqFields) -// func createProjctRegRequest(reqFields *controllers.RegisterProjectReqFields) *http.Request { -// reqBody, _ := json.Marshal(reqFields) + req, _ := http.NewRequest( + "POST", + "/project/", + bytes.NewReader(reqBody), + ) -// req, _ := http.NewRequest( -// "POST", -// "/project/", -// bytes.NewReader(reqBody), -// ) - -// return req -// } + return req +} // Test unauthenticated request to /project/ -// func TestProjectRegNoAuth(t *testing.T) { -// testRequestNoAuth(t, "POST", "/project/") -// } +func TestProjectRegNoAuth(t *testing.T) { + testRequestNoAuth(t, "POST", "/project/") +} -// // Test request to /project/ with invalid jwt -// func TestProjectRegInvalidAuth(t *testing.T) { -// testRequestInvalidAuth(t, "POST", "/project/") -// } +// Test request to /project/ with invalid jwt +func TestProjectRegInvalidAuth(t *testing.T) { + testRequestInvalidAuth(t, "POST", "/project/") +} // Test request to /project/ with session hijacking attempt -// func TestProjectRegSessionHijacking(t *testing.T) { -// // Generate a jwt secret key for testing -// setTestJwtSecretKey() -// defer unsetTestJwtSecretKey() +func TestProjectRegSessionHijacking(t *testing.T) { + // Generate a jwt secret key for testing + setTestJwtSecretKey() + defer unsetTestJwtSecretKey() -// testLoginFields := utils.LoginJwtFields{Username: "someuser"} + testLoginFields := utils.LoginJwtFields{Username: "someuser"} -// someuserJwt, _ := utils.GenerateLoginJwtString(testLoginFields) + someuserJwt, _ := utils.GenerateLoginJwtString(testLoginFields) -// reqFields := controllers.RegisterProjectReqFields{MentorUsername: "anotheruser"} + reqFields := controllers.RegisterProjectReqFields{MentorUsername: "anotheruser"} -// req := createProjctRegRequest(&reqFields) -// req.Header.Add("Bearer", someuserJwt) + req := createProjctRegRequest(&reqFields) + req.Header.Add("Bearer", someuserJwt) -// res := executeRequest(req, nil) + res := executeRequest(req, nil) -// expectStatusCodeToBe(t, res, http.StatusUnauthorized) -// expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusUnauthorized, Message: "Login username and mentor username do not match."}) -// } + expectStatusCodeToBe(t, res, http.StatusUnauthorized) + expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusUnauthorized, Message: "Login username and mentor username do not match."}) +} // Test a request to /project/ with non-existent mentors -// func TestProjectRegInvalidMentor(t *testing.T) { -// // Set up a local test database path -// db := setTestDB() -// defer unsetTestDB() +func TestProjectRegInvalidMentor(t *testing.T) { + // Set up a local test database path + db := setTestDB() + defer unsetTestDB() -// // Generate a jwt secret key for testing -// setTestJwtSecretKey() -// defer unsetTestJwtSecretKey() + // Generate a jwt secret key for testing + setTestJwtSecretKey() + defer unsetTestJwtSecretKey() -// // Register a test mentor -// testUsername := getTestUsername() -// testLoginFields := utils.LoginJwtFields{Username: testUsername} + // Register a test mentor + testUsername := getTestUsername() + testLoginFields := utils.LoginJwtFields{Username: testUsername} -// testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) + testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) -// // --- TEST PROJECT REGISTRATION WITH INVALID PRIMARY MENTOR --- -// projectReqFields := createTestProjectRegFields(testUsername, "") + // --- TEST PROJECT REGISTRATION WITH INVALID PRIMARY MENTOR --- + projectReqFields := createTestProjectRegFields(testUsername, "") -// projectReq := createProjctRegRequest(projectReqFields) -// projectReq.Header.Add("Bearer", testJwt) + projectReq := createProjctRegRequest(projectReqFields) + projectReq.Header.Add("Bearer", testJwt) -// projectRes := executeRequest(projectReq, db) + projectRes := executeRequest(projectReq, db) -// expectStatusCodeToBe(t, projectRes, http.StatusBadRequest) -// expectResponseJSONBodyToBe(t, projectRes, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("Error: Mentor `%s` does not exist.", testUsername)}) -// // --- TEST PROJECT REGISTRATION WITH INVALID PRIMARY MENTOR --- -// } + expectStatusCodeToBe(t, projectRes, http.StatusBadRequest) + expectResponseJSONBodyToBe(t, projectRes, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("Error: Mentor `%s` does not exist.", testUsername)}) + // --- TEST PROJECT REGISTRATION WITH INVALID PRIMARY MENTOR --- +} // Test a new project registration request to /project/ with proper authentication and input -// func tProjectRegNew(db *gorm.DB, testUsername string, testJwt string, t *testing.T) { -// projectReqFields := createTestProjectRegFields(testUsername, "") +func tProjectRegNew(db *gorm.DB, testUsername string, testJwt string, t *testing.T) { + projectReqFields := createTestProjectRegFields(testUsername, "") -// projectReq := createProjctRegRequest(projectReqFields) -// projectReq.Header.Add("Bearer", testJwt) + projectReq := createProjctRegRequest(projectReqFields) + projectReq.Header.Add("Bearer", testJwt) -// projectRes := executeRequest(projectReq, db) + projectRes := executeRequest(projectReq, db) -// expectStatusCodeToBe(t, projectRes, http.StatusOK) -// expectResponseJSONBodyToBe(t, projectRes, utils.HTTPMessage{StatusCode: http.StatusOK, Message: "Success."}) -// } + expectStatusCodeToBe(t, projectRes, http.StatusOK) + expectResponseJSONBodyToBe(t, projectRes, utils.HTTPMessage{StatusCode: http.StatusOK, Message: "Success."}) +} -// // Test an existing project registration request to /project/ with proper authentication and input -// func tProjectRegExisting(db *gorm.DB, testUsername string, testJwt string, t *testing.T) { -// projectReqFields := createTestProjectRegFields(testUsername, "") +// Test an existing project registration request to /project/ with proper authentication and input +func tProjectRegExisting(db *gorm.DB, testUsername string, testJwt string, t *testing.T) { + projectReqFields := createTestProjectRegFields(testUsername, "") -// projectReq := createProjctRegRequest(projectReqFields) -// projectReq.Header.Add("Bearer", testJwt) + projectReq := createProjctRegRequest(projectReqFields) + projectReq.Header.Add("Bearer", testJwt) -// _ = executeRequest(projectReq, db) + _ = executeRequest(projectReq, db) -// // Execute the same request again -// projectReq = createProjctRegRequest(projectReqFields) -// projectReq.Header.Add("Bearer", testJwt) + // Execute the same request again + projectReq = createProjctRegRequest(projectReqFields) + projectReq.Header.Add("Bearer", testJwt) -// projectRes := executeRequest(projectReq, db) + projectRes := executeRequest(projectReq, db) -// expectStatusCodeToBe(t, projectRes, http.StatusBadRequest) -// expectResponseJSONBodyToBe(t, projectRes, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("Error: Project `%s` already exists.", projectReqFields.RepoLink)}) -// } + expectStatusCodeToBe(t, projectRes, http.StatusBadRequest) + expectResponseJSONBodyToBe(t, projectRes, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("Error: Project `%s` already exists.", projectReqFields.RepoLink)}) +} // Test requests to /project/ with proper authentication and input -// func TestProjectRegOK(t *testing.T) { -// // Set up a local test database path -// db := setTestDB() -// defer unsetTestDB() - -// // Generate a jwt secret key for testing -// setTestJwtSecretKey() -// defer unsetTestJwtSecretKey() - -// // Register a test mentor -// testUsername := getTestUsername() -// testLoginFields := utils.LoginJwtFields{ -// Username: testUsername, -// } - -// testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) - -// mentorReqFields := controllers.RegisterMentorReqFields{ -// Username: testUsername, -// Email: "testuser@example.com", -// } - -// mentorReq := createMentorRegRequest(&mentorReqFields) -// mentorReq.Header.Add("Bearer", testJwt) -// _ = executeRequest(mentorReq, db) - -// // New project registration test -// t.Run( -// "Test: new project registration.", -// func(t *testing.T) { -// tProjectRegNew(db, testUsername, testJwt, t) -// }, -// ) - -// // Existing project registration test -// t.Run( -// "Test: existing project registration.", -// func(t *testing.T) { -// tProjectRegExisting(db, testUsername, testJwt, t) -// }, -// ) -// } +func TestProjectRegOK(t *testing.T) { + // Set up a local test database path + db := setTestDB() + defer unsetTestDB() + + // Generate a jwt secret key for testing + setTestJwtSecretKey() + defer unsetTestJwtSecretKey() + + // Register a test mentor + testUsername := getTestUsername() + testLoginFields := utils.LoginJwtFields{ + Username: testUsername, + } + + testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) + + mentorReqFields := controllers.RegisterMentorReqFields{ + Username: testUsername, + Email: "testuser@example.com", + } + + mentorReq := createMentorRegRequest(&mentorReqFields) + mentorReq.Header.Add("Bearer", testJwt) + _ = executeRequest(mentorReq, db) + + // New project registration test + t.Run( + "Test: new project registration.", + func(t *testing.T) { + tProjectRegNew(db, testUsername, testJwt, t) + }, + ) + + // Existing project registration test + t.Run( + "Test: existing project registration.", + func(t *testing.T) { + tProjectRegExisting(db, testUsername, testJwt, t) + }, + ) +} diff --git a/controllers/student_test.go b/controllers/student_test.go index 701a94e3..abe9bec3 100644 --- a/controllers/student_test.go +++ b/controllers/student_test.go @@ -17,152 +17,148 @@ import ( "gorm.io/gorm" ) -/* -----------DISABLE TESTS FOR DISABLED ENDPOINTS-------------- -*/ - -// func createStudentRegRequest(reqFields *controllers.RegisterStudentReqFields) *http.Request { -// reqBody, _ := json.Marshal(reqFields) +func createStudentRegRequest(reqFields *controllers.RegisterStudentReqFields) *http.Request { + reqBody, _ := json.Marshal(reqFields) -// req, _ := http.NewRequest( -// "POST", -// "/student/form/", -// bytes.NewReader(reqBody), -// ) + req, _ := http.NewRequest( + "POST", + "/student/form/", + bytes.NewReader(reqBody), + ) -// return req -// } + return req +} // Test unauthenticated request to /student/form/ -// func TestStudentRegNoAuth(t *testing.T) { -// testRequestNoAuth(t, "POST", "/student/form/") -// } +func TestStudentRegNoAuth(t *testing.T) { + testRequestNoAuth(t, "POST", "/student/form/") +} -// // Test request to /student/form/ with invalid jwt -// func TestStudentRegInvalidAuth(t *testing.T) { -// testRequestInvalidAuth(t, "POST", "/student/form/") -// } +// Test request to /student/form/ with invalid jwt +func TestStudentRegInvalidAuth(t *testing.T) { + testRequestInvalidAuth(t, "POST", "/student/form/") +} // Test request to /student/form/ with session hijacking attempt -// func TestStudentRegSessionHijacking(t *testing.T) { -// // Generate a jwt secret key for testing -// setTestJwtSecretKey() +func TestStudentRegSessionHijacking(t *testing.T) { + // Generate a jwt secret key for testing + setTestJwtSecretKey() -// testLoginFields := utils.LoginJwtFields{Username: "someuser"} + testLoginFields := utils.LoginJwtFields{Username: "someuser"} -// someuserJwt, _ := utils.GenerateLoginJwtString(testLoginFields) + someuserJwt, _ := utils.GenerateLoginJwtString(testLoginFields) -// reqFields := controllers.RegisterStudentReqFields{Username: "anotheruser"} + reqFields := controllers.RegisterStudentReqFields{Username: "anotheruser"} -// req := createStudentRegRequest(&reqFields) -// req.Header.Add("Bearer", someuserJwt) + req := createStudentRegRequest(&reqFields) + req.Header.Add("Bearer", someuserJwt) -// res := executeRequest(req, nil) + res := executeRequest(req, nil) -// expectStatusCodeToBe(t, res, http.StatusUnauthorized) -// expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusUnauthorized, Message: "Login username and given username do not match."}) -// } + expectStatusCodeToBe(t, res, http.StatusUnauthorized) + expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusUnauthorized, Message: "Login username and given username do not match."}) +} -// // Test a new user registration request to /student/form/ with proper authentication and input -// func tStudentRegNewUser(db *gorm.DB, t *testing.T) { -// // Test login fields -// testUsername := getTestUsername() -// testLoginFields := utils.LoginJwtFields{Username: testUsername} +// Test a new user registration request to /student/form/ with proper authentication and input +func tStudentRegNewUser(db *gorm.DB, t *testing.T) { + // Test login fields + testUsername := getTestUsername() + testLoginFields := utils.LoginJwtFields{Username: testUsername} -// testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) -// reqFields := controllers.RegisterStudentReqFields{Username: testUsername} + testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) + reqFields := controllers.RegisterStudentReqFields{Username: testUsername} -// req := createStudentRegRequest(&reqFields) -// req.Header.Add("Bearer", testJwt) + req := createStudentRegRequest(&reqFields) + req.Header.Add("Bearer", testJwt) -// res := executeRequest(req, db) + res := executeRequest(req, db) -// expectStatusCodeToBe(t, res, http.StatusOK) -// expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusOK, Message: "Student registration successful."}) -// } + expectStatusCodeToBe(t, res, http.StatusOK) + expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusOK, Message: "Student registration successful."}) +} -// // Test an existing user registration request to /student/form/ with proper authentication and input -// func tStudentRegExistingUser(db *gorm.DB, t *testing.T) { -// // Test login fields -// testUsername := getTestUsername() -// testLoginFields := utils.LoginJwtFields{Username: testUsername} +// Test an existing user registration request to /student/form/ with proper authentication and input +func tStudentRegExistingUser(db *gorm.DB, t *testing.T) { + // Test login fields + testUsername := getTestUsername() + testLoginFields := utils.LoginJwtFields{Username: testUsername} -// testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) -// reqFields := controllers.RegisterStudentReqFields{Username: testUsername} + testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) + reqFields := controllers.RegisterStudentReqFields{Username: testUsername} -// req := createStudentRegRequest(&reqFields) -// req.Header.Add("Bearer", testJwt) + req := createStudentRegRequest(&reqFields) + req.Header.Add("Bearer", testJwt) -// _ = executeRequest(req, db) + _ = executeRequest(req, db) -// // Execute the same request again -// req = createStudentRegRequest(&reqFields) -// req.Header.Add("Bearer", testJwt) + // Execute the same request again + req = createStudentRegRequest(&reqFields) + req.Header.Add("Bearer", testJwt) -// res := executeRequest(req, db) + res := executeRequest(req, db) -// expectStatusCodeToBe(t, res, http.StatusBadRequest) -// expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("Student `%s` already exists.", testUsername)}) -// } + expectStatusCodeToBe(t, res, http.StatusBadRequest) + expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("Student `%s` already exists.", testUsername)}) +} -// // Test an existing mentor registration request to /student/form/ with proper authentication and input -// func tStudentRegAsMentor(db *gorm.DB, t *testing.T) { -// // Test login fields -// testUsername := getTestUsername() -// testLoginFields := utils.LoginJwtFields{Username: testUsername} +// Test an existing mentor registration request to /student/form/ with proper authentication and input +func tStudentRegAsMentor(db *gorm.DB, t *testing.T) { + // Test login fields + testUsername := getTestUsername() + testLoginFields := utils.LoginJwtFields{Username: testUsername} -// testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) -// mentorFields := controllers.RegisterMentorReqFields{Username: testUsername} + testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) + mentorFields := controllers.RegisterMentorReqFields{Username: testUsername} -// req := createMentorRegRequest(&mentorFields) -// req.Header.Add("Bearer", testJwt) + req := createMentorRegRequest(&mentorFields) + req.Header.Add("Bearer", testJwt) -// _ = executeRequest(req, db) + _ = executeRequest(req, db) -// studentsFields := controllers.RegisterStudentReqFields{Username: testUsername} -// req = createStudentRegRequest(&studentsFields) -// req.Header.Add("Bearer", testJwt) + studentsFields := controllers.RegisterStudentReqFields{Username: testUsername} + req = createStudentRegRequest(&studentsFields) + req.Header.Add("Bearer", testJwt) -// res := executeRequest(req, db) + res := executeRequest(req, db) -// expectStatusCodeToBe(t, res, http.StatusBadRequest) -// expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("The username `%s` already exists as a mentor.", testUsername)}) -// } + expectStatusCodeToBe(t, res, http.StatusBadRequest) + expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("The username `%s` already exists as a mentor.", testUsername)}) +} // Test requests to /student/form/ with proper authentication and input -// func TestStudentRegOK(t *testing.T) { -// // Set up a local test database path -// db := setTestDB() -// defer unsetTestDB() - -// // Generate a jwt secret key for testing -// setTestJwtSecretKey() -// defer unsetTestJwtSecretKey() - -// // New student registration test -// t.Run( -// "Test: new student registration.", -// func(t *testing.T) { -// tStudentRegNewUser(db, t) -// }, -// ) - -// // Existing student registration test -// t.Run( -// "Test: existing student registration.", -// func(t *testing.T) { -// tStudentRegExistingUser(db, t) -// }, -// ) - -// // Mentor registering as student test -// t.Run( -// "Test: Mentor registering as student.", -// func(t *testing.T) { -// tStudentRegAsMentor(db, t) -// }, -// ) -// } +func TestStudentRegOK(t *testing.T) { + // Set up a local test database path + db := setTestDB() + defer unsetTestDB() + + // Generate a jwt secret key for testing + setTestJwtSecretKey() + defer unsetTestJwtSecretKey() + + // New student registration test + t.Run( + "Test: new student registration.", + func(t *testing.T) { + tStudentRegNewUser(db, t) + }, + ) + + // Existing student registration test + t.Run( + "Test: existing student registration.", + func(t *testing.T) { + tStudentRegExistingUser(db, t) + }, + ) + + // Mentor registering as student test + t.Run( + "Test: Mentor registering as student.", + func(t *testing.T) { + tStudentRegAsMentor(db, t) + }, + ) +} func createStudentBlogLinkRequest(reqFields *controllers.StudentBlogLinkReqFields) *http.Request { reqBody, _ := json.Marshal(reqFields) diff --git a/server/router.go b/server/router.go index 7913b992..ac6f6af2 100644 --- a/server/router.go +++ b/server/router.go @@ -16,7 +16,7 @@ var ErrRouteNotFound = errors.New("route not found") var ErrMethodNotAllowed = errors.New("method not allowed") // Setup up mux routes and router -func NewRouter(db *gorm.DB) *mux.Router { +func NewRouter(db *gorm.DB, testMode bool) *mux.Router { router := mux.NewRouter().StrictSlash(true) router.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { utils.LogErrAndRespond(r, w, ErrRouteNotFound, "404 Not Found.", http.StatusNotFound) @@ -32,6 +32,11 @@ func NewRouter(db *gorm.DB) *mux.Router { routes := getRoutes(app) for _, route := range routes { + // skip disabled routes + if !testMode && route.disabled { + continue + } + var handler http.Handler // logger middleware to log incoming requests diff --git a/server/routes.go b/server/routes.go index 0968b3b0..d47b6b10 100644 --- a/server/routes.go +++ b/server/routes.go @@ -12,6 +12,7 @@ type Route struct { Method string Pattern string HandlerFunc http.HandlerFunc + disabled bool } func getRoutes(app *middleware.App) []Route { @@ -21,132 +22,154 @@ func getRoutes(app *middleware.App) []Route { "GET", "/api/", controllers.Index, + false, }, { "OAuth", "POST", "/oauth/", middleware.WrapApp(app, controllers.OAuth), + false, }, { "Profile", "GET", "/profile/", middleware.WithLogin(middleware.WrapApp(app, controllers.FetchProfile)), + false, }, { "Fetch Student Details", "GET", "/student/", middleware.WithLogin(middleware.WrapApp(app, controllers.GetStudentDetails)), + false, }, { "Fetch Mentor Details", "GET", "/mentor/", middleware.WithLogin(middleware.WrapApp(app, controllers.GetMentorDetails)), + false, + }, + { + "Student Registration", + "POST", + "/student/form/", + middleware.WithLogin(middleware.WrapApp(app, controllers.RegisterStudent)), + true, }, - // { - // "Student Registration", - // "POST", - // "/student/form/", - // middleware.WithLogin(middleware.WrapApp(app, controllers.RegisterStudent)), - // }, { "Update Student Details", "PUT", "/student/form/", middleware.WithLogin(middleware.WrapApp(app, controllers.UpdateStudentDetails)), + false, }, { "Student Blog Submission", "POST", "/student/bloglink/", middleware.WithLogin(middleware.WrapApp(app, controllers.StudentBlogLink)), + false, }, { "Student Dashboard", "GET", "/student/dashboard/", middleware.WithLogin(middleware.WrapApp(app, controllers.FetchStudentDashboard)), + false, + }, + { + "Mentor Registration", + "POST", + "/mentor/form/", + middleware.WithLogin(middleware.WrapApp(app, controllers.RegisterMentor)), + true, }, - // { - // "Mentor Registration", - // "POST", - // "/mentor/form/", - // middleware.WithLogin(middleware.WrapApp(app, controllers.RegisterMentor)), - // }, { "Update Mentor Details", "PUT", "/mentor/form/", middleware.WithLogin(middleware.WrapApp(app, controllers.UpdateMentorDetails)), + false, }, { "Fetch All Mentors", "GET", "/mentor/all/", middleware.WithLogin(middleware.WrapApp(app, controllers.FetchAllMentors)), + false, }, { "Mentor Dashboard", "GET", "/mentor/dashboard/", middleware.WithLogin(middleware.WrapApp(app, controllers.FetchMentorDashboard)), + false, }, { "HealthCheck", "GET", "/healthcheck/", middleware.WrapApp(app, controllers.HealthCheck), + false, }, { "Ping", "GET", "/healthcheck/ping/", controllers.Ping, + false, + }, + { + "Project Registration", + "POST", + "/project/", + middleware.WithLogin(middleware.WrapApp(app, controllers.RegisterProject)), + true, }, - // { - // "Project Registration", - // "POST", - // "/project/", - // middleware.WithLogin(middleware.WrapApp(app, controllers.RegisterProject)), - // }, { "Fetch All Projects", "GET", "/project/", middleware.WrapApp(app, controllers.FetchAllProjects), + false, }, { "Update Project Details", "PUT", "/project/", middleware.WithLogin(middleware.WrapApp(app, controllers.UpdateProject)), + false, }, { "Fetch Project Details", "GET", "/project/{id}", middleware.WithLogin(middleware.WrapApp(app, controllers.FetchProjectDetails)), + false, }, { "Fetch All Students Stats", "GET", "/stats/students/", middleware.WrapApp(app, controllers.FetchAllStudentStats), + false, }, { "Fetch Overall Stats", "GET", "/stats/overall/", middleware.WrapApp(app, controllers.FetchOverallStats), + false, }, { "Fetch Project Stats", "GET", "/stats/projects/", middleware.WrapApp(app, controllers.FetchAllProjectStats), + false, }, } } From f96995c3fc06b621d23880ddf24fd19aa7724248 Mon Sep 17 00:00:00 2001 From: Devansh-bit Date: Sun, 17 Dec 2023 22:56:04 +0530 Subject: [PATCH 11/13] style: remove unused comments --- controllers/mentor_test.go | 6 ------ controllers/project_update_test.go | 5 +---- controllers/student_test.go | 5 ----- 3 files changed, 1 insertion(+), 15 deletions(-) diff --git a/controllers/mentor_test.go b/controllers/mentor_test.go index 16b62967..bafc4810 100644 --- a/controllers/mentor_test.go +++ b/controllers/mentor_test.go @@ -116,12 +116,7 @@ func tMentorRegAsStudent(db *gorm.DB, t *testing.T) { testLoginFields := utils.LoginJwtFields{Username: testUsername} testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) - // studentFields := controllers.RegisterStudentReqFields{Username: testUsername} - // req := createStudentRegRequest(&studentFields) - // req.Header.Add("Bearer", testJwt) - - // _ = executeRequest(req, db) db.Table("students").Create(&models.Student{Username: testUsername}) mentorFields := controllers.RegisterMentorReqFields{Username: testUsername} @@ -134,7 +129,6 @@ func tMentorRegAsStudent(db *gorm.DB, t *testing.T) { expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("The username `%s` already exists as a student.", testUsername)}) } -// Currently Disabled // Test requests to /mentor/form/ with proper authentication and input func TestMentorRegOK(t *testing.T) { diff --git a/controllers/project_update_test.go b/controllers/project_update_test.go index be553388..93a26d13 100644 --- a/controllers/project_update_test.go +++ b/controllers/project_update_test.go @@ -80,10 +80,7 @@ func tProjectUpdateNonExistent(db *gorm.DB, testUsername string, testJwt string, func tProjectUpdateExistent(db *gorm.DB, testUsername string, testJwt string, t *testing.T) { // Register a test project projRegFields := createTestProjectRegFields(testUsername, "") - // projRegReq := createProjctRegRequest(projRegFields) - // projRegReq.Header.Add("Bearer", testJwt) - - // _ = executeRequest(projRegReq, db) + db.Create(&models.Project{ Name: projRegFields.Name, Description: projRegFields.Description, diff --git a/controllers/student_test.go b/controllers/student_test.go index abe9bec3..94004a87 100644 --- a/controllers/student_test.go +++ b/controllers/student_test.go @@ -210,12 +210,7 @@ func tStudentBlogLinkExistingUser(db *gorm.DB, t *testing.T) { testLoginFields := utils.LoginJwtFields{Username: testUsername} testJwt, _ := utils.GenerateLoginJwtString(testLoginFields) - // reqFieldsReg := controllers.RegisterStudentReqFields{Username: testUsername} - // req := createStudentRegRequest(&reqFieldsReg) - // req.Header.Add("Bearer", testJwt) - - // _ = executeRequest(req, db) db.Table("students").Create(&models.Student{Username: testUsername}) // Execute the bloglink request From c022f5d6a72d7a8461f01563c6d5eebc02a68d78 Mon Sep 17 00:00:00 2001 From: Devansh-bit Date: Sun, 17 Dec 2023 22:57:11 +0530 Subject: [PATCH 12/13] linting --- controllers/mentor_test.go | 1 - controllers/project_update_test.go | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/controllers/mentor_test.go b/controllers/mentor_test.go index bafc4810..7a152e7d 100644 --- a/controllers/mentor_test.go +++ b/controllers/mentor_test.go @@ -129,7 +129,6 @@ func tMentorRegAsStudent(db *gorm.DB, t *testing.T) { expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("The username `%s` already exists as a student.", testUsername)}) } - // Test requests to /mentor/form/ with proper authentication and input func TestMentorRegOK(t *testing.T) { // Set up a local test database path diff --git a/controllers/project_update_test.go b/controllers/project_update_test.go index 93a26d13..fca3c0d6 100644 --- a/controllers/project_update_test.go +++ b/controllers/project_update_test.go @@ -80,7 +80,7 @@ func tProjectUpdateNonExistent(db *gorm.DB, testUsername string, testJwt string, func tProjectUpdateExistent(db *gorm.DB, testUsername string, testJwt string, t *testing.T) { // Register a test project projRegFields := createTestProjectRegFields(testUsername, "") - + db.Create(&models.Project{ Name: projRegFields.Name, Description: projRegFields.Description, From c94697c1f53654eda059dd79a3cbe240b0b03e57 Mon Sep 17 00:00:00 2001 From: Devansh-bit Date: Sun, 17 Dec 2023 23:21:51 +0530 Subject: [PATCH 13/13] fix: implement requested change --- controllers/project_update.go | 10 ---------- controllers/project_update_test.go | 15 ++------------- 2 files changed, 2 insertions(+), 23 deletions(-) diff --git a/controllers/project_update.go b/controllers/project_update.go index 8dc1ec82..6cd5b559 100644 --- a/controllers/project_update.go +++ b/controllers/project_update.go @@ -114,16 +114,6 @@ func UpdateProject(w http.ResponseWriter, r *http.Request) { ) return } - if tx.Error == gorm.ErrRecordNotFound { - utils.LogErrAndRespond( - r, - w, - err, - fmt.Sprintf("Secondary mentor `%s` does not exist.", reqFields.SecondaryMentorUsername), - http.StatusBadRequest, - ) - return - } } updatedProj := &models.Project{ diff --git a/controllers/project_update_test.go b/controllers/project_update_test.go index fca3c0d6..237cf609 100644 --- a/controllers/project_update_test.go +++ b/controllers/project_update_test.go @@ -110,24 +110,13 @@ func tProjectUpdateExistent(db *gorm.DB, testUsername string, testJwt string, t ReadmeLink: "http://NewRepoLink/README", } - // Test with invalid new secondary mentor - projUpdateFields.SecondaryMentorUsername = "non-existent" - - req := createProjectUpdateRequest(projUpdateFields) - req.Header.Add("Bearer", testJwt) - - res := executeRequest(req, db) - - expectStatusCodeToBe(t, res, http.StatusBadRequest) - expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("Secondary mentor `%s` does not exist.", projUpdateFields.SecondaryMentorUsername)}) - // Test with a valid new secondary mentor projUpdateFields.SecondaryMentorUsername = "testSecondary" - req = createProjectUpdateRequest(projUpdateFields) + req := createProjectUpdateRequest(projUpdateFields) req.Header.Add("Bearer", testJwt) - res = executeRequest(req, db) + res := executeRequest(req, db) expectStatusCodeToBe(t, res, http.StatusOK) expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusOK, Message: "Project successfully updated."})