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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module courses-microservice
go 1.24.1

require (
github.com/DATA-DOG/go-sqlmock v1.5.2
github.com/Masterminds/squirrel v1.5.4
github.com/gin-contrib/cors v1.7.5
github.com/gin-gonic/gin v1.10.0
Expand Down
3 changes: 3 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0=
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=
github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM=
Expand Down Expand Up @@ -96,6 +98,7 @@ github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8Hm
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
Expand Down
2 changes: 1 addition & 1 deletion internal/handlers/assignments/assignments_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ func TestAddAttachment_Success(t *testing.T) {

_, err = io.Copy(fileWriter, strings.NewReader("test file content"))
assert.NoError(t, err)
writer.Close()
_ = writer.Close()

router := createRouterWithJWT(presetUserID.String())

Expand Down
2 changes: 1 addition & 1 deletion internal/handlers/courses/courses_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ func TestAddAttachment_Success(t *testing.T) {

_, err = io.Copy(fileWriter, strings.NewReader("test file content"))
assert.NoError(t, err)
writer.Close()
_ = writer.Close()

router := createRouterWithJWT(presetUserID.String())

Expand Down
2 changes: 1 addition & 1 deletion internal/handlers/modules/modules_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ func TestAddAttachment_Success(t *testing.T) {

_, err = io.Copy(fileWriter, strings.NewReader("test file content"))
assert.NoError(t, err)
writer.Close()
_ = writer.Close()

router := createRouterWithJWT(presetUserID.String())

Expand Down
96 changes: 96 additions & 0 deletions internal/middleware/jwt_auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package middleware_test

import (
"courses-microservice/config"
"courses-microservice/internal/errors"
"courses-microservice/internal/middleware"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -104,3 +105,98 @@ func TestJWTAuthMiddleware_WithErrorHandler(t *testing.T) {
assert.Contains(t, w.Body.String(), "Invalid JWT token")
})
}

func TestErrorHandlerMiddleware_NoErrors(t *testing.T) {
router := gin.New()
router.Use(middleware.ErrorHandlerMiddleware())
router.GET("/test", func(c *gin.Context) {
c.String(http.StatusOK, "ok")
})

resp := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/test", nil)
router.ServeHTTP(resp, req)

assert.Equal(t, http.StatusOK, resp.Code)
assert.Equal(t, "ok", resp.Body.String())
}

func TestErrorHandlerMiddleware_ErrorAlreadyWritten(t *testing.T) {
router := gin.New()
router.Use(middleware.ErrorHandlerMiddleware())
router.GET("/test", func(c *gin.Context) {
c.String(http.StatusBadRequest, "bad")
_ = c.Error(errors.NewBadRequestError("won't be handled"))
})

resp := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/test", nil)
router.ServeHTTP(resp, req)

assert.Equal(t, http.StatusBadRequest, resp.Code)
assert.Equal(t, "bad", resp.Body.String())
}

func TestErrorHandlerMiddleware_KnownErrors(t *testing.T) {
tests := []struct {
name string
err error
statusCode int
message string
}{
{
name: "BadRequestError",
err: errors.NewBadRequestError("bad request"),
statusCode: http.StatusBadRequest,
message: "bad request",
},
{
name: "UnauthorizedError",
err: errors.NewUnauthorizedError("unauthorized"),
statusCode: http.StatusUnauthorized,
message: "unauthorized",
},
{
name: "ForbiddenError",
err: errors.NewForbiddenError("forbidden"),
statusCode: http.StatusForbidden,
message: "forbidden",
},
{
name: "NotFoundError",
err: errors.NewNotFoundError("not found"),
statusCode: http.StatusNotFound,
message: "not found",
},
{
name: "ConflictError",
err: errors.NewConflictError("conflict"),
statusCode: http.StatusConflict,
message: "conflict",
},
{
name: "InternalServerError",
err: errors.NewInternalServerError("internal issue"),
statusCode: http.StatusInternalServerError,
message: "internal issue",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
router := gin.New()
router.Use(middleware.ErrorHandlerMiddleware())
router.GET("/test", func(c *gin.Context) {
_ = c.Error(tt.err)
})

req := httptest.NewRequest(http.MethodGet, "/test", nil)
resp := httptest.NewRecorder()

router.ServeHTTP(resp, req)

assert.Equal(t, tt.statusCode, resp.Code)
assert.Contains(t, resp.Body.String(), tt.message)
})
}
}
127 changes: 127 additions & 0 deletions internal/repository/assignments_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,133 @@ func TestGetAssignmentByID_NotFound(t *testing.T) {
assert.NoError(t, mock.ExpectationsWereMet())
}

func TestCreateOrUpdateAssignmentSubmission_Success(t *testing.T) {
mock, repo := setupMockRepoForAssignments(t)

assignmentID := uuid.New()
studentID := uuid.New()
submission := &models.AssignmentSubmission{
Text: "test submission",
Attachment: "file.png",
Comment: "Looks good",
Score: 90,
Reviewed: true,
IgnoreDeadline: false,
}

// Mock expected query and returned row
mock.ExpectQuery("INSERT INTO assignment_submissions").
WithArgs(
assignmentID,
studentID,
submission.Text,
submission.Attachment,
submission.Comment,
submission.Score,
submission.Reviewed,
submission.IgnoreDeadline,
).
WillReturnRows(pgxmock.NewRows([]string{"id", "created_at", "updated_at"}).
AddRow(uuid.New(), time.Now(), time.Now()))

err := repo.CreateOrUpdateAssignmentSubmission(assignmentID, studentID, submission)
assert.NoError(t, err)
assert.NoError(t, mock.ExpectationsWereMet())
}

func TestGetAssignmentSubmissionByID_Success(t *testing.T) {
mock, repo := setupMockRepoForAssignments(t)

submissionID := uuid.New()
expected := &models.AssignmentSubmission{
Id: submissionID,
AssignmentId: uuid.New(),
StudentId: uuid.New(),
Text: "Great work!",
Attachment: "submission.pdf",
Comment: "Reviewed",
Score: 95,
Reviewed: true,
IgnoreDeadline: false,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}

mock.ExpectQuery("SELECT id, assignment_id, student_id, text, attachment, comment").
WithArgs(submissionID).
WillReturnRows(
pgxmock.NewRows([]string{
"id", "assignment_id", "student_id", "text", "attachment", "comment", "score",
"reviewed", "ignore_deadline", "created_at", "updated_at",
}).AddRow(
expected.Id,
expected.AssignmentId,
expected.StudentId,
expected.Text,
expected.Attachment,
expected.Comment,
expected.Score,
expected.Reviewed,
expected.IgnoreDeadline,
expected.CreatedAt,
expected.UpdatedAt,
),
)

result, err := repo.GetAssignmentSubmissionByID(submissionID)
assert.NoError(t, err)
assert.Equal(t, expected.Id, result.Id)
assert.Equal(t, expected.Text, result.Text)
assert.NoError(t, mock.ExpectationsWereMet())
}

func TestGetAssignmentSubmissionByStudent_Success(t *testing.T) {
mock, repo := setupMockRepoForAssignments(t)

assignmentID := uuid.New()
studentID := uuid.New()
expected := &models.AssignmentSubmission{
Id: uuid.New(),
AssignmentId: assignmentID,
StudentId: studentID,
Text: "My submission",
Attachment: "homework.docx",
Comment: "Looks good",
Score: 88,
Reviewed: true,
IgnoreDeadline: false,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}

mock.ExpectQuery("SELECT id, assignment_id, student_id, text, attachment, comment").
WithArgs(assignmentID, studentID).
WillReturnRows(
pgxmock.NewRows([]string{
"id", "assignment_id", "student_id", "text", "attachment", "comment", "score",
"reviewed", "ignore_deadline", "created_at", "updated_at",
}).AddRow(
expected.Id,
expected.AssignmentId,
expected.StudentId,
expected.Text,
expected.Attachment,
expected.Comment,
expected.Score,
expected.Reviewed,
expected.IgnoreDeadline,
expected.CreatedAt,
expected.UpdatedAt,
),
)

result, err := repo.GetAssignmentSubmissionByStudent(assignmentID, studentID)
assert.NoError(t, err)
assert.Equal(t, expected.Id, result.Id)
assert.Equal(t, expected.Text, result.Text)
assert.NoError(t, mock.ExpectationsWereMet())
}

/* HELPER FUNCTIONS */

func setupMockRepoForAssignments(t *testing.T) (pgxmock.PgxConnIface, repository.CoursesRepository) {
Expand Down
Loading