1db36446134b623b245838f0dc423850831c0269
[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
43         r := NewRouter(nil)
44         statusRoute := r.Get("status")
45         assertions.NotNil(statusRoute)
46         supportedMethods, err := statusRoute.GetMethods()
47         assertions.Equal([]string{http.MethodGet}, supportedMethods)
48         assertions.Nil(err)
49         path, _ := statusRoute.GetPathTemplate()
50         assertions.Equal("/status", path)
51
52         addJobRoute := r.Get("add")
53         assertions.NotNil(addJobRoute)
54         supportedMethods, err = addJobRoute.GetMethods()
55         assertions.Equal([]string{http.MethodPost}, supportedMethods)
56         assertions.Nil(err)
57         path, _ = addJobRoute.GetPathTemplate()
58         assertions.Equal("/jobs", path)
59
60         deleteJobRoute := r.Get("delete")
61         assertions.NotNil(deleteJobRoute)
62         supportedMethods, err = deleteJobRoute.GetMethods()
63         assertions.Equal([]string{http.MethodDelete}, supportedMethods)
64         assertions.Nil(err)
65         path, _ = deleteJobRoute.GetPathTemplate()
66         assertions.Equal("/jobs/{infoJobId}", path)
67
68         notFoundHandler := r.NotFoundHandler
69         handler := http.HandlerFunc(notFoundHandler.ServeHTTP)
70         responseRecorder := httptest.NewRecorder()
71         handler.ServeHTTP(responseRecorder, newRequest("GET", "/wrong", nil, t))
72         assertions.Equal(http.StatusNotFound, responseRecorder.Code)
73         assertions.Contains(responseRecorder.Body.String(), "404 not found.")
74
75         methodNotAllowedHandler := r.MethodNotAllowedHandler
76         handler = http.HandlerFunc(methodNotAllowedHandler.ServeHTTP)
77         responseRecorder = httptest.NewRecorder()
78         handler.ServeHTTP(responseRecorder, newRequest(http.MethodPut, "/status", nil, t))
79         assertions.Equal(http.StatusMethodNotAllowed, responseRecorder.Code)
80         assertions.Contains(responseRecorder.Body.String(), "Method is not supported.")
81
82         setLogLevelRoute := r.Get("setLogLevel")
83         assertions.NotNil(setLogLevelRoute)
84         supportedMethods, err = setLogLevelRoute.GetMethods()
85         assertions.Equal([]string{http.MethodPut}, supportedMethods)
86         assertions.Nil(err)
87         path, _ = setLogLevelRoute.GetPathTemplate()
88         assertions.Equal("/admin/log", path)
89 }
90
91 func TestStatusHandler(t *testing.T) {
92         assertions := require.New(t)
93
94         handler := http.HandlerFunc(statusHandler)
95         responseRecorder := httptest.NewRecorder()
96         r := newRequest(http.MethodGet, "/status", nil, t)
97
98         handler.ServeHTTP(responseRecorder, r)
99
100         assertions.Equal(http.StatusOK, responseRecorder.Code)
101         assertions.Equal("", responseRecorder.Body.String())
102 }
103
104 func TestAddInfoJobHandler(t *testing.T) {
105         assertions := require.New(t)
106
107         type args struct {
108                 job        jobs.JobInfo
109                 mockReturn error
110         }
111         tests := []struct {
112                 name         string
113                 args         args
114                 wantedStatus int
115                 wantedBody   string
116         }{
117                 {
118                         name: "AddInfoJobHandler with correct job, should return OK",
119                         args: args{
120                                 job: jobs.JobInfo{
121                                         Owner:            "owner",
122                                         LastUpdated:      "now",
123                                         InfoJobIdentity:  "jobId",
124                                         TargetUri:        "target",
125                                         InfoJobData:      "{}",
126                                         InfoTypeIdentity: "type",
127                                 },
128                         },
129                         wantedStatus: http.StatusOK,
130                 },
131                 {
132                         name: "AddInfoJobHandler with incorrect job info, should return BadRequest",
133                         args: args{
134                                 job: jobs.JobInfo{
135                                         Owner: "bad",
136                                 },
137                                 mockReturn: errors.New("error"),
138                         },
139                         wantedStatus: http.StatusBadRequest,
140                         wantedBody:   "Invalid job info. Cause: error",
141                 },
142         }
143         for _, tt := range tests {
144                 t.Run(tt.name, func(t *testing.T) {
145                         jobHandlerMock := jobhandler.JobHandler{}
146                         jobHandlerMock.On("AddJobFromRESTCall", tt.args.job).Return(tt.args.mockReturn)
147
148                         callbackHandlerUnderTest := NewProducerCallbackHandler(&jobHandlerMock)
149
150                         handler := http.HandlerFunc(callbackHandlerUnderTest.addInfoJobHandler)
151                         responseRecorder := httptest.NewRecorder()
152                         r := newRequest(http.MethodPost, "/jobs", &tt.args.job, t)
153
154                         handler.ServeHTTP(responseRecorder, r)
155
156                         assertions.Equal(tt.wantedStatus, responseRecorder.Code, tt.name)
157                         assertions.Contains(responseRecorder.Body.String(), tt.wantedBody, tt.name)
158                         jobHandlerMock.AssertCalled(t, "AddJobFromRESTCall", tt.args.job)
159                 })
160         }
161 }
162
163 func TestDeleteJob(t *testing.T) {
164         assertions := require.New(t)
165         jobHandlerMock := jobhandler.JobHandler{}
166         jobHandlerMock.On("DeleteJobFromRESTCall", mock.Anything).Return(nil)
167
168         callbackHandlerUnderTest := NewProducerCallbackHandler(&jobHandlerMock)
169
170         responseRecorder := httptest.NewRecorder()
171         r := mux.SetURLVars(newRequest(http.MethodDelete, "/jobs/", nil, t), map[string]string{"infoJobId": "job1"})
172         handler := http.HandlerFunc(callbackHandlerUnderTest.deleteInfoJobHandler)
173         handler.ServeHTTP(responseRecorder, r)
174         assertions.Equal(http.StatusOK, responseRecorder.Result().StatusCode)
175
176         assertions.Equal("", responseRecorder.Body.String())
177
178         jobHandlerMock.AssertCalled(t, "DeleteJobFromRESTCall", "job1")
179 }
180
181 func TestSetLogLevel(t *testing.T) {
182         assertions := require.New(t)
183
184         type args struct {
185                 logLevel string
186         }
187         tests := []struct {
188                 name         string
189                 args         args
190                 wantedStatus int
191                 wantedBody   string
192         }{
193                 {
194                         name: "Set to valid log level, should return OK",
195                         args: args{
196                                 logLevel: "Debug",
197                         },
198                         wantedStatus: http.StatusOK,
199                 },
200                 {
201                         name: "Set to invalid log level, should return BadRequest",
202                         args: args{
203                                 logLevel: "bad",
204                         },
205                         wantedStatus: http.StatusBadRequest,
206                         wantedBody:   "Invalid log level: bad",
207                 },
208         }
209         for _, tt := range tests {
210                 t.Run(tt.name, func(t *testing.T) {
211                         callbackHandlerUnderTest := NewProducerCallbackHandler(nil)
212
213                         handler := http.HandlerFunc(callbackHandlerUnderTest.setLogLevel)
214                         responseRecorder := httptest.NewRecorder()
215                         r, _ := http.NewRequest(http.MethodPut, "/admin/log?level="+tt.args.logLevel, nil)
216
217                         handler.ServeHTTP(responseRecorder, r)
218
219                         assertions.Equal(tt.wantedStatus, responseRecorder.Code, tt.name)
220                         assertions.Contains(responseRecorder.Body.String(), tt.wantedBody, tt.name)
221                 })
222         }
223 }
224
225 func newRequest(method string, url string, jobInfo *jobs.JobInfo, t *testing.T) *http.Request {
226         var body io.Reader
227         if jobInfo != nil {
228                 bodyAsBytes, _ := json.Marshal(jobInfo)
229                 body = ioutil.NopCloser(bytes.NewReader(bodyAsBytes))
230         }
231         if req, err := http.NewRequest(method, url, body); err == nil {
232                 return req
233         } else {
234                 t.Fatalf("Could not create request due to: %v", err)
235                 return nil
236         }
237 }