768d6bede2692ebc81f1b7cbb4dc0d155c31218c
[nonrtric/rapp/orufhrecovery.git] / goversion / internal / linkfailure / linkfailurehandler_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 linkfailure
22
23 import (
24         "bytes"
25         "encoding/json"
26         "io/ioutil"
27         "net/http"
28         "net/http/httptest"
29         "os"
30         "testing"
31
32         log "github.com/sirupsen/logrus"
33
34         "github.com/stretchr/testify/mock"
35         "github.com/stretchr/testify/require"
36         "oransc.org/usecase/oruclosedloop/internal/repository"
37         repomock "oransc.org/usecase/oruclosedloop/internal/repository/mocks"
38         "oransc.org/usecase/oruclosedloop/internal/restclient/mocks"
39         "oransc.org/usecase/oruclosedloop/internal/ves"
40 )
41
42 func Test_MessagesHandlerWithLinkFailure(t *testing.T) {
43         log.SetLevel(log.DebugLevel)
44         assertions := require.New(t)
45
46         var buf bytes.Buffer
47         log.SetOutput(&buf)
48         defer func() {
49                 log.SetOutput(os.Stderr)
50         }()
51
52         clientMock := mocks.HTTPClient{}
53
54         clientMock.On("Do", mock.Anything).Return(&http.Response{
55                 StatusCode: http.StatusOK,
56         }, nil)
57
58         lookupServiceMock := repomock.LookupService{}
59
60         lookupServiceMock.On("GetODuID", mock.Anything).Return("O-DU-1122", nil)
61
62         handlerUnderTest := NewLinkFailureHandler(&lookupServiceMock, Configuration{
63                 SDNRAddress:  "http://localhost:9990",
64                 SDNRUser:     "admin",
65                 SDNRPassword: "pwd",
66         }, &clientMock)
67
68         responseRecorder := httptest.NewRecorder()
69         r := newRequest(http.MethodPost, "/", getFaultMessage("ERICSSON-O-RU-11220", "CRITICAL"), t)
70         handler := http.HandlerFunc(handlerUnderTest.MessagesHandler)
71         handler.ServeHTTP(responseRecorder, r)
72         assertions.Equal(http.StatusOK, responseRecorder.Result().StatusCode)
73
74         var actualRequest *http.Request
75         clientMock.AssertCalled(t, "Do", mock.MatchedBy(func(req *http.Request) bool {
76                 actualRequest = req
77                 return true
78         }))
79         assertions.Equal(http.MethodPut, actualRequest.Method)
80         assertions.Equal("http", actualRequest.URL.Scheme)
81         assertions.Equal("localhost:9990", actualRequest.URL.Host)
82         expectedSdnrPath := "/rests/data/network-topology:network-topology/topology=topology-netconf/node=O-DU-1122/yang-ext:mount/o-ran-sc-du-hello-world:network-function/distributed-unit-functions=O-DU-1122/radio-resource-management-policy-ratio=rrm-pol-1"
83         assertions.Equal(expectedSdnrPath, actualRequest.URL.Path)
84         assertions.Equal("application/json; charset=utf-8", actualRequest.Header.Get("Content-Type"))
85         tempRequest, _ := http.NewRequest("", "", nil)
86         tempRequest.SetBasicAuth("admin", "pwd")
87         assertions.Equal(tempRequest.Header.Get("Authorization"), actualRequest.Header.Get("Authorization"))
88         body, _ := ioutil.ReadAll(actualRequest.Body)
89         expectedBody := []byte(`{"o-ran-sc-du-hello-world:radio-resource-management-policy-ratio":[{"id":"rrm-pol-1","radio-resource-management-policy-max-ratio":25,"radio-resource-management-policy-members":[{"mobile-country-code":"310","mobile-network-code":"150","slice-differentiator":1,"slice-service-type":1}],"radio-resource-management-policy-min-ratio":15,"user-label":"rrm-pol-1","resource-type":"prb","radio-resource-management-policy-dedicated-ratio":20,"administrative-state":"unlocked"}]}`)
90         assertions.Equal(expectedBody, body)
91         clientMock.AssertNumberOfCalls(t, "Do", 1)
92
93         logString := buf.String()
94         assertions.Contains(logString, "Sent unlock message")
95         assertions.Contains(logString, "O-RU: ERICSSON-O-RU-11220")
96         assertions.Contains(logString, "O-DU: O-DU-1122")
97 }
98
99 func newRequest(method string, url string, bodyAsBytes []byte, t *testing.T) *http.Request {
100         body := ioutil.NopCloser(bytes.NewReader(bodyAsBytes))
101         if req, err := http.NewRequest(method, url, body); err == nil {
102                 return req
103         } else {
104                 t.Fatalf("Could not create request due to: %v", err)
105                 return nil
106         }
107 }
108
109 func Test_MessagesHandlerWithClearLinkFailure(t *testing.T) {
110         log.SetLevel(log.DebugLevel)
111         assertions := require.New(t)
112
113         var buf bytes.Buffer
114         log.SetOutput(&buf)
115         defer func() {
116                 log.SetOutput(os.Stderr)
117         }()
118
119         lookupServiceMock := repomock.LookupService{}
120
121         lookupServiceMock.On("GetODuID", mock.Anything).Return("O-DU-1122", nil)
122
123         handlerUnderTest := NewLinkFailureHandler(&lookupServiceMock, Configuration{}, nil)
124
125         responseRecorder := httptest.NewRecorder()
126         r := newRequest(http.MethodPost, "/", getFaultMessage("ERICSSON-O-RU-11220", "NORMAL"), t)
127         handler := http.HandlerFunc(handlerUnderTest.MessagesHandler)
128         handler.ServeHTTP(responseRecorder, r)
129         assertions.Equal(http.StatusOK, responseRecorder.Result().StatusCode)
130
131         logString := buf.String()
132         assertions.Contains(logString, "Cleared Link failure")
133         assertions.Contains(logString, "O-RU ID: ERICSSON-O-RU-11220")
134 }
135
136 func Test_MessagesHandlerWithLinkFailureUnmappedORU(t *testing.T) {
137         log.SetLevel(log.DebugLevel)
138         assertions := require.New(t)
139
140         var buf bytes.Buffer
141         log.SetOutput(&buf)
142         defer func() {
143                 log.SetOutput(os.Stderr)
144         }()
145
146         lookupServiceMock := repomock.LookupService{}
147
148         lookupServiceMock.On("GetODuID", mock.Anything).Return("", repository.IdNotMappedError{
149                 Id: "ERICSSON-O-RU-11220",
150         })
151
152         handlerUnderTest := NewLinkFailureHandler(&lookupServiceMock, Configuration{}, nil)
153
154         responseRecorder := httptest.NewRecorder()
155         r := newRequest(http.MethodPost, "/", getFaultMessage("ERICSSON-O-RU-11220", "CRITICAL"), t)
156         handler := http.HandlerFunc(handlerUnderTest.MessagesHandler)
157         handler.ServeHTTP(responseRecorder, r)
158         assertions.Equal(http.StatusOK, responseRecorder.Result().StatusCode)
159
160         logString := buf.String()
161         assertions.Contains(logString, "O-RU-ID: ERICSSON-O-RU-11220 not mapped.")
162 }
163
164 func getFaultMessage(sourceName string, eventSeverity string) []byte {
165         linkFailureMessage := ves.FaultMessage{
166                 Event: ves.Event{
167                         CommonEventHeader: ves.CommonEventHeader{
168                                 Domain:     "fault",
169                                 SourceName: sourceName,
170                         },
171                         FaultFields: ves.FaultFields{
172                                 AlarmCondition: "28",
173                                 EventSeverity:  eventSeverity,
174                         },
175                 },
176         }
177         messageAsByteArray, _ := json.Marshal(linkFailureMessage)
178         response := [1]string{string(messageAsByteArray)}
179         responseAsByteArray, _ := json.Marshal(response)
180         return responseAsByteArray
181 }