Skip to content

Commit

Permalink
feat: add tests for controller layer on search repos (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
tobg8 authored Nov 1, 2024
1 parent e5cfb4b commit b499f9d
Showing 1 changed file with 76 additions and 0 deletions.
76 changes: 76 additions & 0 deletions src/controllers/repository_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package controllers

import (
"errors"
"net/http"
"net/http/httptest"
"testing"

"github.com/Scalingo/sclng-backend-test-v1/src/models"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)

type mockRepositoryUseCase struct {
mock.Mock
}

func (m *mockRepositoryUseCase) SearchRepositories(query string) (*models.RepositorySearchResponse, error) {
args := m.Called(query)
return args.Get(0).(*models.RepositorySearchResponse), args.Error(1)
}

func TestSearchRepositoriesEndpoint(t *testing.T) {
tests := map[string]struct {
endpoint string
mockCall func(*mockRepositoryUseCase)
expectedStatus int
}{
"nominal": {
endpoint: "/repositories/search?q=golang",
mockCall: func(m *mockRepositoryUseCase) {
response := &models.RepositorySearchResponse{
TotalCount: 1,
Items: []models.Repository{
{FullName: "scalingo/scalingo-test"},
},
}
m.On("SearchRepositories", "golang").Return(response, nil)
},
expectedStatus: http.StatusOK,
},
"usecase error, return error": {
endpoint: "/repositories/search?q=golang",
mockCall: func(m *mockRepositoryUseCase) {
m.On("SearchRepositories", "golang").Return(&models.RepositorySearchResponse{}, errors.New("usecase error"))
},
expectedStatus: http.StatusInternalServerError,
},
"missing query, return error": {
endpoint: "/repositories/search",
expectedStatus: http.StatusBadRequest,
},
"empty queryu, return error": {
endpoint: "/repositories/search?q=",
expectedStatus: http.StatusBadRequest,
},
}

for name, tt := range tests {
t.Run(name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, tt.endpoint, nil)
w := httptest.NewRecorder()

mockUseCase := new(mockRepositoryUseCase)
controller := NewRepositoryController(mockUseCase)

if tt.mockCall != nil {
tt.mockCall(mockUseCase)
}

controller.SearchRepositories(w, req)

assert.Equal(t, tt.expectedStatus, w.Code)
})
}
}

0 comments on commit b499f9d

Please sign in to comment.