Subscription REST interface update
[ric-plt/xapp-frame.git] / pkg / xapp / subscription_test.go
1 /*
2 ==================================================================================
3   Copyright (c) 2019 Nokia
4 ==================================================================================
5 */
6
7 package xapp
8
9 import (
10         "bytes"
11         "fmt"
12         "net/http"
13         "net/http/httptest"
14         "testing"
15         "time"
16
17         "gerrit.o-ran-sc.org/r/ric-plt/xapp-frame/pkg/clientmodel"
18         "gerrit.o-ran-sc.org/r/ric-plt/xapp-frame/pkg/models"
19         "gerrit.o-ran-sc.org/r/ric-plt/xapp-frame/pkg/restapi/operations/common"
20         "github.com/stretchr/testify/assert"
21 )
22
23 var (
24         suite *testing.T
25
26         meid                = "gnb123456"
27         xappEventInstanceId = int64(1)
28         eventInstanceId     = int64(1)
29         funId               = int64(1)
30         actionId            = int64(1)
31         actionType          = "report"
32         subsequestActioType = "continue"
33         timeToWait          = "w10ms"
34         direction           = int64(0)
35         procedureCode       = int64(27)
36         typeOfMessage       = int64(1)
37         subscriptionId      = ""
38         hPort               = int64(8080)
39         rPort               = int64(4560)
40         clientEndpoint      = clientmodel.SubscriptionParamsClientEndpoint{Host: "localhost", HTTPPort: &hPort, RMRPort: &rPort}
41 )
42
43 // Test cases
44 func TestSetup(t *testing.T) {
45         suite = t
46
47         // Start the server to simulate SubManager
48         go Subscription.Listen(subscriptionHandler, queryHandler, deleteHandler)
49         time.Sleep(time.Duration(2) * time.Second)
50 }
51
52 func TestSubscriptionQueryHandling(t *testing.T) {
53         resp, err := Subscription.QuerySubscriptions()
54
55         assert.Equal(t, err, nil)
56         assert.Equal(t, resp[0].SubscriptionID, int64(11))
57         assert.Equal(t, resp[0].Meid, "Test-Gnb")
58         assert.Equal(t, resp[0].ClientEndpoint, []string{"127.0.0.1:4056"})
59 }
60
61 func TestSubscriptionHandling(t *testing.T) {
62         subscriptionParams := GetSubscriptionparams()
63
64         Subscription.SetResponseCB(func(resp *clientmodel.SubscriptionResponse) {
65                 assert.Equal(t, len(resp.SubscriptionInstances), 1)
66                 assert.Equal(t, *resp.SubscriptionInstances[0].XappEventInstanceID, int64(11))
67                 assert.Equal(t, *resp.SubscriptionInstances[0].E2EventInstanceID, int64(22))
68         })
69
70         _, err := Subscription.Subscribe(subscriptionParams)
71         assert.Equal(t, err, nil)
72 }
73
74 func TestSubscriptionWithClientProvidedIdHandling(t *testing.T) {
75         subscriptionParams := GetSubscriptionparams()
76         subscriptionParams.SubscriptionID = "myxapp"
77     
78         Subscription.SetResponseCB(func(resp *clientmodel.SubscriptionResponse) {
79                 assert.Equal(t, len(resp.SubscriptionInstances), 1)
80                 assert.Equal(t, *resp.SubscriptionInstances[0].XappEventInstanceID, int64(11))
81                 assert.Equal(t, *resp.SubscriptionInstances[0].E2EventInstanceID, int64(22))
82         })
83
84         _, err := Subscription.Subscribe(subscriptionParams)
85         assert.Equal(t, err, nil)
86 }
87
88 func TestBadRequestSubscriptionHandling(t *testing.T) {
89         subscriptionParams := GetSubscriptionparams()
90         subscriptionParams.SubscriptionID = "123_send_bad_request_response"
91
92         Subscription.SetResponseCB(func(resp *clientmodel.SubscriptionResponse) {
93                 assert.Equal(t, len(resp.SubscriptionInstances), 1)
94                 assert.Equal(t, *resp.SubscriptionInstances[0].XappEventInstanceID, int64(11))
95                 assert.Equal(t, *resp.SubscriptionInstances[0].E2EventInstanceID, int64(22))
96         })
97
98         _, err := Subscription.Subscribe(subscriptionParams)
99         assert.Equal(t, err.Error(), "[POST /subscriptions][400] subscribeBadRequest ")
100         fmt.Println("Error:",err)
101 }
102
103 func TestInternalServerErrorSubscriptionHandling(t *testing.T) {
104         subscriptionParams := GetSubscriptionparams()
105         subscriptionParams.SubscriptionID = "123_send_internal_server_error_response"
106
107         Subscription.SetResponseCB(func(resp *clientmodel.SubscriptionResponse) {
108                 assert.Equal(t, len(resp.SubscriptionInstances), 1)
109                 assert.Equal(t, *resp.SubscriptionInstances[0].XappEventInstanceID, int64(11))
110                 assert.Equal(t, *resp.SubscriptionInstances[0].E2EventInstanceID, int64(22))
111         })
112
113         _, err := Subscription.Subscribe(subscriptionParams)
114         assert.Equal(t, err.Error(), "[POST /subscriptions][500] subscribeInternalServerError ")
115         fmt.Println("Error:",err)
116 }
117
118 func GetSubscriptionparams() *clientmodel.SubscriptionParams {
119         return &clientmodel.SubscriptionParams{
120                 SubscriptionID: "",
121                 Meid:           &meid,
122                 RANFunctionID:  &funId,
123                 ClientEndpoint: &clientEndpoint,
124                 SubscriptionDetails: clientmodel.SubscriptionDetailsList{
125                         &clientmodel.SubscriptionDetail{
126                                 XappEventInstanceID: &eventInstanceId,
127                                 EventTriggers:       clientmodel.EventTriggerDefinition{00, 0x11, 0x12, 0x13, 0x00, 0x21, 0x22, 0x24, 0x1B, 0x80},
128                                 ActionToBeSetupList: clientmodel.ActionsToBeSetup{
129                                         &clientmodel.ActionToBeSetup{
130                                                 ActionID:         &actionId,
131                                                 ActionType:       &actionType,
132                                                 ActionDefinition: clientmodel.ActionDefinition{5, 6, 7, 8},
133                                                 SubsequentAction: &clientmodel.SubsequentAction{
134                                                         SubsequentActionType: &subsequestActioType,
135                                                         TimeToWait:           &timeToWait,
136                                                 },
137                                         },
138                                 },
139                         },
140                 },
141         }
142 }
143
144 func TestSuccessfulSubscriptionDeleteHandling(t *testing.T) {
145         subscriptionId = "123_send_successful_response"
146         err := Subscription.Unsubscribe(subscriptionId)
147         assert.Equal(t, err, nil)
148         fmt.Println("Error:",err)
149 }
150
151 func TestBadRequestSubscriptionDeleteHandling(t *testing.T) {
152         subscriptionId = "123_send_bad_request_response"
153         err := Subscription.Unsubscribe(subscriptionId)
154         assert.NotEqual(t, err, nil)
155         fmt.Println("Error:",err.Error())
156         assert.Equal(t, err.Error(), "[DELETE /subscriptions/{subscriptionId}][400] unsubscribeBadRequest ")
157 }
158
159 func TestInternalServerErrorSubscriptionDeleteHandling(t *testing.T) {
160         subscriptionId = "123_send_internal_server_error_response"
161         err := Subscription.Unsubscribe(subscriptionId)
162         assert.NotEqual(t, err, nil)
163         fmt.Println("Error:",err.Error())
164         assert.Equal(t, err.Error(), "[DELETE /subscriptions/{subscriptionId}][500] unsubscribeInternalServerError ")
165 }
166
167 func TestResponseHandler(t *testing.T) {
168         Subscription.SetResponseCB(SubscriptionRespHandler)
169
170         payload := []byte(`{"SubscriptionInstances":[{"tXappEventInstanceID": 1}]`)
171         req, err := http.NewRequest("POST", "/ric/v1/subscriptions/response", bytes.NewBuffer(payload))
172         if err != nil {
173                 t.Fatal(err)
174         }
175
176         rr := httptest.NewRecorder()
177         handler := http.HandlerFunc(Subscription.ResponseHandler)
178         handler.ServeHTTP(rr, req)
179
180         if status := rr.Code; status != http.StatusOK {
181                 t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)
182         }
183         time.Sleep(time.Duration(2) * time.Second)
184 }
185
186 // Helper functions
187 func SubscriptionRespHandler(resp *clientmodel.SubscriptionResponse) {
188 }
189
190 func processSubscriptions(subscriptionId string) {
191         // Generate requestorId, instanceId
192         xappInstanceId := int64(11)
193         e2InstanceId := int64(22)
194
195         resp := &models.SubscriptionResponse{
196                 SubscriptionID: &subscriptionId,
197                 SubscriptionInstances: []*models.SubscriptionInstance{
198                         {
199                                 XappEventInstanceID: &xappInstanceId,
200                                 E2EventInstanceID:   &e2InstanceId,
201                         },
202                 },
203         }
204
205         // Notify the client: don't worry about errors ... Notify() will handle retries, etc.
206         Subscription.Notify(resp, models.SubscriptionParamsClientEndpoint{Host: "localhost", HTTPPort: &hPort, RMRPort: &rPort})
207 }
208
209 func subscriptionHandler(params interface{}) (*models.SubscriptionResponse, int) {
210         p := params.(*models.SubscriptionParams)
211
212         assert.Equal(suite, meid, *p.Meid)
213         assert.Equal(suite, funId, *p.RANFunctionID)
214         assert.Equal(suite, clientEndpoint.Host, p.ClientEndpoint.Host)
215         assert.Equal(suite, clientEndpoint.HTTPPort, p.ClientEndpoint.HTTPPort)
216         assert.Equal(suite, clientEndpoint.RMRPort, p.ClientEndpoint.RMRPort)
217
218         assert.Equal(suite, xappEventInstanceId, *p.SubscriptionDetails[0].XappEventInstanceID)
219         et := []int64{00, 0x11, 0x12, 0x13, 0x00, 0x21, 0x22, 0x24, 0x1B, 0x80}
220         assert.ElementsMatch(suite, et, p.SubscriptionDetails[0].EventTriggers)
221         assert.Equal(suite, actionId, *p.SubscriptionDetails[0].ActionToBeSetupList[0].ActionID)
222         assert.Equal(suite, actionType, *p.SubscriptionDetails[0].ActionToBeSetupList[0].ActionType)
223
224         assert.Equal(suite, subsequestActioType, *p.SubscriptionDetails[0].ActionToBeSetupList[0].SubsequentAction.SubsequentActionType)
225         assert.Equal(suite, timeToWait, *p.SubscriptionDetails[0].ActionToBeSetupList[0].SubsequentAction.TimeToWait)
226         assert.ElementsMatch(suite, []int64{5, 6, 7, 8}, p.SubscriptionDetails[0].ActionToBeSetupList[0].ActionDefinition)
227
228         // Generate a unique subscriptionId
229         subscriptionId = fmt.Sprintf("%s-%s", meid, clientEndpoint.Host)
230
231         if p.SubscriptionID == "123_send_bad_request_response" {
232                 // Simulate bad request case
233                 return &models.SubscriptionResponse{
234                 }, common.UnsubscribeBadRequestCode
235
236         }
237
238         if p.SubscriptionID == "123_send_internal_server_error_response" {
239                 // Simulate bad internal server error case
240                 return &models.SubscriptionResponse{
241                         }, common.UnsubscribeInternalServerErrorCode
242         }
243         // Process subscriptions on the background
244         go processSubscriptions(subscriptionId)
245
246         // and send response immediately
247         return &models.SubscriptionResponse{
248                 SubscriptionID: &subscriptionId,
249         }, common.SubscribeCreatedCode
250 }
251
252 func queryHandler() (models.SubscriptionList, error) {
253         resp := models.SubscriptionList{
254                 &models.SubscriptionData{
255                         SubscriptionID: 11,
256                         Meid:           "Test-Gnb",
257                         ClientEndpoint: []string{"127.0.0.1:4056"},
258                 },
259         }
260         return resp, nil
261 }
262
263 func deleteHandler(ep string) int {
264         assert.Equal(suite, subscriptionId, ep)
265         if subscriptionId == "123_send_successful_response" {
266                 return common.UnsubscribeNoContentCode
267         } else if subscriptionId == "123_send_bad_request_response" {
268                 return common.UnsubscribeBadRequestCode
269         } else {
270                 return common.UnsubscribeInternalServerErrorCode
271         }
272 }