Enhance config handling
[ric-plt/appmgr.git] / pkg / cm / cm_test.go
1 /*
2 ==================================================================================
3   Copyright (c) 2019 AT&T Intellectual Property.
4   Copyright (c) 2019 Nokia
5
6    Licensed under the Apache License, Version 2.0 (the "License");
7    you may not use this file except in compliance with the License.
8    You may obtain a copy of the License at
9
10        http://www.apache.org/licenses/LICENSE-2.0
11
12    Unless required by applicable law or agreed to in writing, software
13    distributed under the License is distributed on an "AS IS" BASIS,
14    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15    See the License for the specific language governing permissions and
16    limitations under the License.
17 ==================================================================================
18 */
19
20 package cm
21
22 import (
23         "encoding/json"
24         "errors"
25         "os"
26         "reflect"
27         "testing"
28
29         "gerrit.oran-osc.org/r/ric-plt/appmgr/pkg/appmgr"
30         "gerrit.oran-osc.org/r/ric-plt/appmgr/pkg/models"
31         "gerrit.oran-osc.org/r/ric-plt/appmgr/pkg/util"
32 )
33
34 var helmSearchOutput = `
35 helm-repo/anr           0.0.1           1.0             Helm Chart for Nokia ANR (Automatic Neighbour Relation) xAPP
36 helm-repo/appmgr        0.0.2           1.0             Helm Chart for xAppManager
37 helm-repo/dualco        0.0.1           1.0             Helm Chart for Nokia dualco xAPP
38 helm-repo/reporter      0.0.1           1.0             Helm Chart for Reporting xAPP
39 helm-repo/uemgr         0.0.1           1.0             Helm Chart for Nokia uemgr xAPP
40 `
41
42 var kubectlConfigmapOutput = `
43 {
44     "local": {
45         "host": ":8080"
46     },
47     "logger": {
48         "level": 3
49     },
50     "rmr": {
51        "protPort": "tcp:4560",
52        "maxSize": 2072,
53        "numWorkers": 1,
54        "txMessages": ["RIC_X2_LOAD_INFORMATION"],
55        "rxMessages": ["RIC_X2_LOAD_INFORMATION"],
56            "policies":   [11, 22, 33]
57     },
58     "db": {
59         "namespace": "ricxapp",
60         "host": "dbaas",
61         "port": 6379
62     }
63 }
64 `
65
66 type ConfigSample struct {
67         Level int
68         Host  string
69 }
70
71 type MockedConfigMapper struct {
72 }
73
74 func (cm *MockedConfigMapper) ReadSchema(name string, c *models.XAppConfig) (err error) {
75         return
76 }
77
78 func (cm *MockedConfigMapper) UploadConfig() (cfg []models.XAppConfig) {
79         return
80 }
81
82 func (cm *MockedConfigMapper) UpdateConfigMap(r models.XAppConfig) (errList models.ConfigValidationErrors, err error) {
83         return
84 }
85
86 func (cm *MockedConfigMapper) ReadConfigMap(name string, ns string, c *interface{}) (err error) {
87         return
88 }
89
90 func (cm *MockedConfigMapper) FetchChart(name string) (err error) {
91         return
92 }
93
94 func (cm *MockedConfigMapper) GetRtmData(name string) (msgs appmgr.RtmData) {
95         return
96 }
97
98 func (cm *MockedConfigMapper) GetNamespace(ns string) (n string) {
99         return
100 }
101
102 func (cm *MockedConfigMapper) GetNamesFromHelmRepo() (names []string) {
103         return
104 }
105
106 // Test cases
107 func TestMain(m *testing.M) {
108         appmgr.Init()
109         appmgr.Logger.SetLevel(0)
110
111         code := m.Run()
112         os.Exit(code)
113 }
114
115 func TestGetRtmData(t *testing.T) {
116         expectedMsgs := appmgr.RtmData{
117                 TxMessages: []string{"RIC_X2_LOAD_INFORMATION"},
118                 RxMessages: []string{"RIC_X2_LOAD_INFORMATION"},
119                 Policies:   []int64{11, 22, 33},
120         }
121
122         util.KubectlExec = func(args string) (out []byte, err error) {
123                 return []byte(kubectlConfigmapOutput), nil
124         }
125
126         result := NewCM().GetRtmData("dummy-xapp")
127         if !reflect.DeepEqual(result, expectedMsgs) {
128                 t.Errorf("TestGetRtmData failed: expected: %v, got: %v", expectedMsgs, result)
129         }
130 }
131
132 func TestHelmNamespace(t *testing.T) {
133         if NewCM().GetNamespace("pltxapp") != "pltxapp" {
134                 t.Errorf("getNamespace failed!")
135         }
136
137         if NewCM().GetNamespace("") != "ricxapp" {
138                 t.Errorf("getNamespace failed!")
139         }
140 }
141
142 func TestFetchChartFails(t *testing.T) {
143         if NewCM().FetchChart("dummy-xapp") == nil {
144                 t.Errorf("TestFetchChart failed!")
145         }
146 }
147
148 func TestFetchChartSuccess(t *testing.T) {
149         util.HelmExec = func(args string) (out []byte, err error) {
150                 return
151         }
152
153         if NewCM().FetchChart("dummy-xapp") != nil {
154                 t.Errorf("TestFetchChart failed!")
155         }
156 }
157
158 func TestGetNamesFromHelmRepoSuccess(t *testing.T) {
159         expectedResult := []string{"anr", "appmgr", "dualco", "reporter", "uemgr"}
160         util.HelmExec = func(args string) (out []byte, err error) {
161                 return []byte(helmSearchOutput), nil
162         }
163
164         names := NewCM().GetNamesFromHelmRepo()
165         if !reflect.DeepEqual(names, expectedResult) {
166                 t.Errorf("GetNamesFromHelmRepo failed: expected %v, got %v", expectedResult, names)
167         }
168 }
169
170 func TestGetNamesFromHelmRepoFailure(t *testing.T) {
171         expectedResult := []string{}
172         util.HelmExec = func(args string) (out []byte, err error) {
173                 return []byte(helmSearchOutput), errors.New("Command failed!")
174         }
175
176         names := NewCM().GetNamesFromHelmRepo()
177         if names != nil {
178                 t.Errorf("GetNamesFromHelmRepo failed: expected %v, got %v", expectedResult, names)
179         }
180 }
181
182 func TestBuildConfigMapSuccess(t *testing.T) {
183         name := "dummy-xapp"
184         namespace := "ricxapp"
185         m := models.ConfigMetadata{XappName: &name, Namespace: &namespace}
186         s := `{"Metadata": {"XappName": "ueec", "Namespace": "ricxapp"}, "Config": {"active": true, "interfaceId":{"globalENBId": {"eNBId": 77, "plmnId": "6666"}}}}`
187
188         util.KubectlExec = func(args string) (out []byte, err error) {
189                 return []byte(`{"logger": {"level": 2}}`), nil
190         }
191
192         cmString, err := NewCM().BuildConfigMap(models.XAppConfig{Metadata: &m, Config: s})
193         if err != nil {
194                 t.Errorf("BuildConfigMap failed: %v -> %v", err, cmString)
195         }
196 }
197
198 func TestUpdateConfigMapFails(t *testing.T) {
199         name := "dummy-xapp"
200         namespace := "ricxapp"
201         config := models.XAppConfig{Metadata: &models.ConfigMetadata{XappName: &name, Namespace: &namespace}}
202
203         validationErrors, err := NewCM().UpdateConfigMap(config)
204         if err == nil {
205                 t.Errorf("UpdateConfigMap failed: %v -> %v", err, validationErrors)
206         }
207 }
208
209 func TestValidationSuccess(t *testing.T) {
210         var d interface{}
211         var cfg map[string]interface{}
212         err := json.Unmarshal([]byte(`{"active": true, "interfaceId":{"globalENBId": {"eNBId": 77, "plmnId": "6666"}}}`), &cfg)
213
214         err = NewCM().ReadFile("../../test/schema.json", &d)
215         if err != nil {
216                 t.Errorf("ReadFile failed: %v -> %v", err, d)
217         }
218
219         feedback, err := NewCM().doValidate(d, cfg)
220         if err != nil {
221                 t.Errorf("doValidate failed: %v -> %v", err, feedback)
222         }
223 }
224
225 func TestValidationFails(t *testing.T) {
226         var d interface{}
227         var cfg map[string]interface{}
228         err := json.Unmarshal([]byte(`{"active": "INVALID", "interfaceId":{"globalENBId": {"eNBId": 77, "plmnId": "6666"}}}`), &cfg)
229
230         err = NewCM().ReadFile("../../test/schema.json", &d)
231         if err != nil {
232                 t.Errorf("ConfigMetadata failed: %v -> %v", err, d)
233         }
234
235         feedback, err := NewCM().doValidate(d, cfg)
236         if err == nil {
237                 t.Errorf("doValidate should faile but didn't: %v -> %v", err, feedback)
238         }
239         appmgr.Logger.Debug("Feedbacks: %v", feedback)
240 }