1package handlers 2 3import ( 4 "bytes" 5 "net/http" 6 "testing" 7 8 "github.com/gorilla/mux" 9 corev2 "github.com/sensu/sensu-go/api/core/v2" 10 "github.com/sensu/sensu-go/backend/store" 11 "github.com/sensu/sensu-go/testing/fixture" 12 "github.com/sensu/sensu-go/testing/mockstore" 13 "github.com/stretchr/testify/mock" 14) 15 16func TestHandlers_CreateResource(t *testing.T) { 17 type storeFunc func(*mockstore.MockStore) 18 tests := []struct { 19 name string 20 body []byte 21 urlVars map[string]string 22 storeFunc storeFunc 23 wantErr bool 24 }{ 25 { 26 name: "invalid request body", 27 body: []byte("foobar"), 28 wantErr: true, 29 }, 30 { 31 name: "invalid resource meta", 32 body: marshal(t, fixture.Resource{ObjectMeta: corev2.ObjectMeta{ 33 Name: "foo", 34 Namespace: "acme", 35 }}), 36 urlVars: map[string]string{"id": "bar", "namespace": "acme"}, 37 wantErr: true, 38 }, 39 { 40 name: "store err, already exists", 41 body: marshal(t, fixture.Resource{ObjectMeta: corev2.ObjectMeta{}}), 42 storeFunc: func(s *mockstore.MockStore) { 43 s.On("CreateResource", mock.Anything, mock.AnythingOfType("*fixture.Resource")). 44 Return(&store.ErrAlreadyExists{}) 45 }, 46 wantErr: true, 47 }, 48 { 49 name: "store err, not valid", 50 body: marshal(t, fixture.Resource{ObjectMeta: corev2.ObjectMeta{}}), 51 storeFunc: func(s *mockstore.MockStore) { 52 s.On("CreateResource", mock.Anything, mock.AnythingOfType("*fixture.Resource")). 53 Return(&store.ErrNotValid{}) 54 }, 55 wantErr: true, 56 }, 57 { 58 name: "store err, default", 59 body: marshal(t, fixture.Resource{ObjectMeta: corev2.ObjectMeta{}}), 60 storeFunc: func(s *mockstore.MockStore) { 61 s.On("CreateResource", mock.Anything, mock.AnythingOfType("*fixture.Resource")). 62 Return(&store.ErrInternal{}) 63 }, 64 wantErr: true, 65 }, 66 { 67 name: "successful create", 68 body: marshal(t, fixture.Resource{ObjectMeta: corev2.ObjectMeta{}}), 69 storeFunc: func(s *mockstore.MockStore) { 70 s.On("CreateResource", mock.Anything, mock.AnythingOfType("*fixture.Resource")). 71 Return(nil) 72 }, 73 }, 74 } 75 for _, tt := range tests { 76 t.Run(tt.name, func(t *testing.T) { 77 store := &mockstore.MockStore{} 78 if tt.storeFunc != nil { 79 tt.storeFunc(store) 80 } 81 82 h := Handlers{ 83 Resource: &fixture.Resource{}, 84 Store: store, 85 } 86 87 r, _ := http.NewRequest(http.MethodPost, "/", bytes.NewReader(tt.body)) 88 r = mux.SetURLVars(r, tt.urlVars) 89 90 _, err := h.CreateResource(r) 91 if (err != nil) != tt.wantErr { 92 t.Errorf("Handlers.CreateResource() error = %v, wantErr %v", err, tt.wantErr) 93 return 94 } 95 }) 96 } 97} 98