050417f550405a63ed17270986a18ef7aafbd724
[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         "oransc.org/usecase/oruclosedloop/internal/ves"
38         "oransc.org/usecase/oruclosedloop/mocks"
39 )
40
41 func Test_MessagesHandlerWithLinkFailure(t *testing.T) {
42         log.SetLevel(log.DebugLevel)
43         assertions := require.New(t)
44
45         var buf bytes.Buffer
46         log.SetOutput(&buf)
47         defer func() {
48                 log.SetOutput(os.Stderr)
49         }()
50
51         clientMock := mocks.HTTPClient{}
52
53         clientMock.On("Do", mock.Anything).Return(&http.Response{
54                 StatusCode: http.StatusOK,
55         }, nil)
56
57         lookupServiceMock := mocks.LookupService{}
58
59         lookupServiceMock.On("GetODuID", mock.Anything).Return("O-DU-1122", nil)
60
61         handlerUnderTest := NewLinkFailureHandler(&lookupServiceMock, Configuration{
62                 SDNRAddress:  "http://localhost:9990",
63                 SDNRUser:     "admin",
64                 SDNRPassword: "pwd",
65         }, &clientMock)
66
67         responseRecorder := httptest.NewRecorder()
68         r := newRequest(http.MethodPost, "/", getFaultMessage("ERICSSON-O-RU-11220", "CRITICAL"), t)
69         handler := http.HandlerFunc(handlerUnderTest.MessagesHandler)
70         handler.ServeHTTP(responseRecorder, r)
71         assertions.Equal(http.StatusOK, responseRecorder.Result().StatusCode)
72
73         var actualRequest *http.Request
74         clientMock.AssertCalled(t, "Do", mock.MatchedBy(func(req *http.Request) bool {
75                 actualRequest = req
76                 return true
77         }))
78         assertions.Equal(http.MethodPut, actualRequest.Method)
79         assertions.Equal("http", actualRequest.URL.Scheme)
80         assertions.Equal("localhost:9990", actualRequest.URL.Host)
81         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"
82         assertions.Equal(expectedSdnrPath, actualRequest.URL.Path)
83         assertions.Equal("application/json; charset=utf-8", actualRequest.Header.Get("Content-Type"))
84         tempRequest, _ := http.NewRequest("", "", nil)
85         tempRequest.SetBasicAuth("admin", "pwd")
86         assertions.Equal(tempRequest.Header.Get("Authorization"), actualRequest.Header.Get("Authorization"))
87         body, _ := ioutil.ReadAll(actualRequest.Body)
88         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"}]}`)
89         assertions.Equal(expectedBody, body)
90         clientMock.AssertNumberOfCalls(t, "Do", 1)
91
92         logString := buf.String()
93         assertions.Contains(logString, "Sent unlock message")
94         assertions.Contains(logString, "O-RU: ERICSSON-O-RU-11220")
95         assertions.Contains(logString, "O-DU: O-DU-1122")
96 }
97
98 func newRequest(method string, url string, bodyAsBytes []byte, t *testing.T) *http.Request {
99         body := ioutil.NopCloser(bytes.NewReader(bodyAsBytes))
100         if req, err := http.NewRequest(method, url, body); err == nil {
101                 return req
102         } else {
103                 t.Fatalf("Could not create request due to: %v", err)
104                 return nil
105         }
106 }
107
108 func Test_MessagesHandlerWithClearLinkFailure(t *testing.T) {
109         log.SetLevel(log.DebugLevel)
110         assertions := require.New(t)
111
112         var buf bytes.Buffer
113         log.SetOutput(&buf)
114         defer func() {
115                 log.SetOutput(os.Stderr)
116         }()
117
118         lookupServiceMock := mocks.LookupService{}
119
120         lookupServiceMock.On("GetODuID", mock.Anything).Return("O-DU-1122", nil)
121
122         handlerUnderTest := NewLinkFailureHandler(&lookupServiceMock, Configuration{}, nil)
123
124         responseRecorder := httptest.NewRecorder()
125         r := newRequest(http.MethodPost, "/", getFaultMessage("ERICSSON-O-RU-11220", "NORMAL"), t)
126         handler := http.HandlerFunc(handlerUnderTest.MessagesHandler)
127         handler.ServeHTTP(responseRecorder, r)
128         assertions.Equal(http.StatusOK, responseRecorder.Result().StatusCode)
129
130         logString := buf.String()
131         assertions.Contains(logString, "Cleared Link failure")
132         assertions.Contains(logString, "O-RU ID: ERICSSON-O-RU-11220")
133 }
134
135 func Test_MessagesHandlerWithLinkFailureUnmappedORU(t *testing.T) {
136         log.SetLevel(log.DebugLevel)
137         assertions := require.New(t)
138
139         var buf bytes.Buffer
140         log.SetOutput(&buf)
141         defer func() {
142                 log.SetOutput(os.Stderr)
143         }()
144
145         lookupServiceMock := mocks.LookupService{}
146
147         lookupServiceMock.On("GetODuID", mock.Anything).Return("", repository.IdNotMappedError{
148                 Id: "ERICSSON-O-RU-11220",
149         })
150
151         handlerUnderTest := NewLinkFailureHandler(&lookupServiceMock, Configuration{}, nil)
152
153         responseRecorder := httptest.NewRecorder()
154         r := newRequest(http.MethodPost, "/", getFaultMessage("ERICSSON-O-RU-11220", "CRITICAL"), t)
155         handler := http.HandlerFunc(handlerUnderTest.MessagesHandler)
156         handler.ServeHTTP(responseRecorder, r)
157         assertions.Equal(http.StatusOK, responseRecorder.Result().StatusCode)
158
159         logString := buf.String()
160         assertions.Contains(logString, "O-RU-ID: ERICSSON-O-RU-11220 not mapped.")
161 }
162
163 func getFaultMessage(sourceName string, eventSeverity string) []byte {
164         linkFailureMessage := ves.FaultMessage{
165                 Event: ves.Event{
166                         CommonEventHeader: ves.CommonEventHeader{
167                                 Domain:     "fault",
168                                 SourceName: sourceName,
169                         },
170                         FaultFields: ves.FaultFields{
171                                 AlarmCondition: "28",
172                                 EventSeverity:  eventSeverity,
173                         },
174                 },
175         }
176         messageAsByteArray, _ := json.Marshal(linkFailureMessage)
177         response := [1]string{string(messageAsByteArray)}
178         responseAsByteArray, _ := json.Marshal(response)
179         return responseAsByteArray
180 }