Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Implement fixes for several failing tests #179

Merged
merged 12 commits into from
Dec 17, 2023
2 changes: 1 addition & 1 deletion cmd/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 == "" {
Expand Down
2 changes: 1 addition & 1 deletion controllers/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
41 changes: 29 additions & 12 deletions controllers/mentor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"gorm.io/gorm"
"net/http"
"reflect"
"strings"
Expand All @@ -12,8 +13,6 @@ import (
"github.com/kossiitkgp/kwoc-backend/v2/controllers"
"github.com/kossiitkgp/kwoc-backend/v2/models"
"github.com/kossiitkgp/kwoc-backend/v2/utils"

"gorm.io/gorm"
)

func createMentorRegRequest(reqFields *controllers.RegisterMentorReqFields) *http.Request {
Expand Down Expand Up @@ -58,6 +57,16 @@ func TestMentorRegSessionHijacking(t *testing.T) {
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) {
// Test login fields
Expand Down Expand Up @@ -107,15 +116,11 @@ 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}
req = createMentorRegRequest(&mentorFields)
req := createMentorRegRequest(&mentorFields)
req.Header.Add("Bearer", testJwt)

res := executeRequest(req, db)
Expand Down Expand Up @@ -314,23 +319,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,
Expand Down Expand Up @@ -362,7 +380,6 @@ func TestMentorDashboardOK(t *testing.T) {
})
}

db.Table("projects").Create(testProjects)
db.Table("students").Create(modelStudents)

testMentor := controllers.MentorDashboard{
Expand All @@ -388,8 +405,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/")
}
}
51 changes: 35 additions & 16 deletions controllers/project_fetch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -143,42 +152,52 @@ 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)
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]
// Generate a jwt secret key for testing
setTestJwtSecretKey()
defer unsetTestJwtSecretKey()

_ = db.Table("projects").Create(&testProj)
// Test login fields
testUsername := getTestUsername()
testLoginFields := utils.LoginJwtFields{Username: testUsername}

req := createFetchProjDetailsRequest(1)
res := executeRequest(req, db)

expectStatusCodeToBe(t, res, http.StatusBadRequest)
expectResponseJSONBodyToBe(t, res, utils.HTTPMessage{StatusCode: http.StatusBadRequest, Message: fmt.Sprintf("Project with id `%d` does not exist.", 1)})
}

// 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
Expand Down
27 changes: 13 additions & 14 deletions controllers/project_reg_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,16 @@ 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"

"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()),
Expand All @@ -40,6 +27,18 @@ func createTestProjectRegFields(mentorUsername string, secondaryMentorUsername s
}
}

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/")
Expand Down
2 changes: 1 addition & 1 deletion controllers/project_update.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,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,
Expand Down
65 changes: 28 additions & 37 deletions controllers/project_update_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,23 @@ 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,
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{
Expand All @@ -97,24 +110,13 @@ func tProjectUpdateExistent(db *gorm.DB, testUsername string, testJwt string, t
ReadmeLink: "http://NewRepoLink/README",
}

// Test with invalid new secondary mentor
harshkhandeparkar marked this conversation as resolved.
Show resolved Hide resolved
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."})
Expand Down Expand Up @@ -155,14 +157,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 != "[email protected]" {
t.Errorf("Project secondary mentor email did not get updated\n Expected: `%s`. Received: `%s`", "[email protected]", updatedProj.SecondaryMentor.Email)
}
}

// Test requests to /project/ with proper authentication and input
Expand All @@ -188,26 +182,23 @@ func TestProjectUpdateOK(t *testing.T) {
Email: "[email protected]",
}

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: "[email protected]",
}

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(
Expand Down
8 changes: 2 additions & 6 deletions controllers/student_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,16 +210,12 @@ 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
reqFields := controllers.StudentBlogLinkReqFields{Username: testUsername, BlogLink: "https://grugbrain.dev/"}
req = createStudentBlogLinkRequest(&reqFields)
req := createStudentBlogLinkRequest(&reqFields)
req.Header.Add("Bearer", testJwt)

res := executeRequest(req, db)
Expand Down
Loading
Loading