6fe4d7a70a0bf89e09dd19b101838a2ef6cd2ca2
[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/jobshandler"
38 )
39
40 func TestNewRouter(t *testing.T) {
41         assertions := require.New(t)
42
43         r := NewRouter(nil, nil)
44         statusRoute := r.Get("health_check")
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("/health_check", 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("/info_job", 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("/info_job/{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 TestAddInfoJobToJobsHandler(t *testing.T) {
92         assertions := require.New(t)
93
94         type args struct {
95                 job        jobs.JobInfo
96                 mockReturn error
97         }
98         tests := []struct {
99                 name         string
100                 args         args
101                 wantedStatus int
102                 wantedBody   string
103         }{
104                 {
105                         name: "AddInfoJobToJobsHandler with correct job, should return OK",
106                         args: args{
107                                 job: jobs.JobInfo{
108                                         Owner:            "owner",
109                                         LastUpdated:      "now",
110                                         InfoJobIdentity:  "jobId",
111                                         TargetUri:        "target",
112                                         InfoJobData:      jobs.Parameters{},
113                                         InfoTypeIdentity: "type",
114                                 },
115                         },
116                         wantedStatus: http.StatusOK,
117                 },
118                 {
119                         name: "AddInfoJobToJobsHandler with incorrect job info, should return BadRequest",
120                         args: args{
121                                 job: jobs.JobInfo{
122                                         Owner: "bad",
123                                 },
124                                 mockReturn: errors.New("error"),
125                         },
126                         wantedStatus: http.StatusBadRequest,
127                         wantedBody:   "Invalid job info. Cause: error",
128                 },
129         }
130         for _, tt := range tests {
131                 t.Run(tt.name, func(t *testing.T) {
132                         jobsHandlerMock := jobshandler.JobsHandler{}
133                         jobsHandlerMock.On("AddJobFromRESTCall", tt.args.job).Return(tt.args.mockReturn)
134
135                         callbackHandlerUnderTest := NewProducerCallbackHandler(&jobsHandlerMock)
136
137                         handler := http.HandlerFunc(callbackHandlerUnderTest.addInfoJobHandler)
138                         responseRecorder := httptest.NewRecorder()
139                         r := newRequest(http.MethodPost, "/jobs", &tt.args.job, t)
140
141                         handler.ServeHTTP(responseRecorder, r)
142
143                         assertions.Equal(tt.wantedStatus, responseRecorder.Code, tt.name)
144                         assertions.Contains(responseRecorder.Body.String(), tt.wantedBody, tt.name)
145                         jobsHandlerMock.AssertCalled(t, "AddJobFromRESTCall", tt.args.job)
146                 })
147         }
148 }
149
150 func TestDeleteJob(t *testing.T) {
151         assertions := require.New(t)
152         jobsHandlerMock := jobshandler.JobsHandler{}
153         jobsHandlerMock.On("DeleteJobFromRESTCall", mock.Anything).Return(nil)
154
155         callbackHandlerUnderTest := NewProducerCallbackHandler(&jobsHandlerMock)
156
157         responseRecorder := httptest.NewRecorder()
158         r := mux.SetURLVars(newRequest(http.MethodDelete, "/jobs/", nil, t), map[string]string{"infoJobId": "job1"})
159         handler := http.HandlerFunc(callbackHandlerUnderTest.deleteInfoJobHandler)
160         handler.ServeHTTP(responseRecorder, r)
161         assertions.Equal(http.StatusOK, responseRecorder.Result().StatusCode)
162
163         assertions.Equal("", responseRecorder.Body.String())
164
165         jobsHandlerMock.AssertCalled(t, "DeleteJobFromRESTCall", "job1")
166 }
167
168 func TestSetLogLevel(t *testing.T) {
169         assertions := require.New(t)
170
171         type args struct {
172                 logLevel string
173         }
174         tests := []struct {
175                 name         string
176                 args         args
177                 wantedStatus int
178                 wantedBody   string
179         }{
180                 {
181                         name: "Set to valid log level, should return OK",
182                         args: args{
183                                 logLevel: "Debug",
184                         },
185                         wantedStatus: http.StatusOK,
186                 },
187                 {
188                         name: "Set to invalid log level, should return BadRequest",
189                         args: args{
190                                 logLevel: "bad",
191                         },
192                         wantedStatus: http.StatusBadRequest,
193                         wantedBody:   "Invalid log level: bad",
194                 },
195         }
196         for _, tt := range tests {
197                 t.Run(tt.name, func(t *testing.T) {
198                         callbackHandlerUnderTest := NewProducerCallbackHandler(nil)
199
200                         handler := http.HandlerFunc(callbackHandlerUnderTest.setLogLevel)
201                         responseRecorder := httptest.NewRecorder()
202                         r, _ := http.NewRequest(http.MethodPut, "/admin/log?level="+tt.args.logLevel, nil)
203
204                         handler.ServeHTTP(responseRecorder, r)
205
206                         assertions.Equal(tt.wantedStatus, responseRecorder.Code, tt.name)
207                         assertions.Contains(responseRecorder.Body.String(), tt.wantedBody, tt.name)
208                 })
209         }
210 }
211
212 func newRequest(method string, url string, jobInfo *jobs.JobInfo, t *testing.T) *http.Request {
213         var body io.Reader
214         if jobInfo != nil {
215                 bodyAsBytes, _ := json.Marshal(jobInfo)
216                 body = ioutil.NopCloser(bytes.NewReader(bodyAsBytes))
217         }
218         if req, err := http.NewRequest(method, url, body); err == nil {
219                 return req
220         } else {
221                 t.Fatalf("Could not create request due to: %v", err)
222                 return nil
223         }
224 }