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

Add Repo feature #11

Merged
merged 18 commits into from
Oct 21, 2021
Merged
Show file tree
Hide file tree
Changes from 7 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
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ _dist/
dist/
bin/
vendor/
*.swp
cmd/albatross/__debug_bin
pkg/helmcli/repository/testdata/config.lock
coverage.txt
135 changes: 135 additions & 0 deletions api/repository/add.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
package repository

import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"

"github.com/gojekfarm/albatross/pkg/logger"

"github.com/gorilla/mux"
)

// AddRequest is the body for PUT request to repository
// swagger:model addRepoRequestBody
type AddRequest struct {
Name string `json:"-"`
URL string `json:"url"`
// Username string `json:"username"`
// Password string `json:"password"`

// example: false
ForceUpdate bool `json:"force_update"`
// CertFile string
kaustubhkurve marked this conversation as resolved.
Show resolved Hide resolved
// KeyFile string
// CaFile string

// example: false
InsecureSkipTLSverify bool `json:"skip_tls_verify"`
}

type addService interface {
Add(context.Context, AddRequest) error
}

// AddErrorResponse body of non 2xx response
// swagger:model addRepoErrorResponseBody
type AddErrorResponse struct {
Error string `json:"error"`
}

// AddOkResponse body of 2xx response
// swagger:model addRepoOkResponseBody
type AddOkResponse struct {
Message string `json:"message"`
}

const NAME string = "repository-name"
punit-kulal marked this conversation as resolved.
Show resolved Hide resolved

// AddHandler handles a repo add/update request
// swagger:operation PUT /repositories/{repository_name} repository addOperation
punit-kulal marked this conversation as resolved.
Show resolved Hide resolved
//
// Add/Update a chart repository to the server.
// The endpoint is idempotent and a repository can be updated by using the force_update parameter to true
// ---
// produces:
// - application/json
// parameters:
// - name: repository_name
// in: path
// required: true
// type: string
// format: string
// - name: Body
// in: body
// required: true
// schema:
// "$ref": "#/definitions/addRepoRequestBody"
// schemes:
// - http
// responses:
// '200':
// description: "The repository was added successfully"
// schema:
// $ref: "#/definitions/addRepoOkResponseBody"
// '400':
// description: "Invalid Request"
// schema:
// $ref: "#/definitions/addRepoErrorResponseBody"
// '500':
// description: "Something went with the server"
// schema:
// $ref: "#/definitions/addRepoErrorResponseBody"
func AddHandler(s addService) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()

vars := mux.Vars(r)
var req AddRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
logger.Errorf("[RepoAdd] error decoding request: %v", err)
w.WriteHeader(http.StatusBadRequest)
return
}

if err := req.isValid(); err != nil {
logger.Errorf("[RepoAdd] error validating request %v", err)
respondAddError(w, "error adding repo", err, http.StatusBadRequest)
return
}

req.Name = vars[NAME]

err := s.Add(r.Context(), req)

if err != nil {
logger.Errorf("[RepoAdd] error adding repo: %v", err)
respondAddError(w, "error adding repo", err, http.StatusInternalServerError)
return
}
resp := AddOkResponse{Message: fmt.Sprintf("Repo %s added successfully with url: %s", req.Name, req.URL)}
if err := json.NewEncoder(w).Encode(&resp); err != nil {
respondAddError(w, "error writing response: %v", err, http.StatusInternalServerError)
return
}
})
}

func respondAddError(w http.ResponseWriter, logprefix string, err error, errorCode int) {
response := AddErrorResponse{Error: err.Error()}
w.WriteHeader(errorCode)
if err := json.NewEncoder(w).Encode(&response); err != nil {
logger.Errorf("[AddRepo] %s %v", logprefix, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}

func (req AddRequest) isValid() error {
if req.URL == "" {
return errors.New("url cannot be empty")
}
return nil
}
115 changes: 115 additions & 0 deletions api/repository/add_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package repository

import (
"context"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/gojekfarm/albatross/pkg/logger"

"github.com/gorilla/mux"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"gotest.tools/assert"
)

type mockService struct {
mock.Mock
}

func (m *mockService) Add(ctx context.Context, req AddRequest) error {
args := m.Called(ctx, req)
return args.Error(0)
}

type RepoAddTestSuite struct {
suite.Suite
recorder *httptest.ResponseRecorder
server *httptest.Server
mockService *mockService
}

func (s *RepoAddTestSuite) SetupSuite() {
logger.Setup("default")
}

func (s *RepoAddTestSuite) SetupTest() {
s.recorder = httptest.NewRecorder()
s.mockService = new(mockService)
router := mux.NewRouter()
path := fmt.Sprintf("/repositories/{%s}", NAME)
router.Handle(path, AddHandler(s.mockService)).Methods(http.MethodPut)
s.server = httptest.NewServer(router)
}

func (s *RepoAddTestSuite) TestRepoAddSuccessFul() {
repoName := "gojek-incubator"
urlName := "https://gojek.github.io/charts/incubator/"
body := fmt.Sprintf(`{"url":"%s", "username":"admin", "password":"123",
"allow_deprecated_repos":true, "force_update": true, "skip_tls_verify": true}`, urlName)

req, _ := http.NewRequest(http.MethodPut, fmt.Sprintf("%s/repositories/%s", s.server.URL, repoName), strings.NewReader(body))
request := AddRequest{
Name: repoName,
URL: urlName,
ForceUpdate: true,
InsecureSkipTLSverify: true,
}

s.mockService.On("Add", mock.Anything, request).Return(nil)

resp, err := http.DefaultClient.Do(req)
assert.Equal(s.T(), http.StatusOK, resp.StatusCode)
expectedResponse := `{"message":"Repo gojek-incubator added successfully with url: https://gojek.github.io/charts/incubator/"}` + "\n"
respBody, _ := ioutil.ReadAll(resp.Body)
assert.Equal(s.T(), expectedResponse, string(respBody))
require.NoError(s.T(), err)
s.mockService.AssertExpectations(s.T())
}

func (s *RepoAddTestSuite) TestRepoAddInvalidRequest() {
repoName := "gojek-incubator"
body := `{"username":"admin", "password":"123"}`

req, _ := http.NewRequest(http.MethodPut, fmt.Sprintf("%s/repositories/%s", s.server.URL, repoName), strings.NewReader(body))

resp, err := http.DefaultClient.Do(req)
assert.Equal(s.T(), http.StatusBadRequest, resp.StatusCode)
expectedResponse := `{"error":"url cannot be empty"}` + "\n"
respBody, _ := ioutil.ReadAll(resp.Body)
assert.Equal(s.T(), expectedResponse, string(respBody))
require.NoError(s.T(), err)
s.mockService.AssertExpectations(s.T())
}

func (s *RepoAddTestSuite) TestRepoAddFailure() {
repoName := "gojek-incubator"
urlName := "https://gojek.github.io/charts/incubator/"
body := fmt.Sprintf(`{"url":"%s", "username":"admin", "password":"123"}`, urlName)

req, _ := http.NewRequest(http.MethodPut, fmt.Sprintf("%s/repositories/%s", s.server.URL, repoName), strings.NewReader(body))
request := AddRequest{
Name: repoName,
URL: urlName,
}

s.mockService.On("Add", mock.Anything, request).Return(errors.New("error adding repository"))

resp, err := http.DefaultClient.Do(req)
assert.Equal(s.T(), http.StatusInternalServerError, resp.StatusCode)
expectedResponse := `{"error":"error adding repository"}` + "\n"
respBody, _ := ioutil.ReadAll(resp.Body)
assert.Equal(s.T(), expectedResponse, string(respBody))
require.NoError(s.T(), err)
s.mockService.AssertExpectations(s.T())
}

func TestInstallAPI(t *testing.T) {
suite.Run(t, new(RepoAddTestSuite))
}
35 changes: 35 additions & 0 deletions api/repository/service.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package repository

import (
"context"

"github.com/gojekfarm/albatross/pkg/helmcli/flags"
"github.com/gojekfarm/albatross/pkg/helmcli/repository"
)

type Service struct {
cli repository.Client
}

func (s Service) Add(ctx context.Context, req AddRequest) error {
addFlags := flags.AddFlags{
Name: req.Name,
URL: req.URL,
ForceUpdate: req.ForceUpdate,
}

adder, err := s.cli.NewAdder(addFlags)
if err != nil {
return err
}

err = adder.Add(ctx)
if err != nil {
return err
}
return nil
kaustubhkurve marked this conversation as resolved.
Show resolved Hide resolved
}

func NewService(cli repository.Client) Service {
return Service{cli}
}
94 changes: 94 additions & 0 deletions api/repository/service_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package repository

import (
"context"
"errors"
"testing"

"github.com/gojekfarm/albatross/pkg/helmcli/flags"
"github.com/gojekfarm/albatross/pkg/helmcli/repository"

"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)

type mockRepositoryClient struct{ mock.Mock }

func (m *mockRepositoryClient) NewAdder(addFlags flags.AddFlags) (repository.Adder, error) {
args := m.Called(addFlags)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(repository.Adder), args.Error(1)
}

type mockAdder struct{ mock.Mock }

func (m *mockAdder) Add(ctx context.Context) error {
args := m.Called(ctx)
return args.Error(0)
}

func TestServiceAddSuccessful(t *testing.T) {
mockCli := new(mockRepositoryClient)
adder := new(mockAdder)
s := NewService(mockCli)
req := AddRequest{
Name: "repoName",
URL: "https://gojek.github.io/charts/incubator/",
}
addFlags := flags.AddFlags{
Name: "repoName",
URL: "https://gojek.github.io/charts/incubator/",
}
mockCli.On("NewAdder", addFlags).Return(adder, nil).Once()
adder.On("Add", mock.Anything).Return(nil).Once()

err := s.Add(context.Background(), req)

require.NoError(t, err)
}

func TestServiceNewAdderError(t *testing.T) {
mockCli := new(mockRepositoryClient)
s := NewService(mockCli)
req := AddRequest{
Name: "repoName",
URL: "https://gojek.github.io/charts/incubator/",
}
addFlags := flags.AddFlags{
Name: "repoName",
URL: "https://gojek.github.io/charts/incubator/",
// Username: "user",
// Password: "password",
}
adderError := errors.New("failed creating adder")
mockCli.On("NewAdder", addFlags).Return(nil, adderError)

err := s.Add(context.Background(), req)

require.Error(t, adderError, err)
}

func TestServiceAddError(t *testing.T) {
mockCli := new(mockRepositoryClient)
adder := new(mockAdder)
s := NewService(mockCli)
req := AddRequest{
Name: "repoName",
URL: "https://gojek.github.io/charts/incubator/",
}
addFlags := flags.AddFlags{
Name: "repoName",
URL: "https://gojek.github.io/charts/incubator/",
// Username: "user",
// Password: "password",
}
addError := errors.New("error while adding repo")
mockCli.On("NewAdder", addFlags).Return(adder, nil).Once()
adder.On("Add", mock.Anything).Return(addError).Once()

err := s.Add(context.Background(), req)

require.Error(t, addError, err)
}
Loading