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