From a52dec70617eac8ef37ad49358246f49a47d82a8 Mon Sep 17 00:00:00 2001 From: nyagamunene Date: Tue, 9 Apr 2024 13:09:33 +0300 Subject: [PATCH 01/18] Added mockery directive Signed-off-by: nyagamunene --- consumers/notifiers/api/endpoint_test.go | 18 +- consumers/notifiers/mocks/notifier.go | 50 ++++-- consumers/notifiers/mocks/subscriptions.go | 200 +++++++++++---------- consumers/notifiers/notifier.go | 2 + consumers/notifiers/service_test.go | 40 +++-- consumers/notifiers/subscriptions.go | 2 + 6 files changed, 179 insertions(+), 133 deletions(-) diff --git a/consumers/notifiers/api/endpoint_test.go b/consumers/notifiers/api/endpoint_test.go index aab51f8d83..83d08eb3e4 100644 --- a/consumers/notifiers/api/endpoint_test.go +++ b/consumers/notifiers/api/endpoint_test.go @@ -67,13 +67,13 @@ func (tr testRequest) make() (*http.Response, error) { return tr.client.Do(req) } -func newService() (notifiers.Service, *authmocks.AuthClient) { +func newService() (notifiers.Service, *authmocks.AuthClient, *mocks.SubscriptionsRepository) { auth := new(authmocks.AuthClient) - repo := mocks.NewRepo(make(map[string]notifiers.Subscription)) + repo := new(mocks.SubscriptionsRepository) idp := uuid.NewMock() - notif := mocks.NewNotifier() + notif := new(mocks.Notifier) from := "exampleFrom" - return notifiers.New(auth, repo, idp, notif, from), auth + return notifiers.New(auth, repo, idp, notif, from), auth, repo } func newServer(svc notifiers.Service) *httptest.Server { @@ -91,7 +91,7 @@ func toJSON(data interface{}) string { } func TestCreate(t *testing.T) { - svc, auth := newService() + svc, auth, repo := newService() ss := newServer(svc) defer ss.Close() @@ -181,6 +181,7 @@ func TestCreate(t *testing.T) { for _, tc := range cases { repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.auth}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return("", nil) req := testRequest{ client: ss.Client(), @@ -198,11 +199,12 @@ func TestCreate(t *testing.T) { assert.Equal(t, tc.location, location, fmt.Sprintf("%s: expected location %s got %s", tc.desc, tc.location, location)) repoCall.Unset() + repoCall1.Unset() } } func TestView(t *testing.T) { - svc, auth := newService() + svc, auth, _ := newService() ss := newServer(svc) defer ss.Close() @@ -282,7 +284,7 @@ func TestView(t *testing.T) { } func TestList(t *testing.T) { - svc, auth := newService() + svc, auth, _ := newService() ss := newServer(svc) defer ss.Close() @@ -408,7 +410,7 @@ func TestList(t *testing.T) { } func TestRemove(t *testing.T) { - svc, auth := newService() + svc, auth, _ := newService() ss := newServer(svc) defer ss.Close() diff --git a/consumers/notifiers/mocks/notifier.go b/consumers/notifiers/mocks/notifier.go index 84c199a21f..12f7fd73c3 100644 --- a/consumers/notifiers/mocks/notifier.go +++ b/consumers/notifiers/mocks/notifier.go @@ -1,29 +1,47 @@ +// Code generated by mockery v2.42.1. DO NOT EDIT. + // Copyright (c) Abstract Machines -// SPDX-License-Identifier: Apache-2.0 package mocks import ( - "github.com/absmach/magistrala/consumers/notifiers" - "github.com/absmach/magistrala/pkg/messaging" + messaging "github.com/absmach/magistrala/pkg/messaging" + mock "github.com/stretchr/testify/mock" ) -var _ notifiers.Notifier = (*notifier)(nil) +// Notifier is an autogenerated mock type for the Notifier type +type Notifier struct { + mock.Mock +} + +// Notify provides a mock function with given fields: from, to, msg +func (_m *Notifier) Notify(from string, to []string, msg *messaging.Message) error { + ret := _m.Called(from, to, msg) -const InvalidSender = "invalid@example.com" + if len(ret) == 0 { + panic("no return value specified for Notify") + } -type notifier struct{} + var r0 error + if rf, ok := ret.Get(0).(func(string, []string, *messaging.Message) error); ok { + r0 = rf(from, to, msg) + } else { + r0 = ret.Error(0) + } -// NewNotifier returns a new Notifier mock. -func NewNotifier() notifiers.Notifier { - return notifier{} + return r0 } -func (n notifier) Notify(from string, to []string, msg *messaging.Message) error { - for _, t := range to { - if t == InvalidSender { - return notifiers.ErrNotify - } - } - return nil +// NewNotifier creates a new instance of Notifier. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewNotifier(t interface { + mock.TestingT + Cleanup(func()) +}) *Notifier { + mock := &Notifier{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock } diff --git a/consumers/notifiers/mocks/subscriptions.go b/consumers/notifiers/mocks/subscriptions.go index 594c18f991..479998d743 100644 --- a/consumers/notifiers/mocks/subscriptions.go +++ b/consumers/notifiers/mocks/subscriptions.go @@ -1,131 +1,133 @@ +// Code generated by mockery v2.42.1. DO NOT EDIT. + // Copyright (c) Abstract Machines -// SPDX-License-Identifier: Apache-2.0 package mocks import ( - "context" - "sort" - "sync" + context "context" - "github.com/absmach/magistrala/consumers/notifiers" - repoerr "github.com/absmach/magistrala/pkg/errors/repository" + notifiers "github.com/absmach/magistrala/consumers/notifiers" + mock "github.com/stretchr/testify/mock" ) -var _ notifiers.SubscriptionsRepository = (*subRepoMock)(nil) - -type subRepoMock struct { - mu sync.Mutex - subs map[string]notifiers.Subscription +// SubscriptionsRepository is an autogenerated mock type for the SubscriptionsRepository type +type SubscriptionsRepository struct { + mock.Mock } -// NewRepo returns a new Subscriptions repository mock. -func NewRepo(subs map[string]notifiers.Subscription) notifiers.SubscriptionsRepository { - return &subRepoMock{ - subs: subs, - } -} +// Remove provides a mock function with given fields: ctx, id +func (_m *SubscriptionsRepository) Remove(ctx context.Context, id string) error { + ret := _m.Called(ctx, id) -func (srm *subRepoMock) Save(_ context.Context, sub notifiers.Subscription) (string, error) { - srm.mu.Lock() - defer srm.mu.Unlock() - if _, ok := srm.subs[sub.ID]; ok { - return "", repoerr.ErrConflict + if len(ret) == 0 { + panic("no return value specified for Remove") } - for _, s := range srm.subs { - if s.Contact == sub.Contact && s.Topic == sub.Topic { - return "", repoerr.ErrConflict - } + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, string) error); ok { + r0 = rf(ctx, id) + } else { + r0 = ret.Error(0) } - srm.subs[sub.ID] = sub - return sub.ID, nil + return r0 } -func (srm *subRepoMock) Retrieve(_ context.Context, id string) (notifiers.Subscription, error) { - srm.mu.Lock() - defer srm.mu.Unlock() - ret, ok := srm.subs[id] - if !ok { - return notifiers.Subscription{}, repoerr.ErrNotFound +// Retrieve provides a mock function with given fields: ctx, id +func (_m *SubscriptionsRepository) Retrieve(ctx context.Context, id string) (notifiers.Subscription, error) { + ret := _m.Called(ctx, id) + + if len(ret) == 0 { + panic("no return value specified for Retrieve") } - return ret, nil -} -func (srm *subRepoMock) RetrieveAll(_ context.Context, pm notifiers.PageMetadata) (notifiers.Page, error) { - srm.mu.Lock() - defer srm.mu.Unlock() + var r0 notifiers.Subscription + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, string) (notifiers.Subscription, error)); ok { + return rf(ctx, id) + } + if rf, ok := ret.Get(0).(func(context.Context, string) notifiers.Subscription); ok { + r0 = rf(ctx, id) + } else { + r0 = ret.Get(0).(notifiers.Subscription) + } - // Sort keys - keys := make([]string, 0) - for k := range srm.subs { - keys = append(keys, k) + if rf, ok := ret.Get(1).(func(context.Context, string) error); ok { + r1 = rf(ctx, id) + } else { + r1 = ret.Error(1) } - sort.Strings(keys) - - var subs []notifiers.Subscription - var total int - offset := int(pm.Offset) - for _, k := range keys { - v := srm.subs[k] - if pm.Topic == "" { - if pm.Contact == "" { - if total < offset { - total++ - continue - } - total++ - subs = appendSubs(subs, v, pm.Limit) - continue - } - if pm.Contact == v.Contact { - if total < offset { - total++ - continue - } - total++ - subs = appendSubs(subs, v, pm.Limit) - continue - } - } - if pm.Topic == v.Topic { - if pm.Contact == "" || pm.Contact == v.Contact { - if total < offset { - total++ - continue - } - total++ - subs = appendSubs(subs, v, pm.Limit) - } - } + + return r0, r1 +} + +// RetrieveAll provides a mock function with given fields: ctx, pm +func (_m *SubscriptionsRepository) RetrieveAll(ctx context.Context, pm notifiers.PageMetadata) (notifiers.Page, error) { + ret := _m.Called(ctx, pm) + + if len(ret) == 0 { + panic("no return value specified for RetrieveAll") } - if len(subs) == 0 { - return notifiers.Page{}, repoerr.ErrNotFound + var r0 notifiers.Page + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, notifiers.PageMetadata) (notifiers.Page, error)); ok { + return rf(ctx, pm) + } + if rf, ok := ret.Get(0).(func(context.Context, notifiers.PageMetadata) notifiers.Page); ok { + r0 = rf(ctx, pm) + } else { + r0 = ret.Get(0).(notifiers.Page) } - ret := notifiers.Page{ - PageMetadata: pm, - Total: uint(total), - Subscriptions: subs, + if rf, ok := ret.Get(1).(func(context.Context, notifiers.PageMetadata) error); ok { + r1 = rf(ctx, pm) + } else { + r1 = ret.Error(1) } - return ret, nil + return r0, r1 } -func appendSubs(subs []notifiers.Subscription, sub notifiers.Subscription, max int) []notifiers.Subscription { - if len(subs) < max || max == -1 { - subs = append(subs, sub) +// Save provides a mock function with given fields: ctx, sub +func (_m *SubscriptionsRepository) Save(ctx context.Context, sub notifiers.Subscription) (string, error) { + ret := _m.Called(ctx, sub) + + if len(ret) == 0 { + panic("no return value specified for Save") + } + + var r0 string + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, notifiers.Subscription) (string, error)); ok { + return rf(ctx, sub) + } + if rf, ok := ret.Get(0).(func(context.Context, notifiers.Subscription) string); ok { + r0 = rf(ctx, sub) + } else { + r0 = ret.Get(0).(string) } - return subs -} -func (srm *subRepoMock) Remove(_ context.Context, id string) error { - srm.mu.Lock() - defer srm.mu.Unlock() - if _, ok := srm.subs[id]; !ok { - return repoerr.ErrNotFound + if rf, ok := ret.Get(1).(func(context.Context, notifiers.Subscription) error); ok { + r1 = rf(ctx, sub) + } else { + r1 = ret.Error(1) } - delete(srm.subs, id) - return nil + + return r0, r1 +} + +// NewSubscriptionsRepository creates a new instance of SubscriptionsRepository. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewSubscriptionsRepository(t interface { + mock.TestingT + Cleanup(func()) +}) *SubscriptionsRepository { + mock := &SubscriptionsRepository{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock } diff --git a/consumers/notifiers/notifier.go b/consumers/notifiers/notifier.go index d7130b87fc..2c23bc9e58 100644 --- a/consumers/notifiers/notifier.go +++ b/consumers/notifiers/notifier.go @@ -13,6 +13,8 @@ import ( var ErrNotify = errors.New("error sending notification") // Notifier represents an API for sending notification. +// +//go:generate mockery --name Notifier --output=./mocks --filename notifier.go --quiet --note "Copyright (c) Abstract Machines" type Notifier interface { // Notify method is used to send notification for the // received message to the provided list of receivers. diff --git a/consumers/notifiers/service_test.go b/consumers/notifiers/service_test.go index c4fb5212e4..b222ab804e 100644 --- a/consumers/notifiers/service_test.go +++ b/consumers/notifiers/service_test.go @@ -30,17 +30,17 @@ const ( validID = "d4ebb847-5d0e-4e46-bdd9-b6aceaaa3a22" ) -func newService() (notifiers.Service, *authmocks.AuthClient) { - repo := mocks.NewRepo(make(map[string]notifiers.Subscription)) +func newService() (notifiers.Service, *authmocks.AuthClient, *mocks.SubscriptionsRepository) { + repo := new(mocks.SubscriptionsRepository) auth := new(authmocks.AuthClient) - notifier := mocks.NewNotifier() + notifier := new(mocks.Notifier) idp := uuid.NewMock() from := "exampleFrom" - return notifiers.New(auth, repo, idp, notifier, from), auth + return notifiers.New(auth, repo, idp, notifier, from), auth, repo } func TestCreateSubscription(t *testing.T) { - svc, auth := newService() + svc, auth, repo := newService() cases := []struct { desc string @@ -74,20 +74,24 @@ func TestCreateSubscription(t *testing.T) { for _, tc := range cases { repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: testsutil.GenerateUUID(t)}, nil) + repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(tc.id, tc.err) id, err := svc.CreateSubscription(context.Background(), tc.token, tc.sub) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) assert.Equal(t, tc.id, id, fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.id, id)) repoCall.Unset() + repoCall1.Unset() } } func TestViewSubscription(t *testing.T) { - svc, auth := newService() + svc, auth, repo := newService() sub := notifiers.Subscription{Contact: exampleUser1, Topic: "valid.topic"} repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return("", nil) id, err := svc.CreateSubscription(context.Background(), exampleUser1, sub) require.Nil(t, err, "Saving a Subscription must succeed") repoCall.Unset() + repoCall1.Unset() sub.ID = id sub.OwnerID = validID @@ -123,15 +127,17 @@ func TestViewSubscription(t *testing.T) { for _, tc := range cases { repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Retrieve", mock.Anything, mock.Anything).Return(tc.sub, tc.err) sub, err := svc.ViewSubscription(context.Background(), tc.token, tc.id) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) assert.Equal(t, tc.sub, sub, fmt.Sprintf("%s: expected %v got %v\n", tc.desc, tc.sub, sub)) repoCall.Unset() + repoCall1.Unset() } } func TestListSubscriptions(t *testing.T) { - svc, auth := newService() + svc, auth, repo := newService() sub := notifiers.Subscription{Contact: exampleUser1, OwnerID: exampleUser1} topic := "topic.subtopic" var subs []notifiers.Subscription @@ -145,9 +151,11 @@ func TestListSubscriptions(t *testing.T) { } tmp.Topic = fmt.Sprintf("%s.%d", topic, i) repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: token}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return("", nil) id, err := svc.CreateSubscription(context.Background(), token, tmp) require.Nil(t, err, "Saving a Subscription must succeed") repoCall.Unset() + repoCall1.Unset() tmp.ID = id tmp.OwnerID = validID subs = append(subs, tmp) @@ -243,20 +251,24 @@ func TestListSubscriptions(t *testing.T) { for _, tc := range cases { repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("RetrieveAll", mock.Anything, mock.Anything).Return(tc.page, tc.err) page, err := svc.ListSubscriptions(context.Background(), tc.token, tc.pageMeta) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) assert.Equal(t, tc.page, page, fmt.Sprintf("%s: got unexpected page\n", tc.desc)) repoCall.Unset() + repoCall1.Unset() } } func TestRemoveSubscription(t *testing.T) { - svc, auth := newService() + svc, auth, repo := newService() sub := notifiers.Subscription{Contact: exampleUser1, Topic: "valid.topic"} repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return("", nil) id, err := svc.CreateSubscription(context.Background(), exampleUser1, sub) require.Nil(t, err, "Saving a Subscription must succeed") repoCall.Unset() + repoCall1.Unset() sub.ID = id sub.OwnerID = validID @@ -288,14 +300,16 @@ func TestRemoveSubscription(t *testing.T) { for _, tc := range cases { repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Remove", mock.Anything, mock.Anything).Return(tc.err) err := svc.RemoveSubscription(context.Background(), tc.token, tc.id) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) repoCall.Unset() + repoCall1.Unset() } } func TestConsume(t *testing.T) { - svc, auth := newService() + svc, auth, repo := newService() sub := notifiers.Subscription{ Contact: exampleUser1, OwnerID: validID, @@ -308,17 +322,21 @@ func TestConsume(t *testing.T) { tmp.Topic = fmt.Sprintf("%s-2", sub.Topic) } repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return("", nil) _, err := svc.CreateSubscription(context.Background(), exampleUser1, tmp) require.Nil(t, err, "Saving a Subscription must succeed") repoCall.Unset() + repoCall1.Unset() } - sub.Contact = mocks.InvalidSender + sub.Contact = "invalid@example.com" sub.Topic = fmt.Sprintf("%s-2", sub.Topic) repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return("", nil) _, err := svc.CreateSubscription(context.Background(), exampleUser1, sub) require.Nil(t, err, "Saving a Subscription must succeed") repoCall.Unset() + repoCall1.Unset() msg := messaging.Message{ Channel: "topic", @@ -347,7 +365,9 @@ func TestConsume(t *testing.T) { } for _, tc := range cases { + repoCall := repo.On("RetrieveAll", mock.Anything, mock.Anything).Return(notifiers.Page{}, tc.err) err := svc.ConsumeBlocking(context.TODO(), tc.msg) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) + repoCall.Unset() } } diff --git a/consumers/notifiers/subscriptions.go b/consumers/notifiers/subscriptions.go index 0d2166da56..c0e3dcb24e 100644 --- a/consumers/notifiers/subscriptions.go +++ b/consumers/notifiers/subscriptions.go @@ -30,6 +30,8 @@ type PageMetadata struct { } // SubscriptionsRepository specifies a Subscription persistence API. +// +//go:generate mockery --name SubscriptionsRepository --output=./mocks --filename subscriptions.go --quiet --note "Copyright (c) Abstract Machines" type SubscriptionsRepository interface { // Save persists a subscription. Successful operation is indicated by non-nil // error response. From 21ae1e17d595da5ddac39ac913c3460a14ca5f00 Mon Sep 17 00:00:00 2001 From: nyagamunene Date: Tue, 9 Apr 2024 14:23:44 +0300 Subject: [PATCH 02/18] Debugged endpoint test(continue) Signed-off-by: nyagamunene --- consumers/notifiers/api/endpoint_test.go | 14 +++++++++++++- consumers/notifiers/service.go | 2 ++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/consumers/notifiers/api/endpoint_test.go b/consumers/notifiers/api/endpoint_test.go index 83d08eb3e4..c9bc34a7cf 100644 --- a/consumers/notifiers/api/endpoint_test.go +++ b/consumers/notifiers/api/endpoint_test.go @@ -10,6 +10,7 @@ import ( "io" "net/http" "net/http/httptest" + "path" "strings" "testing" @@ -112,6 +113,7 @@ func TestCreate(t *testing.T) { auth string status int location string + err error }{ { desc: "add successfully", @@ -120,6 +122,7 @@ func TestCreate(t *testing.T) { auth: token, status: http.StatusCreated, location: fmt.Sprintf("/subscriptions/%s%012d", uuid.Prefix, 1), + err: nil, }, { desc: "add an existing subscription", @@ -128,6 +131,7 @@ func TestCreate(t *testing.T) { auth: token, status: http.StatusConflict, location: "", + err: svcerr.ErrConflict, }, { desc: "add with empty topic", @@ -136,6 +140,7 @@ func TestCreate(t *testing.T) { auth: token, status: http.StatusBadRequest, location: "", + err: svcerr.ErrMalformedEntity, }, { desc: "add with empty contact", @@ -144,6 +149,7 @@ func TestCreate(t *testing.T) { auth: token, status: http.StatusBadRequest, location: "", + err: svcerr.ErrMalformedEntity, }, { desc: "add with invalid auth token", @@ -152,6 +158,7 @@ func TestCreate(t *testing.T) { auth: authmocks.InvalidValue, status: http.StatusUnauthorized, location: "", + err: svcerr.ErrAuthentication, }, { desc: "add with empty auth token", @@ -160,6 +167,7 @@ func TestCreate(t *testing.T) { auth: "", status: http.StatusUnauthorized, location: "", + err: svcerr.ErrAuthentication, }, { desc: "add with invalid request format", @@ -168,6 +176,7 @@ func TestCreate(t *testing.T) { auth: token, status: http.StatusBadRequest, location: "", + err: svcerr.ErrMalformedEntity, }, { desc: "add without content type", @@ -176,12 +185,15 @@ func TestCreate(t *testing.T) { auth: token, status: http.StatusUnsupportedMediaType, location: "", + err: apiutil.ErrUnsupportedContentType, }, } for _, tc := range cases { repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.auth}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return("", nil) + repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(path.Base(tc.location), tc.err) + // svc.CreateSubscription() + // id, err := svc.CreateSubscription(ctx, req.token, sub) req := testRequest{ client: ss.Client(), diff --git a/consumers/notifiers/service.go b/consumers/notifiers/service.go index e7333650d2..5a54dab943 100644 --- a/consumers/notifiers/service.go +++ b/consumers/notifiers/service.go @@ -19,6 +19,8 @@ var ErrMessage = errors.New("failed to convert to Magistrala message") var _ consumers.AsyncConsumer = (*notifierService)(nil) // Service reprents a notification service. +// +//go:generate mockery --name Service --output=./mocks --filename service.go --quiet --note "Copyright (c) Abstract Machines" type Service interface { // CreateSubscription persists a subscription. // Successful operation is indicated by non-nil error response. From c49054b0881349a2ed23271a76c3c7c8c910d8a8 Mon Sep 17 00:00:00 2001 From: nyagamunene Date: Tue, 9 Apr 2024 15:53:03 +0300 Subject: [PATCH 03/18] Debugged endpoint test(continue) Signed-off-by: nyagamunene --- consumers/notifiers/api/endpoint_test.go | 78 ++++++------ consumers/notifiers/mocks/service.go | 151 +++++++++++++++++++++++ 2 files changed, 194 insertions(+), 35 deletions(-) create mode 100644 consumers/notifiers/mocks/service.go diff --git a/consumers/notifiers/api/endpoint_test.go b/consumers/notifiers/api/endpoint_test.go index c9bc34a7cf..0572e703d6 100644 --- a/consumers/notifiers/api/endpoint_test.go +++ b/consumers/notifiers/api/endpoint_test.go @@ -68,13 +68,14 @@ func (tr testRequest) make() (*http.Response, error) { return tr.client.Do(req) } -func newService() (notifiers.Service, *authmocks.AuthClient, *mocks.SubscriptionsRepository) { +func newService() (notifiers.Service, *authmocks.AuthClient, *mocks.SubscriptionsRepository, *mocks.Service) { auth := new(authmocks.AuthClient) repo := new(mocks.SubscriptionsRepository) + test := new(mocks.Service) idp := uuid.NewMock() notif := new(mocks.Notifier) from := "exampleFrom" - return notifiers.New(auth, repo, idp, notif, from), auth, repo + return notifiers.New(auth, repo, idp, notif, from), auth, repo, test } func newServer(svc notifiers.Service) *httptest.Server { @@ -92,7 +93,7 @@ func toJSON(data interface{}) string { } func TestCreate(t *testing.T) { - svc, auth, repo := newService() + svc, _, _, test := newService() ss := newServer(svc) defer ss.Close() @@ -190,11 +191,9 @@ func TestCreate(t *testing.T) { } for _, tc := range cases { - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.auth}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(path.Base(tc.location), tc.err) - // svc.CreateSubscription() - // id, err := svc.CreateSubscription(ctx, req.token, sub) - + // repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.auth}).Return(&magistrala.IdentityRes{Id: validID}, nil) + // repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(path.Base(tc.location), tc.err) + svcCall := test.On("CreateSubscription", mock.Anything, mock.Anything, mock.Anything).Return(path.Base(tc.location), tc.err) req := testRequest{ client: ss.Client(), method: http.MethodPost, @@ -210,13 +209,14 @@ func TestCreate(t *testing.T) { assert.Equal(t, tc.status, res.StatusCode, fmt.Sprintf("%s: expected status code %d got %d", tc.desc, tc.status, res.StatusCode)) assert.Equal(t, tc.location, location, fmt.Sprintf("%s: expected location %s got %s", tc.desc, tc.location, location)) - repoCall.Unset() - repoCall1.Unset() + // repoCall.Unset() + // repoCall1.Unset() + svcCall.Unset() } } func TestView(t *testing.T) { - svc, auth, _ := newService() + svc, auth, repo, _ := newService() ss := newServer(svc) defer ss.Close() @@ -225,9 +225,12 @@ func TestView(t *testing.T) { Contact: contact1, } repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: token}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return("", nil) + id, err := svc.CreateSubscription(context.Background(), token, sub) assert.Nil(t, err, fmt.Sprintf("got an error creating id: %s", err)) repoCall.Unset() + repoCall1.Unset() sr := subRes{ ID: id, @@ -243,6 +246,8 @@ func TestView(t *testing.T) { auth string status int res string + err error + v notifiers.Subscription }{ { desc: "view successfully", @@ -250,33 +255,35 @@ func TestView(t *testing.T) { auth: token, status: http.StatusOK, res: data, + err: nil, + v: sub, }, - { - desc: "view not existing", - id: "not existing", - auth: token, - status: http.StatusNotFound, - res: notFoundRes, - }, - { - desc: "view with invalid auth token", - id: id, - auth: authmocks.InvalidValue, - status: http.StatusUnauthorized, - res: unauthRes, - }, - { - desc: "view with empty auth token", - id: id, - auth: "", - status: http.StatusUnauthorized, - res: missingTokRes, - }, + // { + // desc: "view not existing", + // id: "not existing", + // auth: token, + // status: http.StatusNotFound, + // res: notFoundRes, + // }, + // { + // desc: "view with invalid auth token", + // id: id, + // auth: authmocks.InvalidValue, + // status: http.StatusUnauthorized, + // res: unauthRes, + // }, + // { + // desc: "view with empty auth token", + // id: id, + // auth: "", + // status: http.StatusUnauthorized, + // res: missingTokRes, + // }, } for _, tc := range cases { repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.auth}).Return(&magistrala.IdentityRes{Id: validID}, nil) - + repoCall1 := repo.On("Retrieve", mock.Anything, mock.Anything).Return(tc.v, tc.err) req := testRequest{ client: ss.Client(), method: http.MethodGet, @@ -292,11 +299,12 @@ func TestView(t *testing.T) { assert.Equal(t, tc.res, data, fmt.Sprintf("%s: expected body %s got %s", tc.desc, tc.res, data)) repoCall.Unset() + repoCall1.Unset() } } func TestList(t *testing.T) { - svc, auth, _ := newService() + svc, auth, _, _ := newService() ss := newServer(svc) defer ss.Close() @@ -422,7 +430,7 @@ func TestList(t *testing.T) { } func TestRemove(t *testing.T) { - svc, auth, _ := newService() + svc, auth, _, _ := newService() ss := newServer(svc) defer ss.Close() diff --git a/consumers/notifiers/mocks/service.go b/consumers/notifiers/mocks/service.go new file mode 100644 index 0000000000..853902cd80 --- /dev/null +++ b/consumers/notifiers/mocks/service.go @@ -0,0 +1,151 @@ +// Code generated by mockery v2.42.1. DO NOT EDIT. + +// Copyright (c) Abstract Machines + +package mocks + +import ( + context "context" + + notifiers "github.com/absmach/magistrala/consumers/notifiers" + mock "github.com/stretchr/testify/mock" +) + +// Service is an autogenerated mock type for the Service type +type Service struct { + mock.Mock +} + +// ConsumeBlocking provides a mock function with given fields: ctx, messages +func (_m *Service) ConsumeBlocking(ctx context.Context, messages interface{}) error { + ret := _m.Called(ctx, messages) + + if len(ret) == 0 { + panic("no return value specified for ConsumeBlocking") + } + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, interface{}) error); ok { + r0 = rf(ctx, messages) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// CreateSubscription provides a mock function with given fields: ctx, token, sub +func (_m *Service) CreateSubscription(ctx context.Context, token string, sub notifiers.Subscription) (string, error) { + ret := _m.Called(ctx, token, sub) + + if len(ret) == 0 { + panic("no return value specified for CreateSubscription") + } + + var r0 string + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, string, notifiers.Subscription) (string, error)); ok { + return rf(ctx, token, sub) + } + if rf, ok := ret.Get(0).(func(context.Context, string, notifiers.Subscription) string); ok { + r0 = rf(ctx, token, sub) + } else { + r0 = ret.Get(0).(string) + } + + if rf, ok := ret.Get(1).(func(context.Context, string, notifiers.Subscription) error); ok { + r1 = rf(ctx, token, sub) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// ListSubscriptions provides a mock function with given fields: ctx, token, pm +func (_m *Service) ListSubscriptions(ctx context.Context, token string, pm notifiers.PageMetadata) (notifiers.Page, error) { + ret := _m.Called(ctx, token, pm) + + if len(ret) == 0 { + panic("no return value specified for ListSubscriptions") + } + + var r0 notifiers.Page + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, string, notifiers.PageMetadata) (notifiers.Page, error)); ok { + return rf(ctx, token, pm) + } + if rf, ok := ret.Get(0).(func(context.Context, string, notifiers.PageMetadata) notifiers.Page); ok { + r0 = rf(ctx, token, pm) + } else { + r0 = ret.Get(0).(notifiers.Page) + } + + if rf, ok := ret.Get(1).(func(context.Context, string, notifiers.PageMetadata) error); ok { + r1 = rf(ctx, token, pm) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// RemoveSubscription provides a mock function with given fields: ctx, token, id +func (_m *Service) RemoveSubscription(ctx context.Context, token string, id string) error { + ret := _m.Called(ctx, token, id) + + if len(ret) == 0 { + panic("no return value specified for RemoveSubscription") + } + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, string, string) error); ok { + r0 = rf(ctx, token, id) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ViewSubscription provides a mock function with given fields: ctx, token, id +func (_m *Service) ViewSubscription(ctx context.Context, token string, id string) (notifiers.Subscription, error) { + ret := _m.Called(ctx, token, id) + + if len(ret) == 0 { + panic("no return value specified for ViewSubscription") + } + + var r0 notifiers.Subscription + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, string, string) (notifiers.Subscription, error)); ok { + return rf(ctx, token, id) + } + if rf, ok := ret.Get(0).(func(context.Context, string, string) notifiers.Subscription); ok { + r0 = rf(ctx, token, id) + } else { + r0 = ret.Get(0).(notifiers.Subscription) + } + + if rf, ok := ret.Get(1).(func(context.Context, string, string) error); ok { + r1 = rf(ctx, token, id) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// NewService creates a new instance of Service. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewService(t interface { + mock.TestingT + Cleanup(func()) +}) *Service { + mock := &Service{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} From bdb0163ef8b9f74add843cd66d96d75860581deb Mon Sep 17 00:00:00 2001 From: nyagamunene Date: Tue, 9 Apr 2024 18:18:24 +0300 Subject: [PATCH 04/18] Debugged endpoint test(continue) Signed-off-by: nyagamunene --- consumers/notifiers/api/endpoint_test.go | 466 +++++++++++------------ 1 file changed, 228 insertions(+), 238 deletions(-) diff --git a/consumers/notifiers/api/endpoint_test.go b/consumers/notifiers/api/endpoint_test.go index 0572e703d6..c403bedcc3 100644 --- a/consumers/notifiers/api/endpoint_test.go +++ b/consumers/notifiers/api/endpoint_test.go @@ -14,12 +14,13 @@ import ( "strings" "testing" - "github.com/absmach/magistrala" + // "github.com/absmach/magistrala" authmocks "github.com/absmach/magistrala/auth/mocks" "github.com/absmach/magistrala/consumers/notifiers" httpapi "github.com/absmach/magistrala/consumers/notifiers/api" "github.com/absmach/magistrala/consumers/notifiers/mocks" "github.com/absmach/magistrala/internal/apiutil" + "github.com/absmach/magistrala/internal/testsutil" mglog "github.com/absmach/magistrala/logger" svcerr "github.com/absmach/magistrala/pkg/errors/service" "github.com/absmach/magistrala/pkg/uuid" @@ -68,20 +69,11 @@ func (tr testRequest) make() (*http.Response, error) { return tr.client.Do(req) } -func newService() (notifiers.Service, *authmocks.AuthClient, *mocks.SubscriptionsRepository, *mocks.Service) { - auth := new(authmocks.AuthClient) - repo := new(mocks.SubscriptionsRepository) - test := new(mocks.Service) - idp := uuid.NewMock() - notif := new(mocks.Notifier) - from := "exampleFrom" - return notifiers.New(auth, repo, idp, notif, from), auth, repo, test -} - -func newServer(svc notifiers.Service) *httptest.Server { +func newServer() (*httptest.Server, *mocks.Service) { logger := mglog.NewMock() + svc := new(mocks.Service) mux := httpapi.MakeHandler(svc, logger, instanceID) - return httptest.NewServer(mux) + return httptest.NewServer(mux), svc } func toJSON(data interface{}) string { @@ -93,8 +85,7 @@ func toJSON(data interface{}) string { } func TestCreate(t *testing.T) { - svc, _, _, test := newService() - ss := newServer(svc) + ss, svc := newServer() defer ss.Close() sub := notifiers.Subscription{ @@ -191,9 +182,8 @@ func TestCreate(t *testing.T) { } for _, tc := range cases { - // repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.auth}).Return(&magistrala.IdentityRes{Id: validID}, nil) - // repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(path.Base(tc.location), tc.err) - svcCall := test.On("CreateSubscription", mock.Anything, mock.Anything, mock.Anything).Return(path.Base(tc.location), tc.err) + svcCall := svc.On("CreateSubscription", mock.Anything, mock.Anything, mock.Anything).Return(path.Base(tc.location), tc.err) + req := testRequest{ client: ss.Client(), method: http.MethodPost, @@ -209,28 +199,26 @@ func TestCreate(t *testing.T) { assert.Equal(t, tc.status, res.StatusCode, fmt.Sprintf("%s: expected status code %d got %d", tc.desc, tc.status, res.StatusCode)) assert.Equal(t, tc.location, location, fmt.Sprintf("%s: expected location %s got %s", tc.desc, tc.location, location)) - // repoCall.Unset() - // repoCall1.Unset() svcCall.Unset() } } func TestView(t *testing.T) { - svc, auth, repo, _ := newService() - ss := newServer(svc) + ss, svc := newServer() defer ss.Close() + d := testsutil.GenerateUUID(t) sub := notifiers.Subscription{ Topic: topic, Contact: contact1, + ID: d, + OwnerID: validID, } - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: token}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return("", nil) + svcCall := svc.On("CreateSubscription", context.Background(), token, sub).Return(d, nil) id, err := svc.CreateSubscription(context.Background(), token, sub) assert.Nil(t, err, fmt.Sprintf("got an error creating id: %s", err)) - repoCall.Unset() - repoCall1.Unset() + svcCall.Unset() sr := subRes{ ID: id, @@ -246,8 +234,8 @@ func TestView(t *testing.T) { auth string status int res string - err error - v notifiers.Subscription + err error + Sub notifiers.Subscription }{ { desc: "view successfully", @@ -256,217 +244,15 @@ func TestView(t *testing.T) { status: http.StatusOK, res: data, err: nil, - v: sub, - }, - // { - // desc: "view not existing", - // id: "not existing", - // auth: token, - // status: http.StatusNotFound, - // res: notFoundRes, - // }, - // { - // desc: "view with invalid auth token", - // id: id, - // auth: authmocks.InvalidValue, - // status: http.StatusUnauthorized, - // res: unauthRes, - // }, - // { - // desc: "view with empty auth token", - // id: id, - // auth: "", - // status: http.StatusUnauthorized, - // res: missingTokRes, - // }, - } - - for _, tc := range cases { - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.auth}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Retrieve", mock.Anything, mock.Anything).Return(tc.v, tc.err) - req := testRequest{ - client: ss.Client(), - method: http.MethodGet, - url: fmt.Sprintf("%s/subscriptions/%s", ss.URL, tc.id), - token: tc.auth, - } - res, err := req.make() - assert.Nil(t, err, fmt.Sprintf("%s: unexpected request error %s", tc.desc, err)) - body, err := io.ReadAll(res.Body) - assert.Nil(t, err, fmt.Sprintf("%s: unexpected read error %s", tc.desc, err)) - data := strings.Trim(string(body), "\n") - assert.Equal(t, tc.status, res.StatusCode, fmt.Sprintf("%s: expected status code %d got %d", tc.desc, tc.status, res.StatusCode)) - assert.Equal(t, tc.res, data, fmt.Sprintf("%s: expected body %s got %s", tc.desc, tc.res, data)) - - repoCall.Unset() - repoCall1.Unset() - } -} - -func TestList(t *testing.T) { - svc, auth, _, _ := newService() - ss := newServer(svc) - defer ss.Close() - - const numSubs = 100 - var subs []subRes - - for i := 0; i < numSubs; i++ { - sub := notifiers.Subscription{ - Topic: fmt.Sprintf("topic.subtopic.%d", i), - Contact: contact1, - } - if i%2 == 0 { - sub.Contact = contact2 - } - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: token}).Return(&magistrala.IdentityRes{Id: validID}, nil) - id, err := svc.CreateSubscription(context.Background(), token, sub) - sr := subRes{ - ID: id, - OwnerID: validID, - Contact: sub.Contact, - Topic: sub.Topic, - } - assert.Nil(t, err, fmt.Sprintf("got an error creating id: %s", err)) - repoCall.Unset() - subs = append(subs, sr) - } - noLimit := toJSON(page{Offset: 5, Limit: 20, Total: numSubs, Subscriptions: subs[5:25]}) - one := toJSON(page{Offset: 0, Limit: 20, Total: 1, Subscriptions: subs[10:11]}) - - var contact2Subs []subRes - for i := 20; i < 40; i += 2 { - contact2Subs = append(contact2Subs, subs[i]) - } - contactList := toJSON(page{Offset: 10, Limit: 10, Total: 50, Subscriptions: contact2Subs}) - - cases := []struct { - desc string - query map[string]string - auth string - status int - res string - }{ - { - desc: "list default limit", - query: map[string]string{ - "offset": "5", - }, - auth: token, - status: http.StatusOK, - res: noLimit, - }, - { - desc: "list not existing", - query: map[string]string{ - "topic": "not-found-topic", - }, - auth: token, - status: http.StatusNotFound, - res: notFoundRes, - }, - { - desc: "list one with topic", - query: map[string]string{ - "topic": "topic.subtopic.10", - }, - auth: token, - status: http.StatusOK, - res: one, + Sub: sub, }, { - desc: "list with contact", - query: map[string]string{ - "contact": contact2, - "offset": "10", - "limit": "10", - }, - auth: token, - status: http.StatusOK, - res: contactList, - }, - { - desc: "list with invalid query", - query: map[string]string{ - "offset": "two", - }, - auth: token, - status: http.StatusBadRequest, - res: invalidRes, - }, - { - desc: "list with invalid auth token", - auth: authmocks.InvalidValue, - status: http.StatusUnauthorized, - res: unauthRes, - }, - { - desc: "list with empty auth token", - auth: "", - status: http.StatusUnauthorized, - res: missingTokRes, - }, - } - - for _, tc := range cases { - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.auth}).Return(&magistrala.IdentityRes{Id: validID}, nil) - - req := testRequest{ - client: ss.Client(), - method: http.MethodGet, - url: fmt.Sprintf("%s/subscriptions%s", ss.URL, makeQuery(tc.query)), - token: tc.auth, - } - res, err := req.make() - assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) - body, err := io.ReadAll(res.Body) - assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) - data := strings.Trim(string(body), "\n") - assert.Equal(t, tc.status, res.StatusCode, fmt.Sprintf("%s: expected status code %d got %d", tc.desc, tc.status, res.StatusCode)) - assert.Equal(t, tc.res, data, fmt.Sprintf("%s: got unexpected body\n", tc.desc)) - - repoCall.Unset() - } -} - -func TestRemove(t *testing.T) { - svc, auth, _, _ := newService() - ss := newServer(svc) - defer ss.Close() - - sub := notifiers.Subscription{ - Topic: "topic", - Contact: contact1, - } - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: token}).Return(&magistrala.IdentityRes{Id: validID}, nil) - id, err := svc.CreateSubscription(context.Background(), token, sub) - assert.Nil(t, err, fmt.Sprintf("got an error creating id: %s", err)) - repoCall.Unset() - - cases := []struct { - desc string - id string - auth string - status int - res string - }{ - { - desc: "remove successfully", - id: id, - auth: token, - status: http.StatusNoContent, - }, - { - desc: "remove not existing", + desc: "view not existing", id: "not existing", auth: token, status: http.StatusNotFound, - }, - { - desc: "remove empty id", - id: "", - auth: token, - status: http.StatusBadRequest, + res: notFoundRes, + err: svcerr.ErrNotFound, }, { desc: "view with invalid auth token", @@ -474,6 +260,7 @@ func TestRemove(t *testing.T) { auth: authmocks.InvalidValue, status: http.StatusUnauthorized, res: unauthRes, + err: svcerr.ErrAuthentication, }, { desc: "view with empty auth token", @@ -481,26 +268,229 @@ func TestRemove(t *testing.T) { auth: "", status: http.StatusUnauthorized, res: missingTokRes, + err: svcerr.ErrAuthentication, }, } for _, tc := range cases { - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.auth}).Return(&magistrala.IdentityRes{Id: validID}, nil) + svcCall := svc.On("ViewSubscription", mock.Anything, mock.Anything, tc.id).Return(tc.Sub, tc.err) req := testRequest{ client: ss.Client(), - method: http.MethodDelete, + method: http.MethodGet, url: fmt.Sprintf("%s/subscriptions/%s", ss.URL, tc.id), token: tc.auth, } res, err := req.make() - assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) + assert.Nil(t, err, fmt.Sprintf("%s: unexpected request error %s", tc.desc, err)) + body, err := io.ReadAll(res.Body) + assert.Nil(t, err, fmt.Sprintf("%s: unexpected read error %s", tc.desc, err)) + data := strings.Trim(string(body), "\n") assert.Equal(t, tc.status, res.StatusCode, fmt.Sprintf("%s: expected status code %d got %d", tc.desc, tc.status, res.StatusCode)) + assert.Equal(t, tc.res, data, fmt.Sprintf("%s: expected body %s got %s", tc.desc, tc.res, data)) - repoCall.Unset() + svcCall.Unset() } } +// func TestList(t *testing.T) { +// svc, auth, _, _ := newService() +// ss := newServer(svc) +// defer ss.Close() + +// const numSubs = 100 +// var subs []subRes + +// for i := 0; i < numSubs; i++ { +// sub := notifiers.Subscription{ +// Topic: fmt.Sprintf("topic.subtopic.%d", i), +// Contact: contact1, +// } +// if i%2 == 0 { +// sub.Contact = contact2 +// } +// repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: token}).Return(&magistrala.IdentityRes{Id: validID}, nil) +// id, err := svc.CreateSubscription(context.Background(), token, sub) +// sr := subRes{ +// ID: id, +// OwnerID: validID, +// Contact: sub.Contact, +// Topic: sub.Topic, +// } +// assert.Nil(t, err, fmt.Sprintf("got an error creating id: %s", err)) +// repoCall.Unset() +// subs = append(subs, sr) +// } +// noLimit := toJSON(page{Offset: 5, Limit: 20, Total: numSubs, Subscriptions: subs[5:25]}) +// one := toJSON(page{Offset: 0, Limit: 20, Total: 1, Subscriptions: subs[10:11]}) + +// var contact2Subs []subRes +// for i := 20; i < 40; i += 2 { +// contact2Subs = append(contact2Subs, subs[i]) +// } +// contactList := toJSON(page{Offset: 10, Limit: 10, Total: 50, Subscriptions: contact2Subs}) + +// cases := []struct { +// desc string +// query map[string]string +// auth string +// status int +// res string +// }{ +// { +// desc: "list default limit", +// query: map[string]string{ +// "offset": "5", +// }, +// auth: token, +// status: http.StatusOK, +// res: noLimit, +// }, +// { +// desc: "list not existing", +// query: map[string]string{ +// "topic": "not-found-topic", +// }, +// auth: token, +// status: http.StatusNotFound, +// res: notFoundRes, +// }, +// { +// desc: "list one with topic", +// query: map[string]string{ +// "topic": "topic.subtopic.10", +// }, +// auth: token, +// status: http.StatusOK, +// res: one, +// }, +// { +// desc: "list with contact", +// query: map[string]string{ +// "contact": contact2, +// "offset": "10", +// "limit": "10", +// }, +// auth: token, +// status: http.StatusOK, +// res: contactList, +// }, +// { +// desc: "list with invalid query", +// query: map[string]string{ +// "offset": "two", +// }, +// auth: token, +// status: http.StatusBadRequest, +// res: invalidRes, +// }, +// { +// desc: "list with invalid auth token", +// auth: authmocks.InvalidValue, +// status: http.StatusUnauthorized, +// res: unauthRes, +// }, +// { +// desc: "list with empty auth token", +// auth: "", +// status: http.StatusUnauthorized, +// res: missingTokRes, +// }, +// } + +// for _, tc := range cases { +// repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.auth}).Return(&magistrala.IdentityRes{Id: validID}, nil) + +// req := testRequest{ +// client: ss.Client(), +// method: http.MethodGet, +// url: fmt.Sprintf("%s/subscriptions%s", ss.URL, makeQuery(tc.query)), +// token: tc.auth, +// } +// res, err := req.make() +// assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) +// body, err := io.ReadAll(res.Body) +// assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) +// data := strings.Trim(string(body), "\n") +// assert.Equal(t, tc.status, res.StatusCode, fmt.Sprintf("%s: expected status code %d got %d", tc.desc, tc.status, res.StatusCode)) +// assert.Equal(t, tc.res, data, fmt.Sprintf("%s: got unexpected body\n", tc.desc)) + +// repoCall.Unset() +// } +// } + +// func TestRemove(t *testing.T) { +// svc, auth, _, _ := newService() +// ss := newServer(svc) +// defer ss.Close() + +// sub := notifiers.Subscription{ +// Topic: "topic", +// Contact: contact1, +// } +// repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: token}).Return(&magistrala.IdentityRes{Id: validID}, nil) +// id, err := svc.CreateSubscription(context.Background(), token, sub) +// assert.Nil(t, err, fmt.Sprintf("got an error creating id: %s", err)) +// repoCall.Unset() + +// cases := []struct { +// desc string +// id string +// auth string +// status int +// res string +// }{ +// { +// desc: "remove successfully", +// id: id, +// auth: token, +// status: http.StatusNoContent, +// }, +// { +// desc: "remove not existing", +// id: "not existing", +// auth: token, +// status: http.StatusNotFound, +// }, +// { +// desc: "remove empty id", +// id: "", +// auth: token, +// status: http.StatusBadRequest, +// }, +// { +// desc: "view with invalid auth token", +// id: id, +// auth: authmocks.InvalidValue, +// status: http.StatusUnauthorized, +// res: unauthRes, +// }, +// { +// desc: "view with empty auth token", +// id: id, +// auth: "", +// status: http.StatusUnauthorized, +// res: missingTokRes, +// }, +// } + +// for _, tc := range cases { +// repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.auth}).Return(&magistrala.IdentityRes{Id: validID}, nil) + +// req := testRequest{ +// client: ss.Client(), +// method: http.MethodDelete, +// url: fmt.Sprintf("%s/subscriptions/%s", ss.URL, tc.id), +// token: tc.auth, +// } +// res, err := req.make() +// assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) +// assert.Equal(t, tc.status, res.StatusCode, fmt.Sprintf("%s: expected status code %d got %d", tc.desc, tc.status, res.StatusCode)) + +// repoCall.Unset() +// } +// } + func makeQuery(m map[string]string) string { var ret string for k, v := range m { From bc5f02e78bf32947424be483e3b6b57020dd2ce8 Mon Sep 17 00:00:00 2001 From: nyagamunene Date: Tue, 9 Apr 2024 19:50:12 +0300 Subject: [PATCH 05/18] Debugged endpoint test(continue) Signed-off-by: nyagamunene --- consumers/notifiers/api/endpoint_test.go | 418 ++++++++++++----------- 1 file changed, 218 insertions(+), 200 deletions(-) diff --git a/consumers/notifiers/api/endpoint_test.go b/consumers/notifiers/api/endpoint_test.go index c403bedcc3..a0e1f7ecbe 100644 --- a/consumers/notifiers/api/endpoint_test.go +++ b/consumers/notifiers/api/endpoint_test.go @@ -206,16 +206,15 @@ func TestCreate(t *testing.T) { func TestView(t *testing.T) { ss, svc := newServer() defer ss.Close() - d := testsutil.GenerateUUID(t) sub := notifiers.Subscription{ Topic: topic, Contact: contact1, - ID: d, + ID: testsutil.GenerateUUID(t), OwnerID: validID, } - svcCall := svc.On("CreateSubscription", context.Background(), token, sub).Return(d, nil) + svcCall := svc.On("CreateSubscription", context.Background(), token, sub).Return(sub.ID, nil) id, err := svc.CreateSubscription(context.Background(), token, sub) assert.Nil(t, err, fmt.Sprintf("got an error creating id: %s", err)) svcCall.Unset() @@ -293,203 +292,222 @@ func TestView(t *testing.T) { } } -// func TestList(t *testing.T) { -// svc, auth, _, _ := newService() -// ss := newServer(svc) -// defer ss.Close() - -// const numSubs = 100 -// var subs []subRes - -// for i := 0; i < numSubs; i++ { -// sub := notifiers.Subscription{ -// Topic: fmt.Sprintf("topic.subtopic.%d", i), -// Contact: contact1, -// } -// if i%2 == 0 { -// sub.Contact = contact2 -// } -// repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: token}).Return(&magistrala.IdentityRes{Id: validID}, nil) -// id, err := svc.CreateSubscription(context.Background(), token, sub) -// sr := subRes{ -// ID: id, -// OwnerID: validID, -// Contact: sub.Contact, -// Topic: sub.Topic, -// } -// assert.Nil(t, err, fmt.Sprintf("got an error creating id: %s", err)) -// repoCall.Unset() -// subs = append(subs, sr) -// } -// noLimit := toJSON(page{Offset: 5, Limit: 20, Total: numSubs, Subscriptions: subs[5:25]}) -// one := toJSON(page{Offset: 0, Limit: 20, Total: 1, Subscriptions: subs[10:11]}) - -// var contact2Subs []subRes -// for i := 20; i < 40; i += 2 { -// contact2Subs = append(contact2Subs, subs[i]) -// } -// contactList := toJSON(page{Offset: 10, Limit: 10, Total: 50, Subscriptions: contact2Subs}) - -// cases := []struct { -// desc string -// query map[string]string -// auth string -// status int -// res string -// }{ -// { -// desc: "list default limit", -// query: map[string]string{ -// "offset": "5", -// }, -// auth: token, -// status: http.StatusOK, -// res: noLimit, -// }, -// { -// desc: "list not existing", -// query: map[string]string{ -// "topic": "not-found-topic", -// }, -// auth: token, -// status: http.StatusNotFound, -// res: notFoundRes, -// }, -// { -// desc: "list one with topic", -// query: map[string]string{ -// "topic": "topic.subtopic.10", -// }, -// auth: token, -// status: http.StatusOK, -// res: one, -// }, -// { -// desc: "list with contact", -// query: map[string]string{ -// "contact": contact2, -// "offset": "10", -// "limit": "10", -// }, -// auth: token, -// status: http.StatusOK, -// res: contactList, -// }, -// { -// desc: "list with invalid query", -// query: map[string]string{ -// "offset": "two", -// }, -// auth: token, -// status: http.StatusBadRequest, -// res: invalidRes, -// }, -// { -// desc: "list with invalid auth token", -// auth: authmocks.InvalidValue, -// status: http.StatusUnauthorized, -// res: unauthRes, -// }, -// { -// desc: "list with empty auth token", -// auth: "", -// status: http.StatusUnauthorized, -// res: missingTokRes, -// }, -// } - -// for _, tc := range cases { -// repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.auth}).Return(&magistrala.IdentityRes{Id: validID}, nil) - -// req := testRequest{ -// client: ss.Client(), -// method: http.MethodGet, -// url: fmt.Sprintf("%s/subscriptions%s", ss.URL, makeQuery(tc.query)), -// token: tc.auth, -// } -// res, err := req.make() -// assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) -// body, err := io.ReadAll(res.Body) -// assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) -// data := strings.Trim(string(body), "\n") -// assert.Equal(t, tc.status, res.StatusCode, fmt.Sprintf("%s: expected status code %d got %d", tc.desc, tc.status, res.StatusCode)) -// assert.Equal(t, tc.res, data, fmt.Sprintf("%s: got unexpected body\n", tc.desc)) - -// repoCall.Unset() -// } -// } - -// func TestRemove(t *testing.T) { -// svc, auth, _, _ := newService() -// ss := newServer(svc) -// defer ss.Close() - -// sub := notifiers.Subscription{ -// Topic: "topic", -// Contact: contact1, -// } -// repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: token}).Return(&magistrala.IdentityRes{Id: validID}, nil) -// id, err := svc.CreateSubscription(context.Background(), token, sub) -// assert.Nil(t, err, fmt.Sprintf("got an error creating id: %s", err)) -// repoCall.Unset() - -// cases := []struct { -// desc string -// id string -// auth string -// status int -// res string -// }{ -// { -// desc: "remove successfully", -// id: id, -// auth: token, -// status: http.StatusNoContent, -// }, -// { -// desc: "remove not existing", -// id: "not existing", -// auth: token, -// status: http.StatusNotFound, -// }, -// { -// desc: "remove empty id", -// id: "", -// auth: token, -// status: http.StatusBadRequest, -// }, -// { -// desc: "view with invalid auth token", -// id: id, -// auth: authmocks.InvalidValue, -// status: http.StatusUnauthorized, -// res: unauthRes, -// }, -// { -// desc: "view with empty auth token", -// id: id, -// auth: "", -// status: http.StatusUnauthorized, -// res: missingTokRes, -// }, -// } - -// for _, tc := range cases { -// repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.auth}).Return(&magistrala.IdentityRes{Id: validID}, nil) - -// req := testRequest{ -// client: ss.Client(), -// method: http.MethodDelete, -// url: fmt.Sprintf("%s/subscriptions/%s", ss.URL, tc.id), -// token: tc.auth, -// } -// res, err := req.make() -// assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) -// assert.Equal(t, tc.status, res.StatusCode, fmt.Sprintf("%s: expected status code %d got %d", tc.desc, tc.status, res.StatusCode)) - -// repoCall.Unset() -// } -// } +func TestList(t *testing.T) { + ss, svc := newServer() + defer ss.Close() + + const numSubs = 100 + var subs []subRes + sub := notifiers.Subscription{} + + for i := 0; i < numSubs; i++ { + sub = notifiers.Subscription{ + Topic: fmt.Sprintf("topic.subtopic.%d", i), + Contact: contact1, + ID: testsutil.GenerateUUID(t), + } + if i%2 == 0 { + sub.Contact = contact2 + } + svcCall := svc.On("CreateSubscription", context.Background(), token, sub).Return(sub.ID, nil) + id, err := svc.CreateSubscription(context.Background(), token, sub) + sr := subRes{ + ID: id, + OwnerID: validID, + Contact: sub.Contact, + Topic: sub.Topic, + } + assert.Nil(t, err, fmt.Sprintf("got an error creating id: %s", err)) + svcCall.Unset() + subs = append(subs, sr) + } + noLimit := toJSON(page{Offset: 5, Limit: 20, Total: numSubs, Subscriptions: subs[5:25]}) + // one := toJSON(page{Offset: 0, Limit: 20, Total: 1, Subscriptions: subs[10:11]}) + + var contact2Subs []subRes + for i := 20; i < 40; i += 2 { + contact2Subs = append(contact2Subs, subs[i]) + } + // contactList := toJSON(page{Offset: 10, Limit: 10, Total: 50, Subscriptions: contact2Subs}) + + cases := []struct { + desc string + query map[string]string + auth string + status int + res string + err error + page notifiers.Page + }{ + { + desc: "list default limit", + query: map[string]string{ + "offset": "5", + }, + auth: token, + status: http.StatusOK, + res: noLimit, + err: nil, + page: notifiers.Page{ + Total: numSubs, + Subscriptions: []notifiers.Subscription{sub}, + }, + }, + // { + // desc: "list not existing", + // query: map[string]string{ + // "topic": "not-found-topic", + // }, + // auth: token, + // status: http.StatusNotFound, + // res: notFoundRes, + // err: nil, + // }, + // { + // desc: "list one with topic", + // query: map[string]string{ + // "topic": "topic.subtopic.10", + // }, + // auth: token, + // status: http.StatusOK, + // res: one, + // err: nil, + // }, + // { + // desc: "list with contact", + // query: map[string]string{ + // "contact": contact2, + // "offset": "10", + // "limit": "10", + // }, + // auth: token, + // status: http.StatusOK, + // res: contactList, + // err: nil, + // }, + // { + // desc: "list with invalid query", + // query: map[string]string{ + // "offset": "two", + // }, + // auth: token, + // status: http.StatusBadRequest, + // res: invalidRes, + // err: svcerr.ErrMalformedEntity, + // }, + // { + // desc: "list with invalid auth token", + // auth: authmocks.InvalidValue, + // status: http.StatusUnauthorized, + // res: unauthRes, + // err: svcerr.ErrAuthentication, + // }, + // { + // desc: "list with empty auth token", + // auth: "", + // status: http.StatusUnauthorized, + // res: missingTokRes, + // err: svcerr.ErrAuthentication, + // }, + } + + for _, tc := range cases { + svcCall := svc.On("ListSubscriptions", mock.Anything, mock.Anything, mock.Anything).Return(tc.page, tc.err) + req := testRequest{ + client: ss.Client(), + method: http.MethodGet, + url: fmt.Sprintf("%s/subscriptions%s", ss.URL, makeQuery(tc.query)), + token: tc.auth, + } + res, err := req.make() + assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) + body, err := io.ReadAll(res.Body) + assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) + data := strings.Trim(string(body), "\n") + assert.Equal(t, tc.status, res.StatusCode, fmt.Sprintf("%s: expected status code %d got %d", tc.desc, tc.status, res.StatusCode)) + assert.Equal(t, tc.res, data, fmt.Sprintf("%s: got unexpected body\n", tc.desc)) + + svcCall.Unset() + } +} + +func TestRemove(t *testing.T) { + ss, svc := newServer() + defer ss.Close() + + sub := notifiers.Subscription{ + Topic: "topic", + Contact: contact1, + ID: testsutil.GenerateUUID(t), + } + svcCall := svc.On("CreateSubscription", context.Background(), token, sub).Return(sub.ID, nil) + id, err := svc.CreateSubscription(context.Background(), token, sub) + assert.Nil(t, err, fmt.Sprintf("got an error creating id: %s", err)) + svcCall.Unset() + + cases := []struct { + desc string + id string + auth string + status int + res string + err error + }{ + { + desc: "remove successfully", + id: id, + auth: token, + status: http.StatusNoContent, + err: nil, + }, + { + desc: "remove not existing", + id: "not existing", + auth: token, + status: http.StatusNotFound, + err: svcerr.ErrNotFound, + }, + { + desc: "remove empty id", + id: "", + auth: token, + status: http.StatusBadRequest, + err: svcerr.ErrMalformedEntity, + }, + { + desc: "view with invalid auth token", + id: id, + auth: authmocks.InvalidValue, + status: http.StatusUnauthorized, + res: unauthRes, + err: svcerr.ErrAuthentication, + }, + { + desc: "view with empty auth token", + id: id, + auth: "", + status: http.StatusUnauthorized, + res: missingTokRes, + err: svcerr.ErrAuthentication, + }, + } + + for _, tc := range cases { + svcCall := svc.On("RemoveSubscription", mock.Anything, mock.Anything, tc.id).Return(tc.err) + + req := testRequest{ + client: ss.Client(), + method: http.MethodDelete, + url: fmt.Sprintf("%s/subscriptions/%s", ss.URL, tc.id), + token: tc.auth, + } + res, err := req.make() + assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) + assert.Equal(t, tc.status, res.StatusCode, fmt.Sprintf("%s: expected status code %d got %d", tc.desc, tc.status, res.StatusCode)) + + svcCall.Unset() + } +} func makeQuery(m map[string]string) string { var ret string From d6298d2aaf6dbd9d89dc446a3b6859012816ffe3 Mon Sep 17 00:00:00 2001 From: nyagamunene Date: Thu, 11 Apr 2024 13:31:25 +0300 Subject: [PATCH 06/18] Debugged endpoint test and sdk test Signed-off-by: nyagamunene --- consumers/notifiers/api/endpoint_test.go | 154 ++++++++++++++--------- consumers/notifiers/service_test.go | 8 +- pkg/sdk/go/consumers_test.go | 76 +++++++++-- 3 files changed, 165 insertions(+), 73 deletions(-) diff --git a/consumers/notifiers/api/endpoint_test.go b/consumers/notifiers/api/endpoint_test.go index a0e1f7ecbe..de39768925 100644 --- a/consumers/notifiers/api/endpoint_test.go +++ b/consumers/notifiers/api/endpoint_test.go @@ -14,7 +14,6 @@ import ( "strings" "testing" - // "github.com/absmach/magistrala" authmocks "github.com/absmach/magistrala/auth/mocks" "github.com/absmach/magistrala/consumers/notifiers" httpapi "github.com/absmach/magistrala/consumers/notifiers/api" @@ -298,7 +297,7 @@ func TestList(t *testing.T) { const numSubs = 100 var subs []subRes - sub := notifiers.Subscription{} + var sub notifiers.Subscription for i := 0; i < numSubs; i++ { sub = notifiers.Subscription{ @@ -322,13 +321,13 @@ func TestList(t *testing.T) { subs = append(subs, sr) } noLimit := toJSON(page{Offset: 5, Limit: 20, Total: numSubs, Subscriptions: subs[5:25]}) - // one := toJSON(page{Offset: 0, Limit: 20, Total: 1, Subscriptions: subs[10:11]}) + one := toJSON(page{Offset: 0, Limit: 20, Total: 1, Subscriptions: subs[10:11]}) var contact2Subs []subRes for i := 20; i < 40; i += 2 { contact2Subs = append(contact2Subs, subs[i]) } - // contactList := toJSON(page{Offset: 10, Limit: 10, Total: 50, Subscriptions: contact2Subs}) + contactList := toJSON(page{Offset: 10, Limit: 10, Total: 50, Subscriptions: contact2Subs}) cases := []struct { desc string @@ -349,66 +348,86 @@ func TestList(t *testing.T) { res: noLimit, err: nil, page: notifiers.Page{ + PageMetadata: notifiers.PageMetadata{ + Offset: 5, + Limit: 20, + }, Total: numSubs, - Subscriptions: []notifiers.Subscription{sub}, + Subscriptions: GetSubscriptionsSlice(subs, 5, 25), }, }, - // { - // desc: "list not existing", - // query: map[string]string{ - // "topic": "not-found-topic", - // }, - // auth: token, - // status: http.StatusNotFound, - // res: notFoundRes, - // err: nil, - // }, - // { - // desc: "list one with topic", - // query: map[string]string{ - // "topic": "topic.subtopic.10", - // }, - // auth: token, - // status: http.StatusOK, - // res: one, - // err: nil, - // }, - // { - // desc: "list with contact", - // query: map[string]string{ - // "contact": contact2, - // "offset": "10", - // "limit": "10", - // }, - // auth: token, - // status: http.StatusOK, - // res: contactList, - // err: nil, - // }, - // { - // desc: "list with invalid query", - // query: map[string]string{ - // "offset": "two", - // }, - // auth: token, - // status: http.StatusBadRequest, - // res: invalidRes, - // err: svcerr.ErrMalformedEntity, - // }, - // { - // desc: "list with invalid auth token", - // auth: authmocks.InvalidValue, - // status: http.StatusUnauthorized, - // res: unauthRes, - // err: svcerr.ErrAuthentication, - // }, - // { - // desc: "list with empty auth token", - // auth: "", - // status: http.StatusUnauthorized, - // res: missingTokRes, - // err: svcerr.ErrAuthentication, - // }, + { + desc: "list not existing", + query: map[string]string{ + "topic": "not-found-topic", + }, + auth: token, + status: http.StatusNotFound, + res: notFoundRes, + err: svcerr.ErrNotFound, + }, + { + desc: "list one with topic", + query: map[string]string{ + "topic": "topic.subtopic.10", + }, + auth: token, + status: http.StatusOK, + res: one, + err: nil, + page: notifiers.Page{ + PageMetadata: notifiers.PageMetadata{ + Offset: 0, + Limit: 20, + }, + Total: 1, + Subscriptions: GetSubscriptionsSlice(subs, 10, 11), + }, + }, + { + desc: "list with contact", + query: map[string]string{ + "contact": contact2, + "offset": "10", + "limit": "10", + }, + auth: token, + status: http.StatusOK, + res: contactList, + err: nil, + page: notifiers.Page{ + PageMetadata: notifiers.PageMetadata{ + Offset: 10, + Limit: 10, + }, + Total: 50, + Subscriptions: GetSubscriptionsSlice(contact2Subs, 0, 10), + }, + }, + { + desc: "list with invalid query", + query: map[string]string{ + "offset": "two", + }, + auth: token, + status: http.StatusBadRequest, + res: invalidRes, + err: svcerr.ErrMalformedEntity, + }, + { + desc: "list with invalid auth token", + auth: authmocks.InvalidValue, + status: http.StatusUnauthorized, + res: unauthRes, + err: svcerr.ErrAuthentication, + }, + { + desc: "list with empty auth token", + auth: "", + status: http.StatusUnauthorized, + res: missingTokRes, + err: svcerr.ErrAuthentication, + }, } for _, tc := range cases { @@ -532,3 +551,16 @@ type page struct { Total uint `json:"total,omitempty"` Subscriptions []subRes `json:"subscriptions,omitempty"` } + +func GetSubscriptionsSlice(subs []subRes, start, end int) []notifiers.Subscription { + var result []notifiers.Subscription + for _, sub := range subs { + result = append(result, notifiers.Subscription{ + ID: sub.ID, + OwnerID: sub.OwnerID, + Contact: sub.Contact, + Topic: sub.Topic, + }) + } + return result[start:end] +} diff --git a/consumers/notifiers/service_test.go b/consumers/notifiers/service_test.go index b222ab804e..132a02dcc2 100644 --- a/consumers/notifiers/service_test.go +++ b/consumers/notifiers/service_test.go @@ -87,7 +87,7 @@ func TestViewSubscription(t *testing.T) { svc, auth, repo := newService() sub := notifiers.Subscription{Contact: exampleUser1, Topic: "valid.topic"} repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return("", nil) + repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(validID, nil) id, err := svc.CreateSubscription(context.Background(), exampleUser1, sub) require.Nil(t, err, "Saving a Subscription must succeed") repoCall.Unset() @@ -151,7 +151,7 @@ func TestListSubscriptions(t *testing.T) { } tmp.Topic = fmt.Sprintf("%s.%d", topic, i) repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: token}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return("", nil) + repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(validID, nil) id, err := svc.CreateSubscription(context.Background(), token, tmp) require.Nil(t, err, "Saving a Subscription must succeed") repoCall.Unset() @@ -264,7 +264,7 @@ func TestRemoveSubscription(t *testing.T) { svc, auth, repo := newService() sub := notifiers.Subscription{Contact: exampleUser1, Topic: "valid.topic"} repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return("", nil) + repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(validID, nil) id, err := svc.CreateSubscription(context.Background(), exampleUser1, sub) require.Nil(t, err, "Saving a Subscription must succeed") repoCall.Unset() @@ -322,7 +322,7 @@ func TestConsume(t *testing.T) { tmp.Topic = fmt.Sprintf("%s-2", sub.Topic) } repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return("", nil) + repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(validID, nil) _, err := svc.CreateSubscription(context.Background(), exampleUser1, tmp) require.Nil(t, err, "Saving a Subscription must succeed") repoCall.Unset() diff --git a/pkg/sdk/go/consumers_test.go b/pkg/sdk/go/consumers_test.go index 70e1de4825..17278adf34 100644 --- a/pkg/sdk/go/consumers_test.go +++ b/pkg/sdk/go/consumers_test.go @@ -15,6 +15,7 @@ import ( httpapi "github.com/absmach/magistrala/consumers/notifiers/api" "github.com/absmach/magistrala/consumers/notifiers/mocks" "github.com/absmach/magistrala/internal/apiutil" + "github.com/absmach/magistrala/internal/testsutil" mglog "github.com/absmach/magistrala/logger" "github.com/absmach/magistrala/pkg/errors" svcerr "github.com/absmach/magistrala/pkg/errors/service" @@ -32,12 +33,13 @@ var ( } emptySubscription = sdk.Subscription{} exampleUser1 = "email1@example.com" + ID = testsutil.GenerateUUID(&testing.T{}) ) -func setupSubscriptions() (*httptest.Server, *authmocks.AuthClient) { - repo := mocks.NewRepo(make(map[string]notifiers.Subscription)) +func setupSubscriptions() (*httptest.Server, *authmocks.AuthClient, *mocks.SubscriptionsRepository) { + repo := new(mocks.SubscriptionsRepository) auth := new(authmocks.AuthClient) - notifier := mocks.NewNotifier() + notifier := new(mocks.Notifier) idp := uuid.NewMock() from := "exampleFrom" @@ -45,11 +47,11 @@ func setupSubscriptions() (*httptest.Server, *authmocks.AuthClient) { logger := mglog.NewMock() mux := httpapi.MakeHandler(svc, logger, instanceID) - return httptest.NewServer(mux), auth + return httptest.NewServer(mux), auth, repo } func TestCreateSubscription(t *testing.T) { - ts, auth := setupSubscriptions() + ts, auth, repo := setupSubscriptions() defer ts.Close() sdkConf := sdk.Config{ @@ -66,6 +68,7 @@ func TestCreateSubscription(t *testing.T) { token string err errors.SDKError empty bool + id string }{ { desc: "create new subscription", @@ -73,6 +76,7 @@ func TestCreateSubscription(t *testing.T) { token: exampleUser1, err: nil, empty: false, + id: ID, }, { desc: "create new subscription with empty token", @@ -80,6 +84,7 @@ func TestCreateSubscription(t *testing.T) { token: "", err: errors.NewSDKErrorWithStatus(errors.Wrap(apiutil.ErrValidation, apiutil.ErrBearerToken), http.StatusUnauthorized), empty: true, + id: "", }, { desc: "create new subscription with invalid token", @@ -87,6 +92,7 @@ func TestCreateSubscription(t *testing.T) { token: authmocks.InvalidValue, err: errors.NewSDKErrorWithStatus(svcerr.ErrAuthentication, http.StatusUnauthorized), empty: true, + id: "", }, { desc: "create new empty subscription", @@ -94,20 +100,23 @@ func TestCreateSubscription(t *testing.T) { token: token, err: errors.NewSDKErrorWithStatus(errors.Wrap(apiutil.ErrValidation, apiutil.ErrInvalidTopic), http.StatusBadRequest), empty: true, + id: "", }, } for _, tc := range cases { repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(tc.id, tc.err) loc, err := mgsdk.CreateSubscription(tc.subscription.Topic, tc.subscription.Contact, tc.token) assert.Equal(t, tc.err, err, fmt.Sprintf("%s: expected error %s, got %s", tc.desc, tc.err, err)) assert.Equal(t, tc.empty, loc == "", fmt.Sprintf("%s: expected empty result location, got: %s", tc.desc, loc)) repoCall.Unset() + repoCall1.Unset() } } func TestViewSubscription(t *testing.T) { - ts, auth := setupSubscriptions() + ts, auth, repo := setupSubscriptions() defer ts.Close() sdkConf := sdk.Config{ UsersURL: ts.URL, @@ -117,9 +126,11 @@ func TestViewSubscription(t *testing.T) { mgsdk := sdk.NewSDK(sdkConf) repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(ID, nil) id, err := mgsdk.CreateSubscription("topic", "contact", exampleUser1) require.Nil(t, err, fmt.Sprintf("unexpected error during creating subscription: %s", err)) repoCall.Unset() + repoCall1.Unset() cases := []struct { desc string @@ -153,17 +164,19 @@ func TestViewSubscription(t *testing.T) { for _, tc := range cases { repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Retrieve", mock.Anything, mock.Anything).Return(notifiers.Subscription{Contact: sub1.Contact, Topic: sub1.Topic}, tc.err) respSub, err := mgsdk.ViewSubscription(tc.subID, tc.token) assert.Equal(t, tc.err, err, fmt.Sprintf("%s: expected error %s, got %s", tc.desc, tc.err, err)) tc.response.ID = respSub.ID tc.response.OwnerID = respSub.OwnerID assert.Equal(t, tc.response, respSub, fmt.Sprintf("%s: expected response %s, got %s", tc.desc, tc.response, respSub)) repoCall.Unset() + repoCall1.Unset() } } func TestListSubscription(t *testing.T) { - ts, auth := setupSubscriptions() + ts, auth, repo := setupSubscriptions() defer ts.Close() sdkConf := sdk.Config{ UsersURL: ts.URL, @@ -176,13 +189,17 @@ func TestListSubscription(t *testing.T) { subs := make([]sdk.Subscription, nSubs) for i := 0; i < nSubs; i++ { repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(ID, nil) id, err := mgsdk.CreateSubscription(fmt.Sprintf("topic_%d", i), fmt.Sprintf("contact_%d", i), exampleUser1) require.Nil(t, err, fmt.Sprintf("unexpected error during creating subscription: %s", err)) repoCall.Unset() + repoCall1.Unset() repoCall = auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 = repo.On("Retrieve", mock.Anything, mock.Anything).Return(notifiers.Subscription{Contact: sub1.Contact, Topic: sub1.Topic, ID: id}, nil) sub, err := mgsdk.ViewSubscription(id, exampleUser1) require.Nil(t, err, fmt.Sprintf("unexpected error during getting subscription: %s", err)) repoCall.Unset() + repoCall1.Unset() subs[i] = sub } @@ -192,6 +209,7 @@ func TestListSubscription(t *testing.T) { token string err errors.SDKError response []sdk.Subscription + Page notifiers.Page }{ { desc: "list all subscription", @@ -199,6 +217,13 @@ func TestListSubscription(t *testing.T) { page: sdk.PageMetadata{Offset: 0, Limit: uint64(nSubs)}, err: nil, response: subs, + Page: notifiers.Page{ + PageMetadata: notifiers.PageMetadata{ + Offset: 0, + Limit: nSubs, + }, + Subscriptions: GetSubscriptionsSlice(subs, 0, 10), + }, }, { desc: "list subscription with specific topic", @@ -206,6 +231,14 @@ func TestListSubscription(t *testing.T) { page: sdk.PageMetadata{Offset: 0, Limit: uint64(nSubs), Topic: "topic_1"}, err: nil, response: []sdk.Subscription{subs[1]}, + Page: notifiers.Page{ + PageMetadata: notifiers.PageMetadata{ + Offset: 0, + Limit: nSubs, + Topic: "topic_1", + }, + Subscriptions: GetSubscriptionsSlice(subs, 0, 1), + }, }, { desc: "list subscription with specific contact", @@ -213,20 +246,30 @@ func TestListSubscription(t *testing.T) { page: sdk.PageMetadata{Offset: 0, Limit: uint64(nSubs), Contact: "contact_1"}, err: nil, response: []sdk.Subscription{subs[1]}, + Page: notifiers.Page{ + PageMetadata: notifiers.PageMetadata{ + Offset: 0, + Limit: nSubs, + Contact: "contact_1", + }, + Subscriptions: GetSubscriptionsSlice(subs, 0, 1), + }, }, } for _, tc := range cases { repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("RetrieveAll", mock.Anything, mock.Anything).Return(tc.Page, tc.err) subs, err := mgsdk.ListSubscriptions(tc.page, tc.token) assert.Equal(t, tc.err, err, fmt.Sprintf("%s: expected error %s, got %s", tc.desc, tc.err, err)) assert.Equal(t, tc.response, subs.Subscriptions, fmt.Sprintf("%s: expected response %v, got %v", tc.desc, tc.response, subs.Subscriptions)) repoCall.Unset() + repoCall1.Unset() } } func TestDeleteSubscription(t *testing.T) { - ts, auth := setupSubscriptions() + ts, auth, repo := setupSubscriptions() defer ts.Close() sdkConf := sdk.Config{ UsersURL: ts.URL, @@ -236,9 +279,11 @@ func TestDeleteSubscription(t *testing.T) { mgsdk := sdk.NewSDK(sdkConf) repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(ID, nil) id, err := mgsdk.CreateSubscription("topic", "contact", exampleUser1) require.Nil(t, err, fmt.Sprintf("unexpected error during creating subscription: %s", err)) repoCall.Unset() + repoCall1.Unset() cases := []struct { desc string @@ -272,8 +317,23 @@ func TestDeleteSubscription(t *testing.T) { for _, tc := range cases { repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Remove", mock.Anything, mock.Anything).Return(tc.err) err := mgsdk.DeleteSubscription(tc.subID, tc.token) assert.Equal(t, tc.err, err, fmt.Sprintf("%s: expected error %s, got %s", tc.desc, tc.err, err)) repoCall.Unset() + repoCall1.Unset() } } + +func GetSubscriptionsSlice(subs []sdk.Subscription, start, end int) []notifiers.Subscription { + var result []notifiers.Subscription + for _, sub := range subs { + result = append(result, notifiers.Subscription{ + ID: sub.ID, + OwnerID: sub.OwnerID, + Contact: sub.Contact, + Topic: sub.Topic, + }) + } + return result[start:end] +} From 1d75bbd3f6e8941e801f135e9b3ddac7974980ae Mon Sep 17 00:00:00 2001 From: nyagamunene Date: Thu, 11 Apr 2024 13:40:17 +0300 Subject: [PATCH 07/18] Updated the yml file Signed-off-by: nyagamunene --- .github/workflows/check-generated-files.yml | 9 +++++++++ .../notifiers/mocks/{subscriptions.go => repository.go} | 0 consumers/notifiers/subscriptions.go | 2 +- 3 files changed, 10 insertions(+), 1 deletion(-) rename consumers/notifiers/mocks/{subscriptions.go => repository.go} (100%) diff --git a/.github/workflows/check-generated-files.yml b/.github/workflows/check-generated-files.yml index 3ff3ee001b..adafdfa2ba 100644 --- a/.github/workflows/check-generated-files.yml +++ b/.github/workflows/check-generated-files.yml @@ -66,6 +66,9 @@ jobs: - "mqtt/events/streams.go" - "readers/messages.go" - "lora/routemap.go" + - "consumers/notifiers/notifier.go" + - "consumers/notifiers/service.go" + - "consumers/notifiers/subscriptions.go" - name: Set up protoc if: steps.changes.outputs.proto == 'true' @@ -138,6 +141,9 @@ jobs: mv ./mqtt/mocks/events.go ./mqtt/mocks/events.go.tmp mv ./readers/mocks/messages.go ./readers/mocks/messages.go.tmp mv ./lora/mocks/routes.go ./lora/mocks/routes.go.tmp + mv ./consumers/notifiers/mocks/notifier.go ./consumers/notifiers/mocks/notifier.go.tmp + mv ./consumers/notifiers/mocks/service.go ./consumers/notifiers/mocks/service.go.tmp + mv ./consumers/notifiers/mocks/repository.go ./consumers/notifiers/mocks/repository.go.tmp make mocks @@ -179,3 +185,6 @@ jobs: check_mock_changes ./mqtt/mocks/events.go "MQTT Events Store ./mqtt/mocks/events.go" check_mock_changes ./readers/mocks/messages.go "Message Readers ./readers/mocks/messages.go" check_mock_changes ./lora/mocks/routes.go "LoRa Repository ./lora/mocks/routes.go" + check_mock_changes ./consumers/notifiers/mocks/notifier.go "Notifiers Notifier ./consumers/notifiers/mocks/notifier.go" + check_mock_changes ./consumers/notifiers/mocks/service.go "Notifiers Service ./consumers/notifiers/mocks/service.go" + check_mock_changes ./consumers/notifiers/mocks/repository.go "Notifiers Repository ./consumers/notifiers/mocks/repository.go" diff --git a/consumers/notifiers/mocks/subscriptions.go b/consumers/notifiers/mocks/repository.go similarity index 100% rename from consumers/notifiers/mocks/subscriptions.go rename to consumers/notifiers/mocks/repository.go diff --git a/consumers/notifiers/subscriptions.go b/consumers/notifiers/subscriptions.go index c0e3dcb24e..dcaf4eb60f 100644 --- a/consumers/notifiers/subscriptions.go +++ b/consumers/notifiers/subscriptions.go @@ -31,7 +31,7 @@ type PageMetadata struct { // SubscriptionsRepository specifies a Subscription persistence API. // -//go:generate mockery --name SubscriptionsRepository --output=./mocks --filename subscriptions.go --quiet --note "Copyright (c) Abstract Machines" +//go:generate mockery --name SubscriptionsRepository --output=./mocks --filename repository.go --quiet --note "Copyright (c) Abstract Machines" type SubscriptionsRepository interface { // Save persists a subscription. Successful operation is indicated by non-nil // error response. From 8c8170bfe8130e787fdff8ffb0ff7682df9bf3c4 Mon Sep 17 00:00:00 2001 From: nyagamunene Date: Thu, 11 Apr 2024 16:12:42 +0300 Subject: [PATCH 08/18] Simplified and renamed subscription slice Signed-off-by: nyagamunene --- pkg/sdk/go/consumers_test.go | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/pkg/sdk/go/consumers_test.go b/pkg/sdk/go/consumers_test.go index 17278adf34..0d305df7cc 100644 --- a/pkg/sdk/go/consumers_test.go +++ b/pkg/sdk/go/consumers_test.go @@ -222,7 +222,7 @@ func TestListSubscription(t *testing.T) { Offset: 0, Limit: nSubs, }, - Subscriptions: GetSubscriptionsSlice(subs, 0, 10), + Subscriptions: subscriptionsSlice(subs, 0, 10), }, }, { @@ -237,7 +237,7 @@ func TestListSubscription(t *testing.T) { Limit: nSubs, Topic: "topic_1", }, - Subscriptions: GetSubscriptionsSlice(subs, 0, 1), + Subscriptions: subscriptionsSlice(subs, 0, 1), }, }, { @@ -252,7 +252,7 @@ func TestListSubscription(t *testing.T) { Limit: nSubs, Contact: "contact_1", }, - Subscriptions: GetSubscriptionsSlice(subs, 0, 1), + Subscriptions: subscriptionsSlice(subs, 0, 1), }, }, } @@ -325,15 +325,16 @@ func TestDeleteSubscription(t *testing.T) { } } -func GetSubscriptionsSlice(subs []sdk.Subscription, start, end int) []notifiers.Subscription { - var result []notifiers.Subscription - for _, sub := range subs { - result = append(result, notifiers.Subscription{ +func subscriptionsSlice(subs []sdk.Subscription, start, end int) []notifiers.Subscription { + var res []notifiers.Subscription + for i := start; i < end; i++ { + sub := subs[i] + res = append(res, notifiers.Subscription{ ID: sub.ID, OwnerID: sub.OwnerID, Contact: sub.Contact, Topic: sub.Topic, }) } - return result[start:end] + return res } From 5f48b8cd37ac91364ecfe895423e4f33a133ea3c Mon Sep 17 00:00:00 2001 From: nyagamunene Date: Thu, 11 Apr 2024 19:15:19 +0300 Subject: [PATCH 09/18] Changed endpoint and service test Signed-off-by: nyagamunene --- consumers/notifiers/api/endpoint_test.go | 8 ++-- consumers/notifiers/service_test.go | 53 +++++++++++------------- 2 files changed, 29 insertions(+), 32 deletions(-) diff --git a/consumers/notifiers/api/endpoint_test.go b/consumers/notifiers/api/endpoint_test.go index de39768925..1b459da5b8 100644 --- a/consumers/notifiers/api/endpoint_test.go +++ b/consumers/notifiers/api/endpoint_test.go @@ -181,7 +181,7 @@ func TestCreate(t *testing.T) { } for _, tc := range cases { - svcCall := svc.On("CreateSubscription", mock.Anything, mock.Anything, mock.Anything).Return(path.Base(tc.location), tc.err) + svcCall := svc.On("CreateSubscription", mock.Anything, tc.auth, sub).Return(path.Base(tc.location), tc.err) req := testRequest{ client: ss.Client(), @@ -271,7 +271,7 @@ func TestView(t *testing.T) { } for _, tc := range cases { - svcCall := svc.On("ViewSubscription", mock.Anything, mock.Anything, tc.id).Return(tc.Sub, tc.err) + svcCall := svc.On("ViewSubscription", mock.Anything, tc.auth, tc.id).Return(tc.Sub, tc.err) req := testRequest{ client: ss.Client(), @@ -431,7 +431,7 @@ func TestList(t *testing.T) { } for _, tc := range cases { - svcCall := svc.On("ListSubscriptions", mock.Anything, mock.Anything, mock.Anything).Return(tc.page, tc.err) + svcCall := svc.On("ListSubscriptions", mock.Anything, tc.auth, mock.Anything).Return(tc.page, tc.err) req := testRequest{ client: ss.Client(), method: http.MethodGet, @@ -512,7 +512,7 @@ func TestRemove(t *testing.T) { } for _, tc := range cases { - svcCall := svc.On("RemoveSubscription", mock.Anything, mock.Anything, tc.id).Return(tc.err) + svcCall := svc.On("RemoveSubscription", mock.Anything, tc.auth, tc.id).Return(tc.err) req := testRequest{ client: ss.Client(), diff --git a/consumers/notifiers/service_test.go b/consumers/notifiers/service_test.go index 132a02dcc2..905eb1f6da 100644 --- a/consumers/notifiers/service_test.go +++ b/consumers/notifiers/service_test.go @@ -73,8 +73,8 @@ func TestCreateSubscription(t *testing.T) { } for _, tc := range cases { - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: testsutil.GenerateUUID(t)}, nil) - repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(tc.id, tc.err) + repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: testsutil.GenerateUUID(t)}, nil) + repoCall1 := repo.On("Save", context.Background(), mock.Anything).Return(tc.id, tc.err) id, err := svc.CreateSubscription(context.Background(), tc.token, tc.sub) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) assert.Equal(t, tc.id, id, fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.id, id)) @@ -85,15 +85,12 @@ func TestCreateSubscription(t *testing.T) { func TestViewSubscription(t *testing.T) { svc, auth, repo := newService() - sub := notifiers.Subscription{Contact: exampleUser1, Topic: "valid.topic"} - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(validID, nil) - id, err := svc.CreateSubscription(context.Background(), exampleUser1, sub) - require.Nil(t, err, "Saving a Subscription must succeed") - repoCall.Unset() - repoCall1.Unset() - sub.ID = id - sub.OwnerID = validID + sub := notifiers.Subscription{ + Contact: exampleUser1, + Topic: "valid.topic", + ID: testsutil.GenerateUUID(t), + OwnerID: validID, + } cases := []struct { desc string @@ -105,7 +102,7 @@ func TestViewSubscription(t *testing.T) { { desc: "test success", token: exampleUser1, - id: id, + id: validID, sub: sub, err: nil, }, @@ -119,15 +116,15 @@ func TestViewSubscription(t *testing.T) { { desc: "test with empty token", token: "", - id: id, + id: validID, sub: notifiers.Subscription{}, err: svcerr.ErrAuthentication, }, } for _, tc := range cases { - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Retrieve", mock.Anything, mock.Anything).Return(tc.sub, tc.err) + repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Retrieve", context.Background(), tc.id).Return(tc.sub, tc.err) sub, err := svc.ViewSubscription(context.Background(), tc.token, tc.id) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) assert.Equal(t, tc.sub, sub, fmt.Sprintf("%s: expected %v got %v\n", tc.desc, tc.sub, sub)) @@ -150,8 +147,8 @@ func TestListSubscriptions(t *testing.T) { token = exampleUser2 } tmp.Topic = fmt.Sprintf("%s.%d", topic, i) - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: token}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(validID, nil) + repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: token}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Save", context.Background(), mock.Anything).Return(validID, nil) id, err := svc.CreateSubscription(context.Background(), token, tmp) require.Nil(t, err, "Saving a Subscription must succeed") repoCall.Unset() @@ -250,8 +247,8 @@ func TestListSubscriptions(t *testing.T) { } for _, tc := range cases { - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("RetrieveAll", mock.Anything, mock.Anything).Return(tc.page, tc.err) + repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("RetrieveAll", context.Background(), tc.pageMeta).Return(tc.page, tc.err) page, err := svc.ListSubscriptions(context.Background(), tc.token, tc.pageMeta) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) assert.Equal(t, tc.page, page, fmt.Sprintf("%s: got unexpected page\n", tc.desc)) @@ -263,8 +260,8 @@ func TestListSubscriptions(t *testing.T) { func TestRemoveSubscription(t *testing.T) { svc, auth, repo := newService() sub := notifiers.Subscription{Contact: exampleUser1, Topic: "valid.topic"} - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(validID, nil) + repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Save", context.Background(), mock.Anything).Return(validID, nil) id, err := svc.CreateSubscription(context.Background(), exampleUser1, sub) require.Nil(t, err, "Saving a Subscription must succeed") repoCall.Unset() @@ -299,8 +296,8 @@ func TestRemoveSubscription(t *testing.T) { } for _, tc := range cases { - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Remove", mock.Anything, mock.Anything).Return(tc.err) + repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Remove", context.Background(), tc.id).Return(tc.err) err := svc.RemoveSubscription(context.Background(), tc.token, tc.id) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) repoCall.Unset() @@ -321,8 +318,8 @@ func TestConsume(t *testing.T) { if i%2 == 0 { tmp.Topic = fmt.Sprintf("%s-2", sub.Topic) } - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(validID, nil) + repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Save", context.Background(), mock.Anything).Return(validID, nil) _, err := svc.CreateSubscription(context.Background(), exampleUser1, tmp) require.Nil(t, err, "Saving a Subscription must succeed") repoCall.Unset() @@ -331,8 +328,8 @@ func TestConsume(t *testing.T) { sub.Contact = "invalid@example.com" sub.Topic = fmt.Sprintf("%s-2", sub.Topic) - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return("", nil) + repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall1 := repo.On("Save", context.Background(), mock.Anything).Return("", nil) _, err := svc.CreateSubscription(context.Background(), exampleUser1, sub) require.Nil(t, err, "Saving a Subscription must succeed") repoCall.Unset() @@ -365,7 +362,7 @@ func TestConsume(t *testing.T) { } for _, tc := range cases { - repoCall := repo.On("RetrieveAll", mock.Anything, mock.Anything).Return(notifiers.Page{}, tc.err) + repoCall := repo.On("RetrieveAll", context.TODO(), mock.Anything).Return(notifiers.Page{}, tc.err) err := svc.ConsumeBlocking(context.TODO(), tc.msg) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) repoCall.Unset() From b23a255984973dd1d4923d3683489897b6a9e16d Mon Sep 17 00:00:00 2001 From: nyagamunene Date: Fri, 12 Apr 2024 10:30:31 +0300 Subject: [PATCH 10/18] Renamed GetSubscriptionsSlice and optimized it Signed-off-by: nyagamunene --- consumers/notifiers/api/endpoint_test.go | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/consumers/notifiers/api/endpoint_test.go b/consumers/notifiers/api/endpoint_test.go index 1b459da5b8..49263d04c8 100644 --- a/consumers/notifiers/api/endpoint_test.go +++ b/consumers/notifiers/api/endpoint_test.go @@ -353,7 +353,7 @@ func TestList(t *testing.T) { Limit: 20, }, Total: numSubs, - Subscriptions: GetSubscriptionsSlice(subs, 5, 25), + Subscriptions: subscriptionsSlice(subs, 5, 25), }, }, { @@ -381,7 +381,7 @@ func TestList(t *testing.T) { Limit: 20, }, Total: 1, - Subscriptions: GetSubscriptionsSlice(subs, 10, 11), + Subscriptions: subscriptionsSlice(subs, 10, 11), }, }, { @@ -401,7 +401,7 @@ func TestList(t *testing.T) { Limit: 10, }, Total: 50, - Subscriptions: GetSubscriptionsSlice(contact2Subs, 0, 10), + Subscriptions: subscriptionsSlice(contact2Subs, 0, 10), }, }, { @@ -552,15 +552,16 @@ type page struct { Subscriptions []subRes `json:"subscriptions,omitempty"` } -func GetSubscriptionsSlice(subs []subRes, start, end int) []notifiers.Subscription { - var result []notifiers.Subscription - for _, sub := range subs { - result = append(result, notifiers.Subscription{ +func subscriptionsSlice(subs []subRes, start, end int) []notifiers.Subscription { + var res []notifiers.Subscription + for i := start; i < end; i++ { + sub := subs[i] + res = append(res, notifiers.Subscription{ ID: sub.ID, OwnerID: sub.OwnerID, Contact: sub.Contact, Topic: sub.Topic, }) } - return result[start:end] + return res } From 2a67cb9f2631827440a51335f81d05bcef1e248c Mon Sep 17 00:00:00 2001 From: nyagamunene Date: Tue, 16 Apr 2024 12:52:19 +0300 Subject: [PATCH 11/18] Updated Endpoint test Signed-off-by: nyagamunene --- consumers/notifiers/api/endpoint_test.go | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/consumers/notifiers/api/endpoint_test.go b/consumers/notifiers/api/endpoint_test.go index 49263d04c8..89714dfb65 100644 --- a/consumers/notifiers/api/endpoint_test.go +++ b/consumers/notifiers/api/endpoint_test.go @@ -453,16 +453,7 @@ func TestList(t *testing.T) { func TestRemove(t *testing.T) { ss, svc := newServer() defer ss.Close() - - sub := notifiers.Subscription{ - Topic: "topic", - Contact: contact1, - ID: testsutil.GenerateUUID(t), - } - svcCall := svc.On("CreateSubscription", context.Background(), token, sub).Return(sub.ID, nil) - id, err := svc.CreateSubscription(context.Background(), token, sub) - assert.Nil(t, err, fmt.Sprintf("got an error creating id: %s", err)) - svcCall.Unset() + id := testsutil.GenerateUUID(t) cases := []struct { desc string From 0c385253c37a1562a24fc720351ab1c757b468f8 Mon Sep 17 00:00:00 2001 From: nyagamunene Date: Tue, 16 Apr 2024 14:47:30 +0300 Subject: [PATCH 12/18] Updated consumer test Signed-off-by: nyagamunene --- consumers/notifiers/api/endpoint_test.go | 20 +++-------- consumers/notifiers/service_test.go | 45 ++++++------------------ 2 files changed, 15 insertions(+), 50 deletions(-) diff --git a/consumers/notifiers/api/endpoint_test.go b/consumers/notifiers/api/endpoint_test.go index 89714dfb65..6fc5d4dc62 100644 --- a/consumers/notifiers/api/endpoint_test.go +++ b/consumers/notifiers/api/endpoint_test.go @@ -4,7 +4,6 @@ package api_test import ( - "context" "encoding/json" "fmt" "io" @@ -213,13 +212,8 @@ func TestView(t *testing.T) { OwnerID: validID, } - svcCall := svc.On("CreateSubscription", context.Background(), token, sub).Return(sub.ID, nil) - id, err := svc.CreateSubscription(context.Background(), token, sub) - assert.Nil(t, err, fmt.Sprintf("got an error creating id: %s", err)) - svcCall.Unset() - sr := subRes{ - ID: id, + ID: sub.ID, OwnerID: validID, Contact: sub.Contact, Topic: sub.Topic, @@ -237,7 +231,7 @@ func TestView(t *testing.T) { }{ { desc: "view successfully", - id: id, + id: sub.ID, auth: token, status: http.StatusOK, res: data, @@ -254,7 +248,7 @@ func TestView(t *testing.T) { }, { desc: "view with invalid auth token", - id: id, + id: sub.ID, auth: authmocks.InvalidValue, status: http.StatusUnauthorized, res: unauthRes, @@ -262,7 +256,7 @@ func TestView(t *testing.T) { }, { desc: "view with empty auth token", - id: id, + id: sub.ID, auth: "", status: http.StatusUnauthorized, res: missingTokRes, @@ -308,16 +302,12 @@ func TestList(t *testing.T) { if i%2 == 0 { sub.Contact = contact2 } - svcCall := svc.On("CreateSubscription", context.Background(), token, sub).Return(sub.ID, nil) - id, err := svc.CreateSubscription(context.Background(), token, sub) sr := subRes{ - ID: id, + ID: sub.ID, OwnerID: validID, Contact: sub.Contact, Topic: sub.Topic, } - assert.Nil(t, err, fmt.Sprintf("got an error creating id: %s", err)) - svcCall.Unset() subs = append(subs, sr) } noLimit := toJSON(page{Offset: 5, Limit: 20, Total: numSubs, Subscriptions: subs[5:25]}) diff --git a/consumers/notifiers/service_test.go b/consumers/notifiers/service_test.go index 905eb1f6da..3ca3579ae1 100644 --- a/consumers/notifiers/service_test.go +++ b/consumers/notifiers/service_test.go @@ -20,7 +20,6 @@ import ( "github.com/absmach/magistrala/pkg/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" ) const ( @@ -140,20 +139,12 @@ func TestListSubscriptions(t *testing.T) { var subs []notifiers.Subscription for i := 0; i < total; i++ { tmp := sub - token := exampleUser1 if i%2 == 0 { tmp.Contact = exampleUser2 tmp.OwnerID = exampleUser2 - token = exampleUser2 } tmp.Topic = fmt.Sprintf("%s.%d", topic, i) - repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: token}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Save", context.Background(), mock.Anything).Return(validID, nil) - id, err := svc.CreateSubscription(context.Background(), token, tmp) - require.Nil(t, err, "Saving a Subscription must succeed") - repoCall.Unset() - repoCall1.Unset() - tmp.ID = id + tmp.ID = testsutil.GenerateUUID(t) tmp.OwnerID = validID subs = append(subs, tmp) } @@ -259,15 +250,12 @@ func TestListSubscriptions(t *testing.T) { func TestRemoveSubscription(t *testing.T) { svc, auth, repo := newService() - sub := notifiers.Subscription{Contact: exampleUser1, Topic: "valid.topic"} - repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Save", context.Background(), mock.Anything).Return(validID, nil) - id, err := svc.CreateSubscription(context.Background(), exampleUser1, sub) - require.Nil(t, err, "Saving a Subscription must succeed") - repoCall.Unset() - repoCall1.Unset() - sub.ID = id - sub.OwnerID = validID + sub := notifiers.Subscription{ + Contact: exampleUser1, + Topic: "valid.topic", + ID: testsutil.GenerateUUID(t), + OwnerID: validID, + } cases := []struct { desc string @@ -278,7 +266,7 @@ func TestRemoveSubscription(t *testing.T) { { desc: "test success", token: exampleUser1, - id: id, + id: sub.ID, err: nil, }, { @@ -290,7 +278,7 @@ func TestRemoveSubscription(t *testing.T) { { desc: "test with empty token", token: "", - id: id, + id: sub.ID, err: svcerr.ErrAuthentication, }, } @@ -306,7 +294,7 @@ func TestRemoveSubscription(t *testing.T) { } func TestConsume(t *testing.T) { - svc, auth, repo := newService() + svc, _, repo := newService() sub := notifiers.Subscription{ Contact: exampleUser1, OwnerID: validID, @@ -318,22 +306,9 @@ func TestConsume(t *testing.T) { if i%2 == 0 { tmp.Topic = fmt.Sprintf("%s-2", sub.Topic) } - repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Save", context.Background(), mock.Anything).Return(validID, nil) - _, err := svc.CreateSubscription(context.Background(), exampleUser1, tmp) - require.Nil(t, err, "Saving a Subscription must succeed") - repoCall.Unset() - repoCall1.Unset() } - sub.Contact = "invalid@example.com" sub.Topic = fmt.Sprintf("%s-2", sub.Topic) - repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Save", context.Background(), mock.Anything).Return("", nil) - _, err := svc.CreateSubscription(context.Background(), exampleUser1, sub) - require.Nil(t, err, "Saving a Subscription must succeed") - repoCall.Unset() - repoCall1.Unset() msg := messaging.Message{ Channel: "topic", From b82dbae0784438ad28ae10d98e5618d5e0397355 Mon Sep 17 00:00:00 2001 From: nyagamunene Date: Tue, 16 Apr 2024 17:39:58 +0300 Subject: [PATCH 13/18] Updated consumer test pkg Signed-off-by: nyagamunene --- pkg/sdk/go/consumers_test.go | 36 ++++-------------------------------- 1 file changed, 4 insertions(+), 32 deletions(-) diff --git a/pkg/sdk/go/consumers_test.go b/pkg/sdk/go/consumers_test.go index 0d305df7cc..58f2161c5c 100644 --- a/pkg/sdk/go/consumers_test.go +++ b/pkg/sdk/go/consumers_test.go @@ -23,7 +23,6 @@ import ( "github.com/absmach/magistrala/pkg/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" ) var ( @@ -125,12 +124,6 @@ func TestViewSubscription(t *testing.T) { } mgsdk := sdk.NewSDK(sdkConf) - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(ID, nil) - id, err := mgsdk.CreateSubscription("topic", "contact", exampleUser1) - require.Nil(t, err, fmt.Sprintf("unexpected error during creating subscription: %s", err)) - repoCall.Unset() - repoCall1.Unset() cases := []struct { desc string @@ -141,7 +134,7 @@ func TestViewSubscription(t *testing.T) { }{ { desc: "get existing subscription", - subID: id, + subID: ID, token: exampleUser1, err: nil, response: sub1, @@ -155,7 +148,7 @@ func TestViewSubscription(t *testing.T) { }, { desc: "get subscription with invalid token", - subID: id, + subID: ID, token: "", err: errors.NewSDKErrorWithStatus(errors.Wrap(apiutil.ErrValidation, apiutil.ErrBearerToken), http.StatusUnauthorized), response: sdk.Subscription{}, @@ -187,21 +180,6 @@ func TestListSubscription(t *testing.T) { mgsdk := sdk.NewSDK(sdkConf) nSubs := 10 subs := make([]sdk.Subscription, nSubs) - for i := 0; i < nSubs; i++ { - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(ID, nil) - id, err := mgsdk.CreateSubscription(fmt.Sprintf("topic_%d", i), fmt.Sprintf("contact_%d", i), exampleUser1) - require.Nil(t, err, fmt.Sprintf("unexpected error during creating subscription: %s", err)) - repoCall.Unset() - repoCall1.Unset() - repoCall = auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 = repo.On("Retrieve", mock.Anything, mock.Anything).Return(notifiers.Subscription{Contact: sub1.Contact, Topic: sub1.Topic, ID: id}, nil) - sub, err := mgsdk.ViewSubscription(id, exampleUser1) - require.Nil(t, err, fmt.Sprintf("unexpected error during getting subscription: %s", err)) - repoCall.Unset() - repoCall1.Unset() - subs[i] = sub - } cases := []struct { desc string @@ -278,12 +256,6 @@ func TestDeleteSubscription(t *testing.T) { } mgsdk := sdk.NewSDK(sdkConf) - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: exampleUser1}).Return(&magistrala.IdentityRes{Id: validID}, nil) - repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(ID, nil) - id, err := mgsdk.CreateSubscription("topic", "contact", exampleUser1) - require.Nil(t, err, fmt.Sprintf("unexpected error during creating subscription: %s", err)) - repoCall.Unset() - repoCall1.Unset() cases := []struct { desc string @@ -294,7 +266,7 @@ func TestDeleteSubscription(t *testing.T) { }{ { desc: "delete existing subscription", - subID: id, + subID: ID, token: exampleUser1, err: nil, response: sub1, @@ -308,7 +280,7 @@ func TestDeleteSubscription(t *testing.T) { }, { desc: "delete subscription with invalid token", - subID: id, + subID: ID, token: "", err: errors.NewSDKErrorWithStatus(errors.Wrap(apiutil.ErrValidation, apiutil.ErrBearerToken), http.StatusUnauthorized), response: sdk.Subscription{}, From 9a7d04a167a52b353b8052a45a1695bf1d6e5e2d Mon Sep 17 00:00:00 2001 From: nyagamunene Date: Tue, 16 Apr 2024 18:18:02 +0300 Subject: [PATCH 14/18] Updated consumers test pkg Signed-off-by: nyagamunene --- pkg/sdk/go/consumers_test.go | 138 +++++++++++++++++++++-------------- 1 file changed, 85 insertions(+), 53 deletions(-) diff --git a/pkg/sdk/go/consumers_test.go b/pkg/sdk/go/consumers_test.go index 58f2161c5c..d2abbd1d53 100644 --- a/pkg/sdk/go/consumers_test.go +++ b/pkg/sdk/go/consumers_test.go @@ -68,6 +68,8 @@ func TestCreateSubscription(t *testing.T) { err errors.SDKError empty bool id string + identifyErr error + identityRes *magistrala.IdentityRes }{ { desc: "create new subscription", @@ -76,6 +78,8 @@ func TestCreateSubscription(t *testing.T) { err: nil, empty: false, id: ID, + identifyErr: nil, + identityRes: &magistrala.IdentityRes{Id: validID}, }, { desc: "create new subscription with empty token", @@ -84,6 +88,8 @@ func TestCreateSubscription(t *testing.T) { err: errors.NewSDKErrorWithStatus(errors.Wrap(apiutil.ErrValidation, apiutil.ErrBearerToken), http.StatusUnauthorized), empty: true, id: "", + identifyErr: svcerr.ErrAuthorization, + identityRes: nil, }, { desc: "create new subscription with invalid token", @@ -92,6 +98,8 @@ func TestCreateSubscription(t *testing.T) { err: errors.NewSDKErrorWithStatus(svcerr.ErrAuthentication, http.StatusUnauthorized), empty: true, id: "", + identifyErr: svcerr.ErrAuthorization, + identityRes: nil, }, { desc: "create new empty subscription", @@ -100,11 +108,13 @@ func TestCreateSubscription(t *testing.T) { err: errors.NewSDKErrorWithStatus(errors.Wrap(apiutil.ErrValidation, apiutil.ErrInvalidTopic), http.StatusBadRequest), empty: true, id: "", + identifyErr: nil, + identityRes: &magistrala.IdentityRes{Id: validID}, }, } for _, tc := range cases { - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(tc.identityRes, tc.identifyErr) repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(tc.id, tc.err) loc, err := mgsdk.CreateSubscription(tc.subscription.Topic, tc.subscription.Contact, tc.token) assert.Equal(t, tc.err, err, fmt.Sprintf("%s: expected error %s, got %s", tc.desc, tc.err, err)) @@ -126,37 +136,44 @@ func TestViewSubscription(t *testing.T) { mgsdk := sdk.NewSDK(sdkConf) cases := []struct { - desc string - subID string - token string - err errors.SDKError - response sdk.Subscription + desc string + subID string + token string + err errors.SDKError + response sdk.Subscription + identifyErr error + identityRes *magistrala.IdentityRes }{ { - desc: "get existing subscription", - subID: ID, - token: exampleUser1, - err: nil, - response: sub1, + desc: "get existing subscription", + subID: ID, + token: exampleUser1, + err: nil, + response: sub1, + identifyErr: nil, + identityRes: &magistrala.IdentityRes{Id: validID}, }, { - desc: "get non-existent subscription", - subID: "43", - token: exampleUser1, - err: errors.NewSDKErrorWithStatus(svcerr.ErrNotFound, http.StatusNotFound), - response: sdk.Subscription{}, + desc: "get non-existent subscription", + subID: "43", + token: exampleUser1, + err: errors.NewSDKErrorWithStatus(svcerr.ErrNotFound, http.StatusNotFound), + response: sdk.Subscription{}, + identifyErr: nil, + identityRes: &magistrala.IdentityRes{Id: validID}, }, { - desc: "get subscription with invalid token", - subID: ID, - token: "", - err: errors.NewSDKErrorWithStatus(errors.Wrap(apiutil.ErrValidation, apiutil.ErrBearerToken), http.StatusUnauthorized), - response: sdk.Subscription{}, + desc: "get subscription with invalid token", + subID: ID, + token: "", + err: errors.NewSDKErrorWithStatus(errors.Wrap(apiutil.ErrValidation, apiutil.ErrBearerToken), http.StatusUnauthorized), + response: sdk.Subscription{}, + identifyErr: svcerr.ErrAuthorization, }, } for _, tc := range cases { - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(tc.identityRes, tc.err) repoCall1 := repo.On("Retrieve", mock.Anything, mock.Anything).Return(notifiers.Subscription{Contact: sub1.Contact, Topic: sub1.Topic}, tc.err) respSub, err := mgsdk.ViewSubscription(tc.subID, tc.token) assert.Equal(t, tc.err, err, fmt.Sprintf("%s: expected error %s, got %s", tc.desc, tc.err, err)) @@ -182,12 +199,14 @@ func TestListSubscription(t *testing.T) { subs := make([]sdk.Subscription, nSubs) cases := []struct { - desc string - page sdk.PageMetadata - token string - err errors.SDKError - response []sdk.Subscription - Page notifiers.Page + desc string + page sdk.PageMetadata + token string + err errors.SDKError + response []sdk.Subscription + Page notifiers.Page + identifyErr error + identityRes *magistrala.IdentityRes }{ { desc: "list all subscription", @@ -200,8 +219,10 @@ func TestListSubscription(t *testing.T) { Offset: 0, Limit: nSubs, }, - Subscriptions: subscriptionsSlice(subs, 0, 10), + Subscriptions: subSlice(subs, 0, 10), }, + identifyErr: nil, + identityRes: &magistrala.IdentityRes{Id: validID}, }, { desc: "list subscription with specific topic", @@ -215,8 +236,10 @@ func TestListSubscription(t *testing.T) { Limit: nSubs, Topic: "topic_1", }, - Subscriptions: subscriptionsSlice(subs, 0, 1), + Subscriptions: subSlice(subs, 0, 1), }, + identifyErr: nil, + identityRes: &magistrala.IdentityRes{Id: validID}, }, { desc: "list subscription with specific contact", @@ -230,13 +253,15 @@ func TestListSubscription(t *testing.T) { Limit: nSubs, Contact: "contact_1", }, - Subscriptions: subscriptionsSlice(subs, 0, 1), + Subscriptions: subSlice(subs, 0, 1), }, + identifyErr: nil, + identityRes: &magistrala.IdentityRes{Id: validID}, }, } for _, tc := range cases { - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(tc.identityRes, tc.identifyErr) repoCall1 := repo.On("RetrieveAll", mock.Anything, mock.Anything).Return(tc.Page, tc.err) subs, err := mgsdk.ListSubscriptions(tc.page, tc.token) assert.Equal(t, tc.err, err, fmt.Sprintf("%s: expected error %s, got %s", tc.desc, tc.err, err)) @@ -258,32 +283,39 @@ func TestDeleteSubscription(t *testing.T) { mgsdk := sdk.NewSDK(sdkConf) cases := []struct { - desc string - subID string - token string - err errors.SDKError - response sdk.Subscription + desc string + subID string + token string + err errors.SDKError + response sdk.Subscription + identifyErr error + identityRes *magistrala.IdentityRes }{ { - desc: "delete existing subscription", - subID: ID, - token: exampleUser1, - err: nil, - response: sub1, + desc: "delete existing subscription", + subID: ID, + token: exampleUser1, + err: nil, + response: sub1, + identifyErr: nil, + identityRes: &magistrala.IdentityRes{Id: validID}, }, { - desc: "delete non-existent subscription", - subID: "43", - token: exampleUser1, - err: errors.NewSDKErrorWithStatus(svcerr.ErrNotFound, http.StatusNotFound), - response: sdk.Subscription{}, + desc: "delete non-existent subscription", + subID: "43", + token: exampleUser1, + err: errors.NewSDKErrorWithStatus(svcerr.ErrNotFound, http.StatusNotFound), + response: sdk.Subscription{}, + identifyErr: nil, + identityRes: &magistrala.IdentityRes{Id: validID}, }, { - desc: "delete subscription with invalid token", - subID: ID, - token: "", - err: errors.NewSDKErrorWithStatus(errors.Wrap(apiutil.ErrValidation, apiutil.ErrBearerToken), http.StatusUnauthorized), - response: sdk.Subscription{}, + desc: "delete subscription with invalid token", + subID: ID, + token: "", + err: errors.NewSDKErrorWithStatus(errors.Wrap(apiutil.ErrValidation, apiutil.ErrBearerToken), http.StatusUnauthorized), + response: sdk.Subscription{}, + identifyErr: svcerr.ErrAuthorization, }, } @@ -297,7 +329,7 @@ func TestDeleteSubscription(t *testing.T) { } } -func subscriptionsSlice(subs []sdk.Subscription, start, end int) []notifiers.Subscription { +func subSlice(subs []sdk.Subscription, start, end int) []notifiers.Subscription { var res []notifiers.Subscription for i := start; i < end; i++ { sub := subs[i] From 519ea8e5390e8ebc77f3a586566c42f33628d38d Mon Sep 17 00:00:00 2001 From: nyagamunene Date: Tue, 16 Apr 2024 18:24:51 +0300 Subject: [PATCH 15/18] Updated consumers test pkg Signed-off-by: nyagamunene --- pkg/sdk/go/consumers_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/sdk/go/consumers_test.go b/pkg/sdk/go/consumers_test.go index d2abbd1d53..7403161682 100644 --- a/pkg/sdk/go/consumers_test.go +++ b/pkg/sdk/go/consumers_test.go @@ -320,7 +320,7 @@ func TestDeleteSubscription(t *testing.T) { } for _, tc := range cases { - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(tc.identityRes, tc.err) repoCall1 := repo.On("Remove", mock.Anything, mock.Anything).Return(tc.err) err := mgsdk.DeleteSubscription(tc.subID, tc.token) assert.Equal(t, tc.err, err, fmt.Sprintf("%s: expected error %s, got %s", tc.desc, tc.err, err)) From c00b43de20982285ac3ca0d639abdb11c319f027 Mon Sep 17 00:00:00 2001 From: nyagamunene Date: Thu, 18 Apr 2024 12:44:56 +0300 Subject: [PATCH 16/18] Changed auth repo call Signed-off-by: nyagamunene --- consumers/notifiers/service_test.go | 134 +++++++++++++++++----------- pkg/sdk/go/consumers_test.go | 2 +- 2 files changed, 84 insertions(+), 52 deletions(-) diff --git a/consumers/notifiers/service_test.go b/consumers/notifiers/service_test.go index 3ca3579ae1..2579f34408 100644 --- a/consumers/notifiers/service_test.go +++ b/consumers/notifiers/service_test.go @@ -47,6 +47,8 @@ func TestCreateSubscription(t *testing.T) { sub notifiers.Subscription id string err error + identifyErr error + identityRes *magistrala.IdentityRes }{ { desc: "test success", @@ -54,6 +56,8 @@ func TestCreateSubscription(t *testing.T) { sub: notifiers.Subscription{Contact: exampleUser1, Topic: "valid.topic"}, id: uuid.Prefix + fmt.Sprintf("%012d", 1), err: nil, + identifyErr: nil, + identityRes: &magistrala.IdentityRes{Id: validID}, }, { desc: "test already existing", @@ -61,6 +65,8 @@ func TestCreateSubscription(t *testing.T) { sub: notifiers.Subscription{Contact: exampleUser1, Topic: "valid.topic"}, id: "", err: repoerr.ErrConflict, + identifyErr: nil, + identityRes: &magistrala.IdentityRes{Id: validID}, }, { desc: "test with empty token", @@ -68,11 +74,12 @@ func TestCreateSubscription(t *testing.T) { sub: notifiers.Subscription{Contact: exampleUser1, Topic: "valid.topic"}, id: "", err: svcerr.ErrAuthentication, + identifyErr: svcerr.ErrAuthentication, }, } for _, tc := range cases { - repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: testsutil.GenerateUUID(t)}, nil) + repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: tc.token}).Return(tc.identityRes, tc.identifyErr) repoCall1 := repo.On("Save", context.Background(), mock.Anything).Return(tc.id, tc.err) id, err := svc.CreateSubscription(context.Background(), tc.token, tc.sub) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) @@ -92,37 +99,44 @@ func TestViewSubscription(t *testing.T) { } cases := []struct { - desc string - token string - id string - sub notifiers.Subscription - err error + desc string + token string + id string + sub notifiers.Subscription + err error + identifyErr error + identityRes *magistrala.IdentityRes }{ { - desc: "test success", - token: exampleUser1, - id: validID, - sub: sub, - err: nil, + desc: "test success", + token: exampleUser1, + id: validID, + sub: sub, + err: nil, + identifyErr: nil, + identityRes: &magistrala.IdentityRes{Id: validID}, }, { - desc: "test not existing", - token: exampleUser1, - id: "not_exist", - sub: notifiers.Subscription{}, - err: svcerr.ErrNotFound, + desc: "test not existing", + token: exampleUser1, + id: "not_exist", + sub: notifiers.Subscription{}, + err: svcerr.ErrNotFound, + identifyErr: nil, + identityRes: &magistrala.IdentityRes{Id: validID}, }, { - desc: "test with empty token", - token: "", - id: validID, - sub: notifiers.Subscription{}, - err: svcerr.ErrAuthentication, + desc: "test with empty token", + token: "", + id: validID, + sub: notifiers.Subscription{}, + err: svcerr.ErrAuthentication, + identifyErr: svcerr.ErrAuthentication, }, } for _, tc := range cases { - repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: tc.token}).Return(tc.identityRes, tc.identifyErr) repoCall1 := repo.On("Retrieve", context.Background(), tc.id).Return(tc.sub, tc.err) sub, err := svc.ViewSubscription(context.Background(), tc.token, tc.id) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) @@ -155,11 +169,13 @@ func TestListSubscriptions(t *testing.T) { } cases := []struct { - desc string - token string - pageMeta notifiers.PageMetadata - page notifiers.Page - err error + desc string + token string + pageMeta notifiers.PageMetadata + page notifiers.Page + err error + identifyErr error + identityRes *magistrala.IdentityRes }{ { desc: "test success", @@ -177,6 +193,8 @@ func TestListSubscriptions(t *testing.T) { Subscriptions: subs[:3], Total: total, }, + identifyErr: nil, + identityRes: &magistrala.IdentityRes{Id: validID}, }, { desc: "test not existing", @@ -185,8 +203,10 @@ func TestListSubscriptions(t *testing.T) { Limit: 10, Contact: "empty@example.com", }, - page: notifiers.Page{}, - err: svcerr.ErrNotFound, + page: notifiers.Page{}, + err: svcerr.ErrNotFound, + identifyErr: nil, + identityRes: &magistrala.IdentityRes{Id: validID}, }, { desc: "test with empty token", @@ -196,8 +216,9 @@ func TestListSubscriptions(t *testing.T) { Limit: 12, Topic: "topic.subtopic.13", }, - page: notifiers.Page{}, - err: svcerr.ErrAuthentication, + page: notifiers.Page{}, + err: svcerr.ErrAuthentication, + identifyErr: svcerr.ErrAuthentication, }, { desc: "test with topic", @@ -214,7 +235,9 @@ func TestListSubscriptions(t *testing.T) { Subscriptions: subs[4:5], Total: 1, }, - err: nil, + err: nil, + identifyErr: nil, + identityRes: &magistrala.IdentityRes{Id: validID}, }, { desc: "test with contact and offset", @@ -233,12 +256,14 @@ func TestListSubscriptions(t *testing.T) { Subscriptions: offsetSubs, Total: uint(total / 2), }, - err: nil, + err: nil, + identifyErr: nil, + identityRes: &magistrala.IdentityRes{Id: validID}, }, } for _, tc := range cases { - repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: tc.token}).Return(tc.identityRes, tc.identifyErr) repoCall1 := repo.On("RetrieveAll", context.Background(), tc.pageMeta).Return(tc.page, tc.err) page, err := svc.ListSubscriptions(context.Background(), tc.token, tc.pageMeta) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) @@ -258,33 +283,40 @@ func TestRemoveSubscription(t *testing.T) { } cases := []struct { - desc string - token string - id string - err error + desc string + token string + id string + err error + identifyErr error + identityRes *magistrala.IdentityRes }{ { - desc: "test success", - token: exampleUser1, - id: sub.ID, - err: nil, + desc: "test success", + token: exampleUser1, + id: sub.ID, + err: nil, + identifyErr: nil, + identityRes: &magistrala.IdentityRes{Id: validID}, }, { - desc: "test not existing", - token: exampleUser1, - id: "not_exist", - err: svcerr.ErrNotFound, + desc: "test not existing", + token: exampleUser1, + id: "not_exist", + err: svcerr.ErrNotFound, + identifyErr: nil, + identityRes: &magistrala.IdentityRes{Id: validID}, }, { - desc: "test with empty token", - token: "", - id: sub.ID, - err: svcerr.ErrAuthentication, + desc: "test with empty token", + token: "", + id: sub.ID, + err: svcerr.ErrAuthentication, + identifyErr: svcerr.ErrAuthentication, }, } for _, tc := range cases { - repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: validID}, nil) + repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: tc.token}).Return(tc.identityRes, tc.identifyErr) repoCall1 := repo.On("Remove", context.Background(), tc.id).Return(tc.err) err := svc.RemoveSubscription(context.Background(), tc.token, tc.id) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) diff --git a/pkg/sdk/go/consumers_test.go b/pkg/sdk/go/consumers_test.go index 7403161682..87faecd2ba 100644 --- a/pkg/sdk/go/consumers_test.go +++ b/pkg/sdk/go/consumers_test.go @@ -173,7 +173,7 @@ func TestViewSubscription(t *testing.T) { } for _, tc := range cases { - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(tc.identityRes, tc.err) + repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(tc.identityRes, tc.identifyErr) repoCall1 := repo.On("Retrieve", mock.Anything, mock.Anything).Return(notifiers.Subscription{Contact: sub1.Contact, Topic: sub1.Topic}, tc.err) respSub, err := mgsdk.ViewSubscription(tc.subID, tc.token) assert.Equal(t, tc.err, err, fmt.Sprintf("%s: expected error %s, got %s", tc.desc, tc.err, err)) From b8a2968dce6ed3112d962dba8a35a14a508e6f33 Mon Sep 17 00:00:00 2001 From: nyagamunene Date: Thu, 18 Apr 2024 18:22:18 +0300 Subject: [PATCH 17/18] Linted code Signed-off-by: nyagamunene --- consumers/notifiers/service_test.go | 40 ++++++++++++++--------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/consumers/notifiers/service_test.go b/consumers/notifiers/service_test.go index 2579f34408..e1355fa982 100644 --- a/consumers/notifiers/service_test.go +++ b/consumers/notifiers/service_test.go @@ -42,38 +42,38 @@ func TestCreateSubscription(t *testing.T) { svc, auth, repo := newService() cases := []struct { - desc string - token string - sub notifiers.Subscription - id string - err error + desc string + token string + sub notifiers.Subscription + id string + err error identifyErr error identityRes *magistrala.IdentityRes }{ { - desc: "test success", - token: exampleUser1, - sub: notifiers.Subscription{Contact: exampleUser1, Topic: "valid.topic"}, - id: uuid.Prefix + fmt.Sprintf("%012d", 1), - err: nil, + desc: "test success", + token: exampleUser1, + sub: notifiers.Subscription{Contact: exampleUser1, Topic: "valid.topic"}, + id: uuid.Prefix + fmt.Sprintf("%012d", 1), + err: nil, identifyErr: nil, identityRes: &magistrala.IdentityRes{Id: validID}, }, { - desc: "test already existing", - token: exampleUser1, - sub: notifiers.Subscription{Contact: exampleUser1, Topic: "valid.topic"}, - id: "", - err: repoerr.ErrConflict, + desc: "test already existing", + token: exampleUser1, + sub: notifiers.Subscription{Contact: exampleUser1, Topic: "valid.topic"}, + id: "", + err: repoerr.ErrConflict, identifyErr: nil, identityRes: &magistrala.IdentityRes{Id: validID}, }, { - desc: "test with empty token", - token: "", - sub: notifiers.Subscription{Contact: exampleUser1, Topic: "valid.topic"}, - id: "", - err: svcerr.ErrAuthentication, + desc: "test with empty token", + token: "", + sub: notifiers.Subscription{Contact: exampleUser1, Topic: "valid.topic"}, + id: "", + err: svcerr.ErrAuthentication, identifyErr: svcerr.ErrAuthentication, }, } From e27b595f7f03fdc0474907a2b39e93f7f8aba704 Mon Sep 17 00:00:00 2001 From: nyagamunene Date: Mon, 22 Apr 2024 11:43:10 +0300 Subject: [PATCH 18/18] Removed the indentifier response Signed-off-by: nyagamunene --- consumers/notifiers/service_test.go | 36 ++++++++++++++--------------- pkg/sdk/go/consumers_test.go | 36 ++++++++++++++--------------- 2 files changed, 35 insertions(+), 37 deletions(-) diff --git a/consumers/notifiers/service_test.go b/consumers/notifiers/service_test.go index e1355fa982..28facdcf0d 100644 --- a/consumers/notifiers/service_test.go +++ b/consumers/notifiers/service_test.go @@ -48,7 +48,7 @@ func TestCreateSubscription(t *testing.T) { id string err error identifyErr error - identityRes *magistrala.IdentityRes + userID string }{ { desc: "test success", @@ -57,7 +57,7 @@ func TestCreateSubscription(t *testing.T) { id: uuid.Prefix + fmt.Sprintf("%012d", 1), err: nil, identifyErr: nil, - identityRes: &magistrala.IdentityRes{Id: validID}, + userID: validID, }, { desc: "test already existing", @@ -66,7 +66,7 @@ func TestCreateSubscription(t *testing.T) { id: "", err: repoerr.ErrConflict, identifyErr: nil, - identityRes: &magistrala.IdentityRes{Id: validID}, + userID: validID, }, { desc: "test with empty token", @@ -79,7 +79,7 @@ func TestCreateSubscription(t *testing.T) { } for _, tc := range cases { - repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: tc.token}).Return(tc.identityRes, tc.identifyErr) + repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: tc.userID}, tc.identifyErr) repoCall1 := repo.On("Save", context.Background(), mock.Anything).Return(tc.id, tc.err) id, err := svc.CreateSubscription(context.Background(), tc.token, tc.sub) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) @@ -105,7 +105,7 @@ func TestViewSubscription(t *testing.T) { sub notifiers.Subscription err error identifyErr error - identityRes *magistrala.IdentityRes + userID string }{ { desc: "test success", @@ -114,7 +114,7 @@ func TestViewSubscription(t *testing.T) { sub: sub, err: nil, identifyErr: nil, - identityRes: &magistrala.IdentityRes{Id: validID}, + userID: validID, }, { desc: "test not existing", @@ -123,7 +123,7 @@ func TestViewSubscription(t *testing.T) { sub: notifiers.Subscription{}, err: svcerr.ErrNotFound, identifyErr: nil, - identityRes: &magistrala.IdentityRes{Id: validID}, + userID: validID, }, { desc: "test with empty token", @@ -136,7 +136,7 @@ func TestViewSubscription(t *testing.T) { } for _, tc := range cases { - repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: tc.token}).Return(tc.identityRes, tc.identifyErr) + repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: tc.userID}, tc.identifyErr) repoCall1 := repo.On("Retrieve", context.Background(), tc.id).Return(tc.sub, tc.err) sub, err := svc.ViewSubscription(context.Background(), tc.token, tc.id) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) @@ -175,7 +175,7 @@ func TestListSubscriptions(t *testing.T) { page notifiers.Page err error identifyErr error - identityRes *magistrala.IdentityRes + userID string }{ { desc: "test success", @@ -194,7 +194,7 @@ func TestListSubscriptions(t *testing.T) { Total: total, }, identifyErr: nil, - identityRes: &magistrala.IdentityRes{Id: validID}, + userID: validID, }, { desc: "test not existing", @@ -206,7 +206,7 @@ func TestListSubscriptions(t *testing.T) { page: notifiers.Page{}, err: svcerr.ErrNotFound, identifyErr: nil, - identityRes: &magistrala.IdentityRes{Id: validID}, + userID: validID, }, { desc: "test with empty token", @@ -237,7 +237,7 @@ func TestListSubscriptions(t *testing.T) { }, err: nil, identifyErr: nil, - identityRes: &magistrala.IdentityRes{Id: validID}, + userID: validID, }, { desc: "test with contact and offset", @@ -258,12 +258,12 @@ func TestListSubscriptions(t *testing.T) { }, err: nil, identifyErr: nil, - identityRes: &magistrala.IdentityRes{Id: validID}, + userID: validID, }, } for _, tc := range cases { - repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: tc.token}).Return(tc.identityRes, tc.identifyErr) + repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: tc.userID}, tc.identifyErr) repoCall1 := repo.On("RetrieveAll", context.Background(), tc.pageMeta).Return(tc.page, tc.err) page, err := svc.ListSubscriptions(context.Background(), tc.token, tc.pageMeta) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) @@ -288,7 +288,7 @@ func TestRemoveSubscription(t *testing.T) { id string err error identifyErr error - identityRes *magistrala.IdentityRes + userID string }{ { desc: "test success", @@ -296,7 +296,7 @@ func TestRemoveSubscription(t *testing.T) { id: sub.ID, err: nil, identifyErr: nil, - identityRes: &magistrala.IdentityRes{Id: validID}, + userID: validID, }, { desc: "test not existing", @@ -304,7 +304,7 @@ func TestRemoveSubscription(t *testing.T) { id: "not_exist", err: svcerr.ErrNotFound, identifyErr: nil, - identityRes: &magistrala.IdentityRes{Id: validID}, + userID: validID, }, { desc: "test with empty token", @@ -316,7 +316,7 @@ func TestRemoveSubscription(t *testing.T) { } for _, tc := range cases { - repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: tc.token}).Return(tc.identityRes, tc.identifyErr) + repoCall := auth.On("Identify", context.Background(), &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: tc.userID}, tc.identifyErr) repoCall1 := repo.On("Remove", context.Background(), tc.id).Return(tc.err) err := svc.RemoveSubscription(context.Background(), tc.token, tc.id) assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) diff --git a/pkg/sdk/go/consumers_test.go b/pkg/sdk/go/consumers_test.go index 87faecd2ba..dbb9f2b503 100644 --- a/pkg/sdk/go/consumers_test.go +++ b/pkg/sdk/go/consumers_test.go @@ -69,7 +69,7 @@ func TestCreateSubscription(t *testing.T) { empty bool id string identifyErr error - identityRes *magistrala.IdentityRes + userID string }{ { desc: "create new subscription", @@ -79,7 +79,7 @@ func TestCreateSubscription(t *testing.T) { empty: false, id: ID, identifyErr: nil, - identityRes: &magistrala.IdentityRes{Id: validID}, + userID: validID, }, { desc: "create new subscription with empty token", @@ -89,7 +89,6 @@ func TestCreateSubscription(t *testing.T) { empty: true, id: "", identifyErr: svcerr.ErrAuthorization, - identityRes: nil, }, { desc: "create new subscription with invalid token", @@ -99,7 +98,6 @@ func TestCreateSubscription(t *testing.T) { empty: true, id: "", identifyErr: svcerr.ErrAuthorization, - identityRes: nil, }, { desc: "create new empty subscription", @@ -109,12 +107,12 @@ func TestCreateSubscription(t *testing.T) { empty: true, id: "", identifyErr: nil, - identityRes: &magistrala.IdentityRes{Id: validID}, + userID: validID, }, } for _, tc := range cases { - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(tc.identityRes, tc.identifyErr) + repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: tc.userID}, tc.identifyErr) repoCall1 := repo.On("Save", mock.Anything, mock.Anything).Return(tc.id, tc.err) loc, err := mgsdk.CreateSubscription(tc.subscription.Topic, tc.subscription.Contact, tc.token) assert.Equal(t, tc.err, err, fmt.Sprintf("%s: expected error %s, got %s", tc.desc, tc.err, err)) @@ -142,7 +140,7 @@ func TestViewSubscription(t *testing.T) { err errors.SDKError response sdk.Subscription identifyErr error - identityRes *magistrala.IdentityRes + userID string }{ { desc: "get existing subscription", @@ -151,7 +149,7 @@ func TestViewSubscription(t *testing.T) { err: nil, response: sub1, identifyErr: nil, - identityRes: &magistrala.IdentityRes{Id: validID}, + userID: validID, }, { desc: "get non-existent subscription", @@ -160,7 +158,7 @@ func TestViewSubscription(t *testing.T) { err: errors.NewSDKErrorWithStatus(svcerr.ErrNotFound, http.StatusNotFound), response: sdk.Subscription{}, identifyErr: nil, - identityRes: &magistrala.IdentityRes{Id: validID}, + userID: validID, }, { desc: "get subscription with invalid token", @@ -173,7 +171,7 @@ func TestViewSubscription(t *testing.T) { } for _, tc := range cases { - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(tc.identityRes, tc.identifyErr) + repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: tc.userID}, tc.identifyErr) repoCall1 := repo.On("Retrieve", mock.Anything, mock.Anything).Return(notifiers.Subscription{Contact: sub1.Contact, Topic: sub1.Topic}, tc.err) respSub, err := mgsdk.ViewSubscription(tc.subID, tc.token) assert.Equal(t, tc.err, err, fmt.Sprintf("%s: expected error %s, got %s", tc.desc, tc.err, err)) @@ -206,7 +204,7 @@ func TestListSubscription(t *testing.T) { response []sdk.Subscription Page notifiers.Page identifyErr error - identityRes *magistrala.IdentityRes + userID string }{ { desc: "list all subscription", @@ -222,7 +220,7 @@ func TestListSubscription(t *testing.T) { Subscriptions: subSlice(subs, 0, 10), }, identifyErr: nil, - identityRes: &magistrala.IdentityRes{Id: validID}, + userID: validID, }, { desc: "list subscription with specific topic", @@ -239,7 +237,7 @@ func TestListSubscription(t *testing.T) { Subscriptions: subSlice(subs, 0, 1), }, identifyErr: nil, - identityRes: &magistrala.IdentityRes{Id: validID}, + userID: validID, }, { desc: "list subscription with specific contact", @@ -256,12 +254,12 @@ func TestListSubscription(t *testing.T) { Subscriptions: subSlice(subs, 0, 1), }, identifyErr: nil, - identityRes: &magistrala.IdentityRes{Id: validID}, + userID: validID, }, } for _, tc := range cases { - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(tc.identityRes, tc.identifyErr) + repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: tc.userID}, tc.identifyErr) repoCall1 := repo.On("RetrieveAll", mock.Anything, mock.Anything).Return(tc.Page, tc.err) subs, err := mgsdk.ListSubscriptions(tc.page, tc.token) assert.Equal(t, tc.err, err, fmt.Sprintf("%s: expected error %s, got %s", tc.desc, tc.err, err)) @@ -289,7 +287,7 @@ func TestDeleteSubscription(t *testing.T) { err errors.SDKError response sdk.Subscription identifyErr error - identityRes *magistrala.IdentityRes + userID string }{ { desc: "delete existing subscription", @@ -298,7 +296,7 @@ func TestDeleteSubscription(t *testing.T) { err: nil, response: sub1, identifyErr: nil, - identityRes: &magistrala.IdentityRes{Id: validID}, + userID: validID, }, { desc: "delete non-existent subscription", @@ -307,7 +305,7 @@ func TestDeleteSubscription(t *testing.T) { err: errors.NewSDKErrorWithStatus(svcerr.ErrNotFound, http.StatusNotFound), response: sdk.Subscription{}, identifyErr: nil, - identityRes: &magistrala.IdentityRes{Id: validID}, + userID: validID, }, { desc: "delete subscription with invalid token", @@ -320,7 +318,7 @@ func TestDeleteSubscription(t *testing.T) { } for _, tc := range cases { - repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(tc.identityRes, tc.err) + repoCall := auth.On("Identify", mock.Anything, &magistrala.IdentityReq{Token: tc.token}).Return(&magistrala.IdentityRes{Id: tc.userID}, tc.err) repoCall1 := repo.On("Remove", mock.Anything, mock.Anything).Return(tc.err) err := mgsdk.DeleteSubscription(tc.subID, tc.token) assert.Equal(t, tc.err, err, fmt.Sprintf("%s: expected error %s, got %s", tc.desc, tc.err, err))