b5c4b057cc44dfdba351dae6b075eb7db61d3894
[ric-plt/e2mgr.git] / E2Manager / controllers / controller_test.go
1 //
2 // Copyright 2019 AT&T Intellectual Property
3 // Copyright 2019 Nokia
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //      http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17
18 package controllers
19
20 import (
21         "bytes"
22         "e2mgr/configuration"
23         "e2mgr/e2managererrors"
24         "e2mgr/logger"
25         "e2mgr/mocks"
26         "e2mgr/models"
27         "e2mgr/providers/httpmsghandlerprovider"
28         "e2mgr/rNibWriter"
29         "e2mgr/rmrCgo"
30         "e2mgr/tests"
31         "encoding/json"
32         "fmt"
33         "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/common"
34         "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/entities"
35         "gerrit.o-ran-sc.org/r/ric-plt/nodeb-rnib.git/reader"
36         "github.com/gorilla/mux"
37         "github.com/stretchr/testify/assert"
38         "github.com/stretchr/testify/mock"
39         "io"
40         "io/ioutil"
41         "net/http"
42         "net/http/httptest"
43         "strings"
44         "testing"
45 )
46
47 func TestShutdownHandlerRnibError(t *testing.T) {
48         log := initLog(t)
49         config := configuration.ParseConfiguration()
50
51         rmrMessengerMock := &mocks.RmrMessengerMock{}
52         readerMock := &mocks.RnibReaderMock{}
53         readerProvider := func() reader.RNibReader {
54                 return readerMock
55         }
56         writerMock := &mocks.RnibWriterMock{}
57         writerProvider := func() rNibWriter.RNibWriter {
58                 return writerMock
59         }
60
61         rnibErr := &common.RNibError{}
62         var nbIdentityList []*entities.NbIdentity
63         readerMock.On("GetListNodebIds").Return(nbIdentityList, rnibErr)
64
65         writer := httptest.NewRecorder()
66         controller := NewController(log, getRmrService(rmrMessengerMock, log), readerProvider, writerProvider, config)
67         controller.ShutdownHandler(writer, tests.GetHttpRequest())
68
69         var errorResponse = parseJsonRequest(t, writer.Body)
70
71         assert.Equal(t, http.StatusInternalServerError, writer.Result().StatusCode)
72         assert.Equal(t, errorResponse.Code, e2managererrors.NewRnibDbError().Err.Code)
73 }
74
75 func TestHeaderValidationFailed(t *testing.T) {
76         log := initLog(t)
77         config := configuration.ParseConfiguration()
78
79         rmrMessengerMock := &mocks.RmrMessengerMock{}
80         readerMock := &mocks.RnibReaderMock{}
81         readerProvider := func() reader.RNibReader {
82                 return readerMock
83         }
84         writerMock := &mocks.RnibWriterMock{}
85         writerProvider := func() rNibWriter.RNibWriter {
86                 return writerMock
87         }
88
89         writer := httptest.NewRecorder()
90
91         controller := NewController(log, getRmrService(rmrMessengerMock, log), readerProvider, writerProvider, config)
92
93         header := &http.Header{}
94
95         controller.handleRequest(writer, header, httpmsghandlerprovider.ShutdownRequest, nil, true, http.StatusNoContent)
96
97         var errorResponse = parseJsonRequest(t, writer.Body)
98         err := e2managererrors.NewHeaderValidationError()
99
100         assert.Equal(t, http.StatusUnsupportedMediaType, writer.Result().StatusCode)
101         assert.Equal(t, errorResponse.Code, err.Err.Code)
102         assert.Equal(t, errorResponse.Message, err.Err.Message)
103 }
104
105 func TestShutdownStatusNoContent(t *testing.T) {
106         log := initLog(t)
107
108         rmrMessengerMock := &mocks.RmrMessengerMock{}
109         readerMock := &mocks.RnibReaderMock{}
110         readerProvider := func() reader.RNibReader {
111                 return readerMock
112         }
113         writerMock := &mocks.RnibWriterMock{}
114         writerProvider := func() rNibWriter.RNibWriter {
115                 return writerMock
116         }
117         config := configuration.ParseConfiguration()
118
119         var rnibError common.IRNibError
120         nbIdentityList := []*entities.NbIdentity{}
121         readerMock.On("GetListNodebIds").Return(nbIdentityList, rnibError)
122
123         writer := httptest.NewRecorder()
124         controller := NewController(log, getRmrService(rmrMessengerMock, log), readerProvider, writerProvider, config)
125         controller.ShutdownHandler(writer, tests.GetHttpRequest())
126
127         assert.Equal(t, http.StatusNoContent, writer.Result().StatusCode)
128 }
129
130 func TestHandleInternalError(t *testing.T) {
131         log := initLog(t)
132         config := configuration.ParseConfiguration()
133
134         rmrMessengerMock := &mocks.RmrMessengerMock{}
135         readerMock := &mocks.RnibReaderMock{}
136         readerProvider := func() reader.RNibReader {
137                 return readerMock
138         }
139         writerMock := &mocks.RnibWriterMock{}
140         writerProvider := func() rNibWriter.RNibWriter {
141                 return writerMock
142         }
143
144         writer := httptest.NewRecorder()
145         controller := NewController(log, getRmrService(rmrMessengerMock, log), readerProvider, writerProvider, config)
146         err := e2managererrors.NewInternalError()
147
148         controller.handleErrorResponse(err, writer)
149         var errorResponse = parseJsonRequest(t, writer.Body)
150
151         assert.Equal(t, http.StatusInternalServerError, writer.Result().StatusCode)
152         assert.Equal(t, errorResponse.Code, err.Err.Code)
153         assert.Equal(t, errorResponse.Message, err.Err.Message)
154 }
155
156 func TestHandleCommandAlreadyInProgressError(t *testing.T) {
157         log := initLog(t)
158         config := configuration.ParseConfiguration()
159
160         rmrMessengerMock := &mocks.RmrMessengerMock{}
161         readerMock := &mocks.RnibReaderMock{}
162         readerProvider := func() reader.RNibReader {
163                 return readerMock
164         }
165         writerMock := &mocks.RnibWriterMock{}
166         writerProvider := func() rNibWriter.RNibWriter {
167                 return writerMock
168         }
169         writer := httptest.NewRecorder()
170         controller := NewController(log, getRmrService(rmrMessengerMock, log), readerProvider, writerProvider, config)
171         err := e2managererrors.NewCommandAlreadyInProgressError()
172
173         controller.handleErrorResponse(err, writer)
174         var errorResponse = parseJsonRequest(t, writer.Body)
175
176         assert.Equal(t, http.StatusMethodNotAllowed, writer.Result().StatusCode)
177         assert.Equal(t, errorResponse.Code, err.Err.Code)
178         assert.Equal(t, errorResponse.Message, err.Err.Message)
179 }
180
181 func TestValidateHeaders(t *testing.T) {
182         log := initLog(t)
183
184         rmrMessengerMock := &mocks.RmrMessengerMock{}
185         readerMock := &mocks.RnibReaderMock{}
186         readerProvider := func() reader.RNibReader {
187                 return readerMock
188         }
189         writerMock := &mocks.RnibWriterMock{}
190         writerProvider := func() rNibWriter.RNibWriter {
191                 return writerMock
192         }
193         config := configuration.ParseConfiguration()
194
195         controller := NewController(log, getRmrService(rmrMessengerMock, log), readerProvider, writerProvider, config)
196
197         header := http.Header{}
198         header.Set("Content-Type", "application/json")
199         result := controller.validateRequestHeader(&header)
200
201         assert.Nil(t, result)
202 }
203
204 func parseJsonRequest(t *testing.T, r io.Reader) models.ErrorResponse {
205
206         var errorResponse models.ErrorResponse
207         body, err := ioutil.ReadAll(r)
208         if err != nil {
209                 t.Errorf("Error cannot deserialize json request")
210         }
211         json.Unmarshal(body, &errorResponse)
212
213         return errorResponse
214 }
215
216 func initLog(t *testing.T) *logger.Logger {
217         log, err := logger.InitLogger(logger.InfoLevel)
218         if err != nil {
219                 t.Errorf("#delete_all_request_handler_test.TestHandleSuccessFlow - failed to initialize logger, error: %s", err)
220         }
221         return log
222 }
223
224 func TestX2ResetHandleSuccessfulRequestedCause(t *testing.T) {
225         log := initLog(t)
226
227         ranName := "test1"
228
229         readerMock := &mocks.RnibReaderMock{}
230         readerProvider := func() reader.RNibReader {
231                 return readerMock
232         }
233         writerMock := &mocks.RnibWriterMock{}
234         writerProvider := func() rNibWriter.RNibWriter {
235                 return writerMock
236         }
237         payload := []byte{0x00, 0x07, 0x00, 0x08, 0x00, 0x00, 0x01, 0x00, 0x05, 0x40, 0x01, 0x40}
238         xaction := []byte(ranName)
239         msg := rmrCgo.NewMBuf(rmrCgo.RIC_X2_RESET, len(payload), ranName, &payload, &xaction)
240         rmrMessengerMock := &mocks.RmrMessengerMock{}
241         rmrMessengerMock.On("SendMsg", msg, mock.Anything).Return(msg, nil)
242
243         config := configuration.ParseConfiguration()
244         rmrService := getRmrService(rmrMessengerMock, log)
245
246         writer := httptest.NewRecorder()
247         controller := NewController(log, rmrService, readerProvider, writerProvider, config)
248
249         var nodeb = &entities.NodebInfo{ConnectionStatus: entities.ConnectionStatus_CONNECTED}
250         readerMock.On("GetNodeb", ranName).Return(nodeb, nil)
251
252         data4Req := map[string]interface{}{"cause": "protocol:transfer-syntax-error"}
253         b := new(bytes.Buffer)
254         _ = json.NewEncoder(b).Encode(data4Req)
255         req, _ := http.NewRequest("PUT", "https://localhost:3800/nodeb-reset", b)
256         req = mux.SetURLVars(req, map[string]string{"ranName": ranName})
257
258         controller.X2ResetHandler(writer, req)
259         assert.Equal(t, http.StatusNoContent, writer.Result().StatusCode)
260
261 }
262
263 func TestX2ResetHandleSuccessfulRequestedDefault(t *testing.T) {
264         log := initLog(t)
265
266         ranName := "test1"
267
268         readerMock := &mocks.RnibReaderMock{}
269         readerProvider := func() reader.RNibReader {
270                 return readerMock
271         }
272         writerMock := &mocks.RnibWriterMock{}
273         writerProvider := func() rNibWriter.RNibWriter {
274                 return writerMock
275         }
276         // o&m intervention
277         payload := []byte{0x00, 0x07, 0x00, 0x08, 0x00, 0x00, 0x01, 0x00, 0x05, 0x40, 0x01, 0x64}
278         xaction := []byte(ranName)
279         msg := rmrCgo.NewMBuf(rmrCgo.RIC_X2_RESET, len(payload), ranName, &payload, &xaction)
280         rmrMessengerMock := &mocks.RmrMessengerMock{}
281         rmrMessengerMock.On("SendMsg", msg, mock.Anything).Return(msg, nil)
282
283         config := configuration.ParseConfiguration()
284         rmrService := getRmrService(rmrMessengerMock, log)
285
286         writer := httptest.NewRecorder()
287         controller := NewController(log, rmrService, readerProvider, writerProvider, config)
288
289         var nodeb = &entities.NodebInfo{ConnectionStatus: entities.ConnectionStatus_CONNECTED}
290         readerMock.On("GetNodeb", ranName).Return(nodeb, nil)
291
292         // no body
293         b := new(bytes.Buffer)
294         req, _ := http.NewRequest("PUT", "https://localhost:3800/nodeb-reset", b)
295         req = mux.SetURLVars(req, map[string]string{"ranName": ranName})
296
297         controller.X2ResetHandler(writer, req)
298         assert.Equal(t, http.StatusNoContent, writer.Result().StatusCode)
299
300 }
301
302 func TestX2ResetHandleFailureInvalidBody(t *testing.T) {
303         log := initLog(t)
304
305         ranName := "test1"
306
307         readerMock := &mocks.RnibReaderMock{}
308         readerProvider := func() reader.RNibReader {
309                 return readerMock
310         }
311         writerMock := &mocks.RnibWriterMock{}
312         writerProvider := func() rNibWriter.RNibWriter {
313                 return writerMock
314         }
315         rmrMessengerMock := &mocks.RmrMessengerMock{}
316
317         config := configuration.ParseConfiguration()
318         rmrService := getRmrService(rmrMessengerMock, log)
319
320         writer := httptest.NewRecorder()
321         controller := NewController(log, rmrService, readerProvider, writerProvider, config)
322
323         // Invalid json: attribute name without quotes (should be "cause":).
324         b := strings.NewReader("{cause:\"protocol:transfer-syntax-error\"")
325         req, _ := http.NewRequest("PUT", "https://localhost:3800/nodeb-reset", b)
326         req = mux.SetURLVars(req, map[string]string{"ranName": ranName})
327
328         controller.X2ResetHandler(writer, req)
329         assert.Equal(t, http.StatusBadRequest, writer.Result().StatusCode)
330
331         _, ok := rmrService.E2sessions[ranName]
332         assert.False(t, ok)
333
334 }
335
336 func TestHandleErrorResponse(t *testing.T) {
337         log := initLog(t)
338
339         readerMock := &mocks.RnibReaderMock{}
340         readerProvider := func() reader.RNibReader {
341                 return readerMock
342         }
343         writerMock := &mocks.RnibWriterMock{}
344         writerProvider := func() rNibWriter.RNibWriter {
345                 return writerMock
346         }
347         rmrMessengerMock := &mocks.RmrMessengerMock{}
348
349         config := configuration.ParseConfiguration()
350         rmrService := getRmrService(rmrMessengerMock, log)
351
352         controller := NewController(log, rmrService, readerProvider, writerProvider, config)
353
354         writer := httptest.NewRecorder()
355         controller.handleErrorResponse(e2managererrors.NewRnibDbError(), writer)
356         assert.Equal(t, http.StatusInternalServerError, writer.Result().StatusCode)
357
358         writer = httptest.NewRecorder()
359         controller.handleErrorResponse(e2managererrors.NewCommandAlreadyInProgressError(), writer)
360         assert.Equal(t, http.StatusMethodNotAllowed, writer.Result().StatusCode)
361
362         writer = httptest.NewRecorder()
363         controller.handleErrorResponse(e2managererrors.NewHeaderValidationError(), writer)
364         assert.Equal(t, http.StatusUnsupportedMediaType, writer.Result().StatusCode)
365
366         writer = httptest.NewRecorder()
367         controller.handleErrorResponse(e2managererrors.NewWrongStateError("", ""), writer)
368         assert.Equal(t, http.StatusBadRequest, writer.Result().StatusCode)
369
370         writer = httptest.NewRecorder()
371         controller.handleErrorResponse(e2managererrors.NewRequestValidationError(), writer)
372         assert.Equal(t, http.StatusBadRequest, writer.Result().StatusCode)
373
374         writer = httptest.NewRecorder()
375         controller.handleErrorResponse(e2managererrors.NewRmrError(), writer)
376         assert.Equal(t, http.StatusInternalServerError, writer.Result().StatusCode)
377
378         writer = httptest.NewRecorder()
379         controller.handleErrorResponse(e2managererrors.NewResourceNotFoundError(), writer)
380         assert.Equal(t, http.StatusNotFound, writer.Result().StatusCode)
381
382         writer = httptest.NewRecorder()
383         controller.handleErrorResponse(fmt.Errorf("ErrorError"), writer)
384         assert.Equal(t, http.StatusInternalServerError, writer.Result().StatusCode)
385 }