Add test for consumer restclient
[nonrtric.git] / dmaap-mediator-producer / internal / server / server_test.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2021: Nordix Foundation
6 //   %%
7 //   Licensed under the Apache License, Version 2.0 (the "License");
8 //   you may not use this file except in compliance with the License.
9 //   You may obtain a copy of the License at
10 //
11 //        http://www.apache.org/licenses/LICENSE-2.0
12 //
13 //   Unless required by applicable law or agreed to in writing, software
14 //   distributed under the License is distributed on an "AS IS" BASIS,
15 //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 //   See the License for the specific language governing permissions and
17 //   limitations under the License.
18 //   ========================LICENSE_END===================================
19 //
20
21 package server
22
23 import (
24         "bytes"
25         "encoding/json"
26         "errors"
27         "io"
28         "io/ioutil"
29         "net/http"
30         "net/http/httptest"
31         "testing"
32
33         "github.com/gorilla/mux"
34         "github.com/stretchr/testify/mock"
35         "github.com/stretchr/testify/require"
36         "oransc.org/nonrtric/dmaapmediatorproducer/internal/jobs"
37         "oransc.org/nonrtric/dmaapmediatorproducer/mocks/jobhandler"
38 )
39
40 func TestNewRouter(t *testing.T) {
41         assertions := require.New(t)
42         r := NewRouter()
43         statusRoute := r.Get("status")
44         assertions.NotNil(statusRoute)
45         supportedMethods, err := statusRoute.GetMethods()
46         assertions.Equal([]string{http.MethodGet}, supportedMethods)
47         assertions.Nil(err)
48
49         addJobRoute := r.Get("add")
50         assertions.NotNil(addJobRoute)
51         supportedMethods, err = addJobRoute.GetMethods()
52         assertions.Equal([]string{http.MethodPost}, supportedMethods)
53         assertions.Nil(err)
54
55         deleteJobRoute := r.Get("delete")
56         assertions.NotNil(deleteJobRoute)
57         supportedMethods, err = deleteJobRoute.GetMethods()
58         assertions.Equal([]string{http.MethodDelete}, supportedMethods)
59         assertions.Nil(err)
60
61         notFoundHandler := r.NotFoundHandler
62         handler := http.HandlerFunc(notFoundHandler.ServeHTTP)
63         responseRecorder := httptest.NewRecorder()
64         handler.ServeHTTP(responseRecorder, newRequest("GET", "/wrong", nil, t))
65         assertions.Equal(http.StatusNotFound, responseRecorder.Code)
66
67         assertions.Contains(responseRecorder.Body.String(), "404 not found.")
68
69         methodNotAllowedHandler := r.MethodNotAllowedHandler
70         handler = http.HandlerFunc(methodNotAllowedHandler.ServeHTTP)
71         responseRecorder = httptest.NewRecorder()
72         handler.ServeHTTP(responseRecorder, newRequest(http.MethodPut, "/status", nil, t))
73         assertions.Equal(http.StatusMethodNotAllowed, responseRecorder.Code)
74
75         assertions.Contains(responseRecorder.Body.String(), "Method is not supported.")
76 }
77
78 func TestStatusHandler(t *testing.T) {
79         assertions := require.New(t)
80         responseRecorder := httptest.NewRecorder()
81         r := newRequest(http.MethodGet, "/status", nil, t)
82         handler := http.HandlerFunc(statusHandler)
83         handler.ServeHTTP(responseRecorder, r)
84         assertions.Equal(http.StatusOK, responseRecorder.Code)
85
86         assertions.Equal("", responseRecorder.Body.String())
87 }
88
89 func TestAddInfoJobHandler(t *testing.T) {
90         assertions := require.New(t)
91         jobHandlerMock := jobhandler.JobHandler{}
92
93         goodJobInfo := jobs.JobInfo{
94                 Owner:            "owner",
95                 LastUpdated:      "now",
96                 InfoJobIdentity:  "jobId",
97                 TargetUri:        "target",
98                 InfoJobData:      "{}",
99                 InfoTypeIdentity: "type",
100         }
101         badJobInfo := jobs.JobInfo{
102                 Owner: "bad",
103         }
104         jobHandlerMock.On("AddJob", goodJobInfo).Return(nil)
105         jobHandlerMock.On("AddJob", badJobInfo).Return(errors.New("error"))
106         jobs.Handler = &jobHandlerMock
107
108         type args struct {
109                 responseRecorder *httptest.ResponseRecorder
110                 r                *http.Request
111         }
112         tests := []struct {
113                 name         string
114                 args         args
115                 wantedStatus int
116                 wantedBody   string
117                 assertFunc   assertMockFunk
118         }{
119                 {
120                         name: "AddInfoJobHandler with correct path and method, should return OK",
121                         args: args{
122                                 responseRecorder: httptest.NewRecorder(),
123                                 r:                newRequest(http.MethodPost, "/jobs", &goodJobInfo, t),
124                         },
125                         wantedStatus: http.StatusOK,
126                         wantedBody:   "",
127                         assertFunc: func(mock *jobhandler.JobHandler) {
128                                 mock.AssertCalled(t, "AddJob", goodJobInfo)
129                         },
130                 },
131                 {
132                         name: "AddInfoJobHandler with incorrect job info, should return BadRequest",
133                         args: args{
134                                 responseRecorder: httptest.NewRecorder(),
135                                 r:                newRequest(http.MethodPost, "/jobs", &badJobInfo, t),
136                         },
137                         wantedStatus: http.StatusBadRequest,
138                         wantedBody:   "Invalid job info. Cause: error",
139                 },
140         }
141         for _, tt := range tests {
142                 t.Run(tt.name, func(t *testing.T) {
143                         handler := http.HandlerFunc(addInfoJobHandler)
144                         handler.ServeHTTP(tt.args.responseRecorder, tt.args.r)
145                         assertions.Equal(tt.wantedStatus, tt.args.responseRecorder.Code, tt.name)
146
147                         assertions.Contains(tt.args.responseRecorder.Body.String(), tt.wantedBody, tt.name)
148
149                         if tt.assertFunc != nil {
150                                 tt.assertFunc(&jobHandlerMock)
151                         }
152                 })
153         }
154 }
155
156 func TestDeleteJob(t *testing.T) {
157         assertions := require.New(t)
158         jobHandlerMock := jobhandler.JobHandler{}
159
160         jobHandlerMock.On("DeleteJob", mock.Anything).Return(nil)
161         jobs.Handler = &jobHandlerMock
162
163         responseRecorder := httptest.NewRecorder()
164         r := mux.SetURLVars(newRequest(http.MethodDelete, "/jobs/", nil, t), map[string]string{"infoJobId": "job1"})
165         handler := http.HandlerFunc(deleteInfoJobHandler)
166         handler.ServeHTTP(responseRecorder, r)
167         assertions.Equal(http.StatusOK, responseRecorder.Result().StatusCode)
168
169         assertions.Equal("", responseRecorder.Body.String())
170
171         jobHandlerMock.AssertCalled(t, "DeleteJob", "job1")
172 }
173
174 type assertMockFunk func(mock *jobhandler.JobHandler)
175
176 func newRequest(method string, url string, jobInfo *jobs.JobInfo, t *testing.T) *http.Request {
177         var body io.Reader
178         if jobInfo != nil {
179                 bodyAsBytes, _ := json.Marshal(jobInfo)
180                 body = ioutil.NopCloser(bytes.NewReader(bodyAsBytes))
181         }
182         if req, err := http.NewRequest(method, url, body); err == nil {
183                 return req
184         } else {
185                 t.Fatalf("Could not create request due to: %v", err)
186                 return nil
187         }
188 }