Moving RMR message reciver into go routine
[ric-plt/a1.git] / a1-go / pkg / resthooks / resthooks_test.go
1 /*
2 ==================================================================================
3   Copyright (c) 2021 Samsung
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    This source code is part of the near-RT RIC (RAN Intelligent Controller)
18    platform project (RICP).
19 ==================================================================================
20 */
21 package resthooks
22
23 import (
24         "encoding/json"
25         "os"
26         "strconv"
27         "testing"
28         "time"
29
30         "gerrit.o-ran-sc.org/r/ric-plt/a1/pkg/a1"
31         "gerrit.o-ran-sc.org/r/ric-plt/a1/pkg/models"
32         "github.com/stretchr/testify/assert"
33         "github.com/stretchr/testify/mock"
34 )
35
36 type RmrSenderMock struct {
37         mock.Mock
38 }
39
40 var rh *Resthook
41 var sdlInst *SdlMock
42 var rmrSenderInst *RmrSenderMock
43
44 func TestMain(m *testing.M) {
45         sdlInst = new(SdlMock)
46
47         sdlInst.On("GetAll", "A1m_ns").Return([]string{"a1.policy_instance.1006001.qos",
48                 "a1.policy_instance.20005.123456",
49                 "a1.policy_instance.20005.234567",
50                 "a1.policy_type.1006001",
51                 "a1.policy_type.20000",
52                 "a1.policy_inst_metadata.1006001.qos",
53         }, nil)
54         rmrSenderInst = new(RmrSenderMock)
55         a1.Init()
56         rh = createResthook(sdlInst, rmrSenderInst)
57         code := m.Run()
58         os.Exit(code)
59 }
60
61 func TestHealth(t *testing.T) {
62         resp := rh.GetA1Health()
63         if resp == true {
64                 a1.Logger.Debug("A1 is healthy ")
65                 assert.Equal(t, true, resp)
66         } else {
67                 a1.Logger.Debug("A1 is unhealthy")
68                 assert.Equal(t, false, resp)
69         }
70 }
71
72 func TestGetAllPolicyType(t *testing.T) {
73         resp := rh.GetAllPolicyType()
74         assert.Equal(t, 2, len(resp))
75 }
76
77 func TestGetPolicyType(t *testing.T) {
78
79         policyTypeId := models.PolicyTypeID(20001)
80
81         var policyTypeSchema models.PolicyTypeSchema
82         name := "admission_control_policy_mine"
83         policyTypeSchema.Name = &name
84         policytypeid := int64(20001)
85         policyTypeSchema.PolicyTypeID = &policytypeid
86         description := "various parameters to control admission of dual connection"
87         policyTypeSchema.Description = &description
88         schema := `{"$schema": "http://json-schema.org/draft-07/schema#","type":"object","properties": {"enforce": {"type":"boolean","default":"true",},"window_length": {"type":        "integer","default":1,"minimum":1,"maximum":60,"description": "Sliding window length (in minutes)",},
89 "blocking_rate": {"type":"number","default":10,"minimum":1,"maximum":100,"description": "% Connections to block",},"additionalProperties": false,},}`
90         policyTypeSchema.CreateSchema = schema
91         key := a1PolicyPrefix + strconv.FormatInt((int64(policyTypeId)), 10)
92         var keys [1]string
93         keys[0] = key
94         //Setup Expectations
95         sdlInst.On("Get", a1MediatorNs, keys[:]).Return(map[string]interface{}{key: policyTypeSchema}, nil)
96         resp := rh.GetPolicyType(policyTypeId)
97         assert.NotNil(t, resp)
98
99         sdlInst.AssertExpectations(t)
100
101 }
102
103 func TestCreatePolicyType(t *testing.T) {
104         var policyTypeId models.PolicyTypeID
105         policyTypeId = 20001
106         var policyTypeSchema models.PolicyTypeSchema
107         name := "admission_control_policy_mine"
108         policyTypeSchema.Name = &name
109         policytypeid := int64(20001)
110         policyTypeSchema.PolicyTypeID = &policytypeid
111         description := "various parameters to control admission of dual connection"
112         policyTypeSchema.Description = &description
113         policyTypeSchema.CreateSchema = `{"$schema": "http://json-schema.org/draft-07/schema#","type":"object","properties": {"enforce": {"type":"boolean","default":"true",},"window_length": {"type":        "integer","default":1,"minimum":1,"maximum":60,"description": "Sliding window length (in minutes)",},
114 "blocking_rate": {"type":"number","default":10,"minimum":1,"maximum":100,"description": "% Connections to block",},"additionalProperties": false,},}`
115
116         data, err := policyTypeSchema.MarshalBinary()
117         a1.Logger.Debug("error : %+v ", err)
118         a1.Logger.Debug("data : %+v ", data)
119         key := a1PolicyPrefix + strconv.FormatInt(20001, 10)
120         a1.Logger.Debug("key : %+v ", key)
121         //Setup Expectations
122         sdlInst.On("SetIfNotExists", a1MediatorNs, key, string(data)).Return(true, nil)
123
124         errresp := rh.CreatePolicyType(policyTypeId, policyTypeSchema)
125         //Data Assertion
126         assert.Nil(t, errresp)
127         //Mock Assertion :Behavioral
128         sdlInst.AssertExpectations(t)
129 }
130
131 func TestCreatePolicyTypeInstance(t *testing.T) {
132         var policyInstanceID models.PolicyInstanceID
133         policyInstanceID = "123456"
134         var httpBody = `{"enforce":true,"window_length":20,"blocking_rate":20,"trigger_threshold":10}`
135         instancekey := a1InstancePrefix + strconv.FormatInt(20001, 10) + "." + string(policyInstanceID)
136         var policyTypeId models.PolicyTypeID
137         policyTypeId = 20001
138
139         var instancedata map[string]interface{}
140
141         json.Unmarshal([]byte(httpBody), &instancedata)
142
143         data, _ := json.Marshal(instancedata)
144         a1.Logger.Debug("Marshaled data : %+v", string(data))
145         a1.Logger.Debug("instancekey   : %+v", instancekey)
146         instancearr := []interface{}{instancekey, string(data)}
147         sdlInst.On("Set", "A1m_ns", instancearr).Return(nil)
148
149         metadatainstancekey := a1InstanceMetadataPrefix + strconv.FormatInt(20001, 10) + "." + string(policyInstanceID)
150         creation_timestamp := time.Now()
151         var metadatajson []interface{}
152         metadatajson = append(metadatajson, map[string]string{"created_at": creation_timestamp.Format("2006-01-02 15:04:05"), "has_been_deleted": "False"})
153         metadata, _ := json.Marshal(metadatajson)
154         a1.Logger.Debug("Marshaled Metadata : %+v", string(metadata))
155         a1.Logger.Debug("metadatainstancekey   : %+v", metadatainstancekey)
156         metadatainstancearr := []interface{}{metadatainstancekey, string(metadata)}
157         sdlInst.On("Set", "A1m_ns", metadatainstancearr).Return(nil)
158         rmrSenderInst.On("RmrSendToXapp", "httpBodyString", 20010).Return(true)
159
160         errresp := rh.CreatePolicyInstance(policyTypeId, policyInstanceID, instancedata)
161
162         assert.Nil(t, errresp)
163         sdlInst.AssertExpectations(t)
164 }
165
166 func TestGetPolicyInstance(t *testing.T) {
167
168         var policyTypeId models.PolicyTypeID
169         policyTypeId = 20001
170         var policyInstanceID models.PolicyInstanceID
171         policyInstanceID = "123456"
172         httpBody := `{
173                 "enforce":true,
174                 "window_length":20,
175            "blocking_rate":20,
176                 "trigger_threshold":10
177                 }`
178         instancekey := a1InstancePrefix + strconv.FormatInt(20001, 10) + "." + string(policyInstanceID)
179         a1.Logger.Debug("httpBody String : %+v", httpBody)
180         a1.Logger.Debug("key   : %+v", instancekey)
181         var keys [1]string
182         keys[0] = instancekey
183         //Setup Expectations
184         sdlInst.On("Get", a1MediatorNs, keys[:]).Return(httpBody, nil)
185
186         resp, err := rh.GetPolicyInstance(policyTypeId, policyInstanceID)
187         a1.Logger.Error("err : %+v", err)
188         assert.NotNil(t, resp)
189
190         sdlInst.AssertExpectations(t)
191 }
192
193 func TestGetAllPolicyIntances(t *testing.T) {
194         var policyTypeId models.PolicyTypeID
195         policyTypeId = 20005
196         resp, err := rh.GetAllPolicyInstance(policyTypeId)
197         a1.Logger.Error("err : %+v", err)
198         assert.Equal(t, 2, len(resp))
199 }
200
201 func TestDeletePolicyType(t *testing.T) {
202
203         policyTypeId := models.PolicyTypeID(20001)
204         key := a1PolicyPrefix + strconv.FormatInt((int64(policyTypeId)), 10)
205         var keys [1]string
206         keys[0] = key
207
208         //Setup Expectations
209         sdlInst.On("Remove", a1MediatorNs, keys[:]).Return(nil)
210
211         errresp := rh.DeletePolicyType(policyTypeId)
212
213         assert.Nil(t, errresp)
214         sdlInst.AssertExpectations(t)
215 }
216
217 func TestGetPolicyInstanceStatus(t *testing.T) {
218         var policyTypeId models.PolicyTypeID
219         policyTypeId = 20001
220         var policyInstanceID models.PolicyInstanceID
221         policyInstanceID = "123456"
222         httpBody := `{
223                 "created_at":"0001-01-01T00:00:00.000Z",
224                 "instance_status":"NOT IN EFFECT"
225                 }`
226         instancekey := a1InstanceMetadataPrefix + strconv.FormatInt(20001, 10) + "." + string(policyInstanceID)
227         a1.Logger.Debug("httpBody String : %+v", httpBody)
228         a1.Logger.Debug("key   : %+v", instancekey)
229         var keys [1]string
230         keys[0] = instancekey
231         sdlInst.On("Get", a1MediatorNs, keys[:]).Return(httpBody)
232
233         resp, errresp := rh.GetPolicyInstanceStatus(policyTypeId, policyInstanceID)
234
235         assert.Nil(t, errresp)
236         assert.NotNil(t, resp)
237         sdlInst.AssertExpectations(t)
238 }
239
240 func TestDeletePolicyInstance(t *testing.T) {
241         var policyTypeId models.PolicyTypeID
242         policyTypeId = 20001
243         var policyInstanceID models.PolicyInstanceID
244         policyInstanceID = "123456"
245         var policyTypeSchema models.PolicyTypeSchema
246         name := "admission_control_policy_mine"
247         policyTypeSchema.Name = &name
248         policytypeid := int64(20001)
249         policyTypeSchema.PolicyTypeID = &policytypeid
250         description := "various parameters to control admission of dual connection"
251         policyTypeSchema.Description = &description
252         schema := `{"$schema": "http://json-schema.org/draft-07/schema#","type":"object","properties": {"enforce": {"type":"boolean","default":"true",},"window_length": {"type":        "integer","default":1,"minimum":1,"maximum":60,"description": "Sliding window length (in minutes)",},
253 "blocking_rate": {"type":"number","default":10,"minimum":1,"maximum":100,"description": "% Connections to block",},"additionalProperties": false,},}`
254         policyTypeSchema.CreateSchema = schema
255
256         key := a1PolicyPrefix + strconv.FormatInt((int64(policyTypeId)), 10)
257         var policytypekeys [1]string
258         policytypekeys[0] = key
259
260         sdlInst.On("Get", a1MediatorNs, policytypekeys[:]).Return(map[string]interface{}{key: policyTypeSchema}, nil)
261
262         httpBody := `{
263                 "enforce":true,
264                 "window_length":20,
265            "blocking_rate":20,
266                 "trigger_threshold":10
267                 }`
268         instancekey := a1InstancePrefix + strconv.FormatInt(20001, 10) + "." + string(policyInstanceID)
269         var instancekeys [1]string
270         instancekeys[0] = instancekey
271
272         sdlInst.On("Get", a1MediatorNs, instancekeys[:]).Return(httpBody, nil)
273
274         var instanceMetadataKeys [1]string
275         instanceMetadataKey := a1InstanceMetadataPrefix + strconv.FormatInt((int64(policyTypeId)), 10) + "." + string(policyInstanceID)
276         instanceMetadataKeys[0] = instanceMetadataKey
277         httpBody = `{
278                 "created_at":"2022-11-02 10:30:20",
279                         "instance_status":"NOT IN EFFECT"
280                 }`
281
282         sdlInst.On("Get", a1MediatorNs, instanceMetadataKeys[:]).Return(httpBody, nil)
283
284         sdlInst.On("Remove", a1MediatorNs, instanceMetadataKeys[:]).Return(nil)
285
286         var metadatainstancekeys [1]string
287         metadatainstancekeys[0] = instancekey
288
289         sdlInst.On("Remove", a1MediatorNs, metadatainstancekeys[:]).Return(nil)
290
291         metadatainstancekey := a1InstanceMetadataPrefix + strconv.FormatInt(20001, 10) + "." + string(policyInstanceID)
292         deleted_timestamp := time.Now()
293         var metadatajson interface{}
294         metadatajson = map[string]string{"created_at": "2022-11-02 10:30:20", "deleted_at": deleted_timestamp.Format("2006-01-02 15:04:05"), "has_been_deleted": "True"}
295         metadata, _ := json.Marshal(metadatajson)
296         metadatainstancearr := []interface{}{metadatainstancekey, string(metadata)}
297
298         sdlInst.On("Set", "A1m_ns", metadatainstancearr).Return(nil)
299
300         httpBodyString := `{"operation":"DELETE","payload":"","policy_instance_id":"123456","policy_type_id":"20001"}`
301
302         rmrSenderInst.On("RmrSendToXapp", httpBodyString, 20010).Return(true)
303
304         errresp := rh.DeletePolicyInstance(policyTypeId, policyInstanceID)
305
306         assert.Nil(t, errresp)
307         sdlInst.AssertExpectations(t)
308 }
309 func TestDataDelivery(t *testing.T) {
310
311         httpBody := `{
312                 "job":"1",
313                 "payload":"payload"
314                 }
315                 `
316         var instancedata interface{}
317
318         json.Unmarshal([]byte(httpBody), &instancedata)
319         a1.Logger.Debug("Marshaled data : %+v", (instancedata))
320         httpBodyString := `{"ei_job_id":"1","payload":"payload"}`
321         rmrSenderInst.On("RmrSendToXapp", httpBodyString, 20017).Return(true)
322         errresp := rh.DataDelivery(instancedata)
323
324         assert.Nil(t, errresp)
325         sdlInst.AssertExpectations(t)
326 }
327
328 func TestGetMetaData(t *testing.T) {
329         var policyTypeId models.PolicyTypeID
330         policyTypeId = 20001
331         var policyInstanceID models.PolicyInstanceID
332         policyInstanceID = "123456"
333         instanceMetadataKey := a1InstanceMetadataPrefix + strconv.FormatInt((int64(policyTypeId)), 10) + "." + string(policyInstanceID)
334         a1.Logger.Debug("key : %+v", instanceMetadataKey)
335
336         var keys [1]string
337         keys[0] = instanceMetadataKey
338
339         policySchemaString := `{
340                 "created_at":"2022-11-02 10:30:20",
341                 "instance_status":"NOT IN EFFECT"
342                 }`
343
344         sdlInst.On("Get", a1MediatorNs, keys[:]).Return(map[string]interface{}{instanceMetadataKey: policySchemaString}, nil)
345
346         resp, errresp := rh.getMetaData(policyTypeId, policyInstanceID)
347
348         assert.Nil(t, errresp)
349         assert.NotNil(t, resp)
350         sdlInst.AssertExpectations(t)
351 }
352
353 type SdlMock struct {
354         mock.Mock
355 }
356
357 func (s *SdlMock) GetAll(ns string) ([]string, error) {
358         args := s.MethodCalled("GetAll", ns)
359         return args.Get(0).([]string), nil
360 }
361
362 func (s *SdlMock) Get(ns string, keys []string) (map[string]interface{}, error) {
363         a1.Logger.Debug("Get Called ")
364         args := s.MethodCalled("Get", ns, keys)
365         a1.Logger.Debug("ns :%+v", args.Get(0))
366         policytypeid := int64(20001)
367         policyInstanceID := "123456"
368         var policySchemaString string
369         var key string
370         if keys[0] == "a1.policy_instance.20001.123456" {
371                 policySchemaString = `{
372                         "enforce":true,
373                         "window_length":20,
374                    "blocking_rate":20,
375                         "trigger_threshold":10
376                         }`
377                 key = a1InstancePrefix + strconv.FormatInt(policytypeid, 10) + "." + string(policyInstanceID)
378         } else if keys[0] == "a1.policy_type.20001" {
379                 policySchemaString = `{"create_schema":{"$schema":"http://json-schema.org/draft-07/schema#","properties":{"additionalProperties":false,"blocking_rate":{"default":10,"description":"% Connections to block","maximum":1001,"minimum":1,"type":"number"},"enforce":{"default":"true","type":"boolean"},"window_length":{"default":1,"description":"Sliding window length (in minutes)","maximum":60,"minimum":1,"type":"integer"}},"type":"object"},"description":"various parameters to control admission of dual connection","name":"admission_control_policy_mine","policy_type_id":20001}`
380                 key = a1PolicyPrefix + strconv.FormatInt((policytypeid), 10)
381         } else if keys[0] == "a1.policy_inst_metadata.20001.123456" {
382                 policySchemaString = `{
383                         "created_at":"2022-11-02 10:30:20",
384                         "instance_status":"NOT IN EFFECT"
385                         }`
386                 key = a1InstanceMetadataPrefix + strconv.FormatInt(policytypeid, 10) + "." + string(policyInstanceID)
387         }
388         a1.Logger.Debug(" policy SchemaString %+v", policySchemaString)
389         policyTypeSchema, _ := json.Marshal((policySchemaString))
390         a1.Logger.Debug(" policyTypeSchema %+v", string(policyTypeSchema))
391
392         a1.Logger.Debug(" key for policy type %+v", key)
393         mp := map[string]interface{}{key: string(policySchemaString)}
394         a1.Logger.Debug("Get Called and mp return %+v ", mp)
395         return mp, nil
396 }
397 func (s *SdlMock) SetIfNotExists(ns string, key string, data interface{}) (bool, error) {
398         args := s.MethodCalled("SetIfNotExists", ns, key, data)
399         return args.Bool(0), args.Error(1)
400 }
401
402 func (s *SdlMock) Set(ns string, pairs ...interface{}) error {
403         args := s.MethodCalled("Set", ns, pairs)
404         return args.Error(0)
405 }
406 func (s *SdlMock) SetIf(ns string, key string, oldData, newData interface{}) (bool, error) {
407         args := s.MethodCalled("SetIfNotExists", ns, key, oldData, newData)
408         return args.Bool(0), args.Error(1)
409 }
410
411 func (rmr *RmrSenderMock) RmrSendToXapp(httpBodyString string, mtype int) bool {
412         if httpBodyString == `{"blocking_rate":20,"enforce":true,"trigger_threshold":10,"window_length":20}` {
413                 args := rmr.MethodCalled("RmrSendToXapp", httpBodyString, mtype)
414                 return args.Bool(0)
415         } else if httpBodyString == `{"ei_job_id":"1","payload":"payload"}` {
416                 args := rmr.MethodCalled("RmrSendToXapp", httpBodyString, mtype)
417                 return args.Bool(0)
418         }
419         return true
420 }
421
422 func (s *SdlMock) Remove(ns string, keys []string) error {
423         args := s.MethodCalled("Remove", ns, keys)
424         return args.Error(0)
425 }