2 // ========================LICENSE_START=================================
5 // Copyright (C) 2021: Nordix Foundation
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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===================================
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"
40 func TestNewRouter(t *testing.T) {
41 assertions := require.New(t)
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)
49 path, _ := statusRoute.GetPathTemplate()
50 assertions.Equal("/health_check", path)
52 addJobRoute := r.Get("add")
53 assertions.NotNil(addJobRoute)
54 supportedMethods, err = addJobRoute.GetMethods()
55 assertions.Equal([]string{http.MethodPost}, supportedMethods)
57 path, _ = addJobRoute.GetPathTemplate()
58 assertions.Equal("/info_job", path)
60 deleteJobRoute := r.Get("delete")
61 assertions.NotNil(deleteJobRoute)
62 supportedMethods, err = deleteJobRoute.GetMethods()
63 assertions.Equal([]string{http.MethodDelete}, supportedMethods)
65 path, _ = deleteJobRoute.GetPathTemplate()
66 assertions.Equal("/info_job/{infoJobId}", path)
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.")
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.")
82 setLogLevelRoute := r.Get("setLogLevel")
83 assertions.NotNil(setLogLevelRoute)
84 supportedMethods, err = setLogLevelRoute.GetMethods()
85 assertions.Equal([]string{http.MethodPut}, supportedMethods)
87 path, _ = setLogLevelRoute.GetPathTemplate()
88 assertions.Equal("/admin/log", path)
91 func TestAddInfoJobToJobsHandler(t *testing.T) {
92 assertions := require.New(t)
102 wantedErrorInfo *ErrorInfo
105 name: "AddInfoJobToJobsHandler with correct job, should return OK",
110 InfoJobIdentity: "jobId",
112 InfoJobData: jobs.Parameters{},
113 InfoTypeIdentity: "type",
116 wantedStatus: http.StatusOK,
119 name: "AddInfoJobToJobsHandler with incorrect job info, should return BadRequest",
124 mockReturn: errors.New("error"),
126 wantedStatus: http.StatusBadRequest,
127 wantedErrorInfo: &ErrorInfo{
128 Status: http.StatusBadRequest,
129 Detail: "Invalid job info. Cause: error",
133 for _, tt := range tests {
134 t.Run(tt.name, func(t *testing.T) {
135 jobsHandlerMock := jobshandler.JobsHandler{}
136 jobsHandlerMock.On("AddJobFromRESTCall", tt.args.job).Return(tt.args.mockReturn)
138 callbackHandlerUnderTest := NewProducerCallbackHandler(&jobsHandlerMock)
140 handler := http.HandlerFunc(callbackHandlerUnderTest.addInfoJobHandler)
141 responseRecorder := httptest.NewRecorder()
142 r := newRequest(http.MethodPost, "/jobs", &tt.args.job, t)
144 handler.ServeHTTP(responseRecorder, r)
146 assertions.Equal(tt.wantedStatus, responseRecorder.Code, tt.name)
147 if tt.wantedErrorInfo != nil {
148 var actualErrInfo ErrorInfo
149 err := json.Unmarshal(getBody(responseRecorder, t), &actualErrInfo)
151 t.Error("Unable to unmarshal error body", err)
154 assertions.Equal(*tt.wantedErrorInfo, actualErrInfo, tt.name)
155 assertions.Equal("application/problem+json", responseRecorder.Result().Header.Get("Content-Type"))
157 jobsHandlerMock.AssertCalled(t, "AddJobFromRESTCall", tt.args.job)
162 func TestDeleteJob(t *testing.T) {
163 assertions := require.New(t)
164 jobsHandlerMock := jobshandler.JobsHandler{}
165 jobsHandlerMock.On("DeleteJobFromRESTCall", mock.Anything).Return(nil)
167 callbackHandlerUnderTest := NewProducerCallbackHandler(&jobsHandlerMock)
169 responseRecorder := httptest.NewRecorder()
170 r := mux.SetURLVars(newRequest(http.MethodDelete, "/jobs/", nil, t), map[string]string{"infoJobId": "job1"})
171 handler := http.HandlerFunc(callbackHandlerUnderTest.deleteInfoJobHandler)
172 handler.ServeHTTP(responseRecorder, r)
173 assertions.Equal(http.StatusOK, responseRecorder.Result().StatusCode)
175 assertions.Equal("", responseRecorder.Body.String())
177 jobsHandlerMock.AssertCalled(t, "DeleteJobFromRESTCall", "job1")
180 func TestSetLogLevel(t *testing.T) {
181 assertions := require.New(t)
190 wantedErrorInfo *ErrorInfo
193 name: "Set to valid log level, should return OK",
197 wantedStatus: http.StatusOK,
200 name: "Set to invalid log level, should return BadRequest",
204 wantedStatus: http.StatusBadRequest,
205 wantedErrorInfo: &ErrorInfo{
206 Detail: "Invalid log level: bad. Log level will not be changed!",
207 Status: http.StatusBadRequest,
211 for _, tt := range tests {
212 t.Run(tt.name, func(t *testing.T) {
213 callbackHandlerUnderTest := NewProducerCallbackHandler(nil)
215 handler := http.HandlerFunc(callbackHandlerUnderTest.setLogLevel)
216 responseRecorder := httptest.NewRecorder()
217 r, _ := http.NewRequest(http.MethodPut, "/admin/log?level="+tt.args.logLevel, nil)
219 handler.ServeHTTP(responseRecorder, r)
221 assertions.Equal(tt.wantedStatus, responseRecorder.Code, tt.name)
222 if tt.wantedErrorInfo != nil {
223 var actualErrInfo ErrorInfo
224 err := json.Unmarshal(getBody(responseRecorder, t), &actualErrInfo)
226 t.Error("Unable to unmarshal error body", err)
229 assertions.Equal(*tt.wantedErrorInfo, actualErrInfo, tt.name)
230 assertions.Equal("application/problem+json", responseRecorder.Result().Header.Get("Content-Type"))
236 func newRequest(method string, url string, jobInfo *jobs.JobInfo, t *testing.T) *http.Request {
239 bodyAsBytes, _ := json.Marshal(jobInfo)
240 body = ioutil.NopCloser(bytes.NewReader(bodyAsBytes))
242 if req, err := http.NewRequest(method, url, body); err == nil {
245 t.Fatalf("Could not create request due to: %v", err)
250 func getBody(responseRecorder *httptest.ResponseRecorder, t *testing.T) []byte {
251 buf := new(bytes.Buffer)
252 if _, err := buf.ReadFrom(responseRecorder.Body); err != nil {
253 t.Error("Unable to read error body", err)