// Copyright 2019 Drone.IO Inc. All rights reserved. // Use of this source code is governed by the Drone Non-Commercial License // that can be found in the LICENSE file. package user import ( "encoding/json" "io/ioutil" "net/http" "net/http/httptest" "testing" "github.com/drone/drone/handler/api/errors" "github.com/drone/drone/handler/api/request" "github.com/drone/drone/mock" "github.com/drone/drone/core" "github.com/golang/mock/gomock" "github.com/google/go-cmp/cmp" "github.com/sirupsen/logrus" ) func init() { logrus.SetOutput(ioutil.Discard) } func TestRepositoryList(t *testing.T) { controller := gomock.NewController(t) defer controller.Finish() mockUser := &core.User{ ID: 1, Login: "octocat", } mockRepos := []*core.Repository{ { Namespace: "octocat", Name: "hello-world", Slug: "octocat/hello-world", }, } repos := mock.NewMockRepositoryStore(controller) repos.EXPECT().List(gomock.Any(), mockUser.ID).Return(mockRepos, nil) w := httptest.NewRecorder() r := httptest.NewRequest("GET", "/", nil) r = r.WithContext( request.WithUser(r.Context(), mockUser), ) HandleRepos(repos)(w, r) if got, want := w.Code, http.StatusOK; want != got { t.Errorf("Want response code %d, got %d", want, got) } got, want := []*core.Repository{}, mockRepos json.NewDecoder(w.Body).Decode(&got) if diff := cmp.Diff(got, want); len(diff) > 0 { t.Errorf(diff) } } func TestRepositoryListErr(t *testing.T) { controller := gomock.NewController(t) defer controller.Finish() mockUser := &core.User{ ID: 1, Login: "octocat", } repos := mock.NewMockRepositoryStore(controller) repos.EXPECT().List(gomock.Any(), mockUser.ID).Return(nil, errors.ErrNotFound) w := httptest.NewRecorder() r := httptest.NewRequest("GET", "/", nil) r = r.WithContext( request.WithUser(r.Context(), mockUser), ) HandleRepos(repos)(w, r) if got, want := w.Code, http.StatusInternalServerError; want != got { t.Errorf("Want response code %d, got %d", want, got) } got, want := &errors.Error{}, errors.ErrNotFound json.NewDecoder(w.Body).Decode(got) if diff := cmp.Diff(got, want); len(diff) > 0 { t.Errorf(diff) } }