blob: 44a0c834fd34a7d8dab45c4b7c9133ffa90c4160 [file] [log] [blame]
Mohamed Abukar34e43832019-11-13 17:57:15 +02001/*
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
20package cm
21
22import (
23 "encoding/json"
24 "errors"
25 "os"
26 "reflect"
Timo Tietavainend3aa5b92020-11-12 03:50:01 +020027 "strings"
Mohamed Abukar34e43832019-11-13 17:57:15 +020028 "testing"
29
Abukar Mohamedf8b99662020-03-02 14:44:30 +000030 "gerrit.o-ran-sc.org/r/ric-plt/appmgr/pkg/appmgr"
31 "gerrit.o-ran-sc.org/r/ric-plt/appmgr/pkg/models"
32 "gerrit.o-ran-sc.org/r/ric-plt/appmgr/pkg/util"
Mohamed Abukar34e43832019-11-13 17:57:15 +020033)
34
Timo Tietavainend3aa5b92020-11-12 03:50:01 +020035const (
36 expectedHelmSearchCmd = "search helm-repo"
37 expectedHelmFetchCmd = `fetch --untar --untardir /tmp helm-repo/dummy-xapp`
38)
39
40var caughtKubeExecArgs []string
41var kubeExecRetOut string
42var kubeExecRetErr error
43var caughtHelmExecArgs string
44var helmExecRetOut string
45var helmExecRetErr error
46
47var expectedKubectlGetCmd []string = []string{
48 `get configmap -o jsonpath='{.data.config-file\.json}' -n ricxapp configmap-ricxapp-anr-appconfig`,
49 `get configmap -o jsonpath='{.data.config-file\.json}' -n ricxapp configmap-ricxapp-appmgr-appconfig`,
50 `get configmap -o jsonpath='{.data.config-file\.json}' -n ricxapp configmap-ricxapp-dualco-appconfig`,
51 `get configmap -o jsonpath='{.data.config-file\.json}' -n ricxapp configmap-ricxapp-reporter-appconfig`,
52 `get configmap -o jsonpath='{.data.config-file\.json}' -n ricxapp configmap-ricxapp-uemgr-appconfig`,
53}
54
Mohamed Abukar34e43832019-11-13 17:57:15 +020055var helmSearchOutput = `
56helm-repo/anr 0.0.1 1.0 Helm Chart for Nokia ANR (Automatic Neighbour Relation) xAPP
57helm-repo/appmgr 0.0.2 1.0 Helm Chart for xAppManager
58helm-repo/dualco 0.0.1 1.0 Helm Chart for Nokia dualco xAPP
59helm-repo/reporter 0.0.1 1.0 Helm Chart for Reporting xAPP
60helm-repo/uemgr 0.0.1 1.0 Helm Chart for Nokia uemgr xAPP
61`
62
63var kubectlConfigmapOutput = `
64{
65 "local": {
66 "host": ":8080"
67 },
68 "logger": {
69 "level": 3
70 },
71 "rmr": {
72 "protPort": "tcp:4560",
73 "maxSize": 2072,
74 "numWorkers": 1,
75 "txMessages": ["RIC_X2_LOAD_INFORMATION"],
Mohamed Abukare71a5a52019-12-05 08:26:30 +020076 "rxMessages": ["RIC_X2_LOAD_INFORMATION"],
77 "policies": [11, 22, 33]
Mohamed Abukar34e43832019-11-13 17:57:15 +020078 },
79 "db": {
80 "namespace": "ricxapp",
81 "host": "dbaas",
82 "port": 6379
83 }
84}
85`
Mohamed Abukar9261ff62020-11-20 10:23:15 +020086var kubectlNewConfigmapOutput = `
87{
88 "name": "ueec",
89 "version": "0.7.0",
90 "vendor": "Nokia",
91 "moId": "SEP",
92 "containers": [
93 {
94 "name": "ueec",
95 "image": {
96 "registry": "ranco-dev-tools.eastus.cloudapp.azure.com:10001",
97 "name": "ueec-xapp",
98 "tag": "0.5.3"
99 },
100 "resources": {
101 "limits": {
102 "cpu": "1",
103 "memory": "50Mi"
104 },
105 "requests": {
106 "cpu": "1",
107 "memory": "100Mi"
108 }
109 }
110 }
111 ],
112 "livenessProbe": {
113 "httpGet": {
114 "path": "ric/v1/health/alive",
115 "port": 8080
116 },
117 "initialDelaySeconds": 5,
118 "periodSeconds": 15
119 },
120 "readinessProbe": {
121 "httpGet": {
122 "path": "ric/v1/health/ready",
123 "port": 8080
124 },
125 "initialDelaySeconds": 5,
126 "periodSeconds": 15
127 },
128 "messaging": {
129 "ports": [
130 {
131 "name": "http",
132 "container": "ueec",
133 "port": 8080,
134 "description": "http service"
135 },
136 {
137 "name": "rmr-route",
138 "container": "ueec",
139 "port": 4561,
140 "description": "rmr route port for ueec"
141 },
142 {
143 "name": "rmr-data",
144 "container": "ueec",
145 "port": 4560,
146 "maxSize": 2072,
147 "threadType": 0,
148 "lowLatency": false,
149 "txMessages": ["RIC_X2_LOAD_INFORMATION"],
150 "rxMessages": ["RIC_X2_LOAD_INFORMATION"],
151 "policies": [11, 22, 33],
152 "description": "rmr data port for ueec"
153 }
154 ]
155 },
156 "controls": {
157 "logger": {
158 "level": 3
159 },
160 "subscription": {
161 "subscriptionActive": true,
162 "functionId": 1,
163 "plmnId": "310150",
164 "eNBId": "202251",
165 "timeout": 5,
166 "host": "service-ricplt-submgr-http.ricplt:8088",
167 "clientEndpoint": "service-ricxapp-ueec-http.ricxapp:8080"
168 }
169 },
170 "metrics": {
171 "url": "/ric/v1/metrics",
172 "namespace": "ricxapp"
173 },
174 "faults": { },
175 "measurements": []
176}
177`
Timo Tietavainend3aa5b92020-11-12 03:50:01 +0200178var cfgData = `{
179 "active":true,
180 "interfaceId": {
181 "globalENBId":{
182 "plmnId": "1234",
183 "eNBId":"55"
184 }
185 }
186}`
Mohamed Abukar34e43832019-11-13 17:57:15 +0200187
188type ConfigSample struct {
189 Level int
190 Host string
191}
192
193type MockedConfigMapper struct {
194}
195
196func (cm *MockedConfigMapper) ReadSchema(name string, c *models.XAppConfig) (err error) {
197 return
198}
199
200func (cm *MockedConfigMapper) UploadConfig() (cfg []models.XAppConfig) {
201 return
202}
203
Mohamed Abukar34e43832019-11-13 17:57:15 +0200204func (cm *MockedConfigMapper) UpdateConfigMap(r models.XAppConfig) (errList models.ConfigValidationErrors, err error) {
205 return
206}
207
Mohamed Abukar34e43832019-11-13 17:57:15 +0200208func (cm *MockedConfigMapper) ReadConfigMap(name string, ns string, c *interface{}) (err error) {
209 return
210}
211
Mohamed Abukar34e43832019-11-13 17:57:15 +0200212func (cm *MockedConfigMapper) FetchChart(name string) (err error) {
213 return
214}
215
Mohamed Abukare71a5a52019-12-05 08:26:30 +0200216func (cm *MockedConfigMapper) GetRtmData(name string) (msgs appmgr.RtmData) {
Mohamed Abukar34e43832019-11-13 17:57:15 +0200217 return
218}
219
220func (cm *MockedConfigMapper) GetNamespace(ns string) (n string) {
221 return
222}
223
224func (cm *MockedConfigMapper) GetNamesFromHelmRepo() (names []string) {
225 return
226}
227
228// Test cases
229func TestMain(m *testing.M) {
230 appmgr.Init()
231 appmgr.Logger.SetLevel(0)
232
233 code := m.Run()
234 os.Exit(code)
235}
236
Timo Tietavainend3aa5b92020-11-12 03:50:01 +0200237func TestUploadConfigAllSuccess(t *testing.T) {
238 var cfg interface{}
239 var expectedResult models.AllXappConfig
240 ns := "ricxapp"
241 xapps := []string{"anr", "appmgr", "dualco", "reporter", "uemgr"}
242
243 if ret := json.Unmarshal([]byte(cfgData), &cfg); ret != nil {
244 t.Errorf("UploadConfigAll Json unmarshal failed: %v", ret)
245 }
246
247 for i, _ := range xapps {
248 expectedResult = append(expectedResult,
249 &models.XAppConfig{
250 Config: cfg,
251 Metadata: &models.ConfigMetadata{
252 Namespace: &ns,
253 XappName: &xapps[i],
254 },
255 },
256 )
257 }
258
259 defer func() { resetHelmExecMock() }()
260 helmExec = mockedHelmExec
261 //Fake helm search success
262 helmExecRetOut = helmSearchOutput
263
264 defer func() { resetKubeExecMock() }()
265 kubeExec = mockedKubeExec
266 //Fake 'kubectl get configmap' success
267 kubeExecRetOut = strings.ReplaceAll(cfgData, "\\", "")
268
269 result := NewCM().UploadConfigAll()
270 if !reflect.DeepEqual(result, expectedResult) {
271 t.Errorf("UploadConfigAll failed: expected: %v, got: %v", expectedResult, result)
272 }
273 if caughtHelmExecArgs != expectedHelmSearchCmd {
274 t.Errorf("UploadConfigAll failed: expected: %v, got: %v", expectedHelmSearchCmd, caughtHelmExecArgs)
275 }
276 if !reflect.DeepEqual(caughtKubeExecArgs, expectedKubectlGetCmd) {
277 t.Errorf("UploadConfigAll failed: expected: %v, got: %v", expectedKubectlGetCmd, caughtKubeExecArgs)
278 }
279}
280
281func TestUploadConfigAllReturnsEmptyMapIfAllConfigMapReadsFail(t *testing.T) {
282 var expectedResult models.AllXappConfig
283
284 defer func() { resetHelmExecMock() }()
285 helmExec = mockedHelmExec
286 //Fake helm search success
287 helmExecRetOut = helmSearchOutput
288
289 defer func() { resetKubeExecMock() }()
290 kubeExec = mockedKubeExec
291 //Fake 'kubectl get configmap' failure
292 kubeExecRetErr = errors.New("some error")
293
294 result := NewCM().UploadConfigAll()
295 if !reflect.DeepEqual(result, expectedResult) {
296 t.Errorf("UploadConfigAll failed: expected: %v, got: %v", expectedResult, result)
297 }
298}
299
300func TestUploadConfigElementSuccess(t *testing.T) {
301 var cfg interface{}
302 var expectedResult models.AllXappConfig
303 ns := "ricxapp"
304 xapps := []string{"anr", "appmgr", "dualco", "reporter", "uemgr"}
305
306 if ret := json.Unmarshal([]byte(cfgData), &cfg); ret != nil {
307 t.Errorf("UploadConfigElement Json unmarshal failed: %v", ret)
308 }
309
310 for i, _ := range xapps {
311 expectedResult = append(expectedResult,
312 &models.XAppConfig{
313 Config: cfg.(map[string]interface{})["active"],
314 Metadata: &models.ConfigMetadata{
315 Namespace: &ns,
316 XappName: &xapps[i],
317 },
318 },
319 )
320 }
321
322 defer func() { resetHelmExecMock() }()
323 helmExec = mockedHelmExec
324 //Fake helm search success
325 helmExecRetOut = helmSearchOutput
326
327 defer func() { resetKubeExecMock() }()
328 kubeExec = mockedKubeExec
329 //Fake 'kubectl get configmap' success
330 kubeExecRetOut = strings.ReplaceAll(cfgData, "\\", "")
331
332 result := NewCM().UploadConfigElement("active")
333 if !reflect.DeepEqual(result, expectedResult) {
334 t.Errorf("UploadConfigElement failed: expected: %v, got: %v", expectedResult, result)
335 }
336 if caughtHelmExecArgs != expectedHelmSearchCmd {
337 t.Errorf("UploadConfigElement failed: expected: %v, got: %v", expectedHelmSearchCmd, caughtHelmExecArgs)
338 }
339 if !reflect.DeepEqual(caughtKubeExecArgs, expectedKubectlGetCmd) {
340 t.Errorf("UploadConfigElement failed: expected: %v, got: %v", expectedKubectlGetCmd, caughtKubeExecArgs)
341 }
342}
343
344func TestUploadConfigElementReturnsEmptyMapIfElementMissingFromConfigMap(t *testing.T) {
345 var expectedResult models.AllXappConfig
346
347 defer func() { resetHelmExecMock() }()
348 helmExec = mockedHelmExec
349 //Fake helm search success
350 helmExecRetOut = helmSearchOutput
351
352 defer func() { resetKubeExecMock() }()
353 kubeExec = mockedKubeExec
354 //Fake 'kubectl get configmap' success
355 kubeExecRetOut = strings.ReplaceAll(cfgData, "\\", "")
356
357 //Try to upload non-existing configuration element
358 result := NewCM().UploadConfigElement("some-not-existing-element")
359 if !reflect.DeepEqual(result, expectedResult) {
360 t.Errorf("UploadConfigElement failed: expected: %v, got: %v", expectedResult, result)
361 }
362}
363
364func TestGetRtmDataSuccess(t *testing.T) {
365 expectedKubeCmd := []string{
366 `get configmap -o jsonpath='{.data.config-file\.json}' -n ricxapp configmap-ricxapp-dummy-xapp-appconfig`,
367 }
Mohamed Abukare71a5a52019-12-05 08:26:30 +0200368 expectedMsgs := appmgr.RtmData{
Mohamed Abukar34e43832019-11-13 17:57:15 +0200369 TxMessages: []string{"RIC_X2_LOAD_INFORMATION"},
370 RxMessages: []string{"RIC_X2_LOAD_INFORMATION"},
Mohamed Abukare71a5a52019-12-05 08:26:30 +0200371 Policies: []int64{11, 22, 33},
Mohamed Abukar34e43832019-11-13 17:57:15 +0200372 }
373
Timo Tietavainend3aa5b92020-11-12 03:50:01 +0200374 defer func() { resetKubeExecMock() }()
375 kubeExec = mockedKubeExec
376 //Fake 'kubectl get configmap' success
377 kubeExecRetOut = kubectlConfigmapOutput
Mohamed Abukar34e43832019-11-13 17:57:15 +0200378
Mohamed Abukare71a5a52019-12-05 08:26:30 +0200379 result := NewCM().GetRtmData("dummy-xapp")
Mohamed Abukar34e43832019-11-13 17:57:15 +0200380 if !reflect.DeepEqual(result, expectedMsgs) {
Timo Tietavainend3aa5b92020-11-12 03:50:01 +0200381 t.Errorf("GetRtmData failed: expected: %v, got: %v", expectedMsgs, result)
382 }
383 if !reflect.DeepEqual(caughtKubeExecArgs, expectedKubeCmd) {
384 t.Errorf("GetRtmData failed: expected: '%v', got: '%v'", expectedKubeCmd, caughtKubeExecArgs)
385 }
386}
387
Mohamed Abukar9261ff62020-11-20 10:23:15 +0200388func TestGetRtmDataNewSuccess(t *testing.T) {
389 expectedKubeCmd := []string{
390 `get configmap -o jsonpath='{.data.config-file\.json}' -n ricxapp configmap-ricxapp-dummy-xapp-appconfig`,
391 }
392 expectedMsgs := appmgr.RtmData{
393 TxMessages: []string{"RIC_X2_LOAD_INFORMATION"},
394 RxMessages: []string{"RIC_X2_LOAD_INFORMATION"},
395 Policies: []int64{11, 22, 33},
396 }
397
398 defer func() { resetKubeExecMock() }()
399 kubeExec = mockedKubeExec
400 //Fake 'kubectl get configmap' success
401 kubeExecRetOut = kubectlNewConfigmapOutput
402
403 result := NewCM().GetRtmData("dummy-xapp")
404 if !reflect.DeepEqual(result, expectedMsgs) {
405 t.Errorf("GetRtmData failed: expected: %v, got: %v", expectedMsgs, result)
406 }
407 if !reflect.DeepEqual(caughtKubeExecArgs, expectedKubeCmd) {
408 t.Errorf("GetRtmData failed: expected: '%v', got: '%v'", expectedKubeCmd, caughtKubeExecArgs)
409 }
410}
411
Timo Tietavainend3aa5b92020-11-12 03:50:01 +0200412func TestGetRtmDataReturnsNoDataIfConfigmapGetFails(t *testing.T) {
413 var expectedMsgs appmgr.RtmData
414
415 defer func() { resetKubeExecMock() }()
416 kubeExec = mockedKubeExec
417 //Fake 'kubectl get configmap' failure
418 kubeExecRetErr = errors.New("some error")
419
420 result := NewCM().GetRtmData("dummy-xapp")
421 if !reflect.DeepEqual(result, expectedMsgs) {
422 t.Errorf("GetRtmData failed: expected: %v, got: %v", expectedMsgs, result)
423 }
424}
425
426func TestGetRtmDataReturnsNoDataIfJsonParseFails(t *testing.T) {
427 var expectedMsgs appmgr.RtmData
428
429 defer func() { resetKubeExecMock() }()
430 kubeExec = mockedKubeExec
431 //Fake 'kubectl get configmap' to return nothing what will cause JSON parse failure
432
433 result := NewCM().GetRtmData("dummy-xapp")
434 if !reflect.DeepEqual(result, expectedMsgs) {
435 t.Errorf("GetRtmData failed: expected: %v, got: %v", expectedMsgs, result)
Mohamed Abukar34e43832019-11-13 17:57:15 +0200436 }
437}
438
439func TestHelmNamespace(t *testing.T) {
440 if NewCM().GetNamespace("pltxapp") != "pltxapp" {
441 t.Errorf("getNamespace failed!")
442 }
443
444 if NewCM().GetNamespace("") != "ricxapp" {
445 t.Errorf("getNamespace failed!")
446 }
447}
448
449func TestFetchChartFails(t *testing.T) {
450 if NewCM().FetchChart("dummy-xapp") == nil {
451 t.Errorf("TestFetchChart failed!")
452 }
453}
454
455func TestFetchChartSuccess(t *testing.T) {
Timo Tietavainend3aa5b92020-11-12 03:50:01 +0200456 defer func() { resetHelmExecMock() }()
457 helmExec = mockedHelmExec
Mohamed Abukar34e43832019-11-13 17:57:15 +0200458
459 if NewCM().FetchChart("dummy-xapp") != nil {
460 t.Errorf("TestFetchChart failed!")
461 }
462}
463
Timo Tietavainend3aa5b92020-11-12 03:50:01 +0200464func TestGetNamespaceSuccess(t *testing.T) {
465 if ns := NewCM().GetNamespace("my-ns"); ns != "my-ns" {
466 t.Errorf("GetNamespace failed: expected: my-ns, got: %s", ns)
467 }
468}
469
470func TestGetNamespaceReturnsConfiguredNamespaceName(t *testing.T) {
471 if ns := NewCM().GetNamespace(""); ns != "ricxapp" {
472 t.Errorf("GetNamespace failed: expected: ricxapp, got: %s", ns)
473 }
474}
475
Mohamed Abukar34e43832019-11-13 17:57:15 +0200476func TestGetNamesFromHelmRepoSuccess(t *testing.T) {
477 expectedResult := []string{"anr", "appmgr", "dualco", "reporter", "uemgr"}
Timo Tietavainend3aa5b92020-11-12 03:50:01 +0200478
479 defer func() { resetHelmExecMock() }()
480 helmExec = mockedHelmExec
481 //Fake helm search success
482 helmExecRetOut = helmSearchOutput
Mohamed Abukar34e43832019-11-13 17:57:15 +0200483
484 names := NewCM().GetNamesFromHelmRepo()
485 if !reflect.DeepEqual(names, expectedResult) {
486 t.Errorf("GetNamesFromHelmRepo failed: expected %v, got %v", expectedResult, names)
487 }
Timo Tietavainend3aa5b92020-11-12 03:50:01 +0200488 if caughtHelmExecArgs != expectedHelmSearchCmd {
489 t.Errorf("GetNamesFromHelmRepo failed: expected: %v, got: %v", expectedHelmSearchCmd, caughtHelmExecArgs)
490 }
Mohamed Abukar34e43832019-11-13 17:57:15 +0200491}
492
493func TestGetNamesFromHelmRepoFailure(t *testing.T) {
494 expectedResult := []string{}
Timo Tietavainend3aa5b92020-11-12 03:50:01 +0200495
496 defer func() { resetHelmExecMock() }()
497 helmExec = mockedHelmExec
498 helmExecRetOut = helmSearchOutput
499 helmExecRetErr = errors.New("Command failed!")
Mohamed Abukar34e43832019-11-13 17:57:15 +0200500
wahidweb559c92021-03-30 06:24:31 +0000501 EnvHelmVersion = "3"
Mohamed Abukar34e43832019-11-13 17:57:15 +0200502 names := NewCM().GetNamesFromHelmRepo()
503 if names != nil {
504 t.Errorf("GetNamesFromHelmRepo failed: expected %v, got %v", expectedResult, names)
505 }
506}
507
Mohamed Abukaraca8f3c2020-01-14 11:10:16 +0200508func TestBuildConfigMapSuccess(t *testing.T) {
Timo Tietavainend3aa5b92020-11-12 03:50:01 +0200509 expectedKubeCmd := []string{
510 `get configmap -o jsonpath='{.data.config-file\.json}' -n ricxapp configmap-ricxapp-dummy-xapp-appconfig`,
511 }
Mohamed Abukar34e43832019-11-13 17:57:15 +0200512 name := "dummy-xapp"
Mohamed Abukaraca8f3c2020-01-14 11:10:16 +0200513 namespace := "ricxapp"
514 m := models.ConfigMetadata{XappName: &name, Namespace: &namespace}
Timo Tietavainend3aa5b92020-11-12 03:50:01 +0200515 s := `{"Metadata": {"XappName": "ueec", "Namespace": "ricxapp"}, ` +
516 `"Config": {"active": true, "interfaceId":{"globalENBId": {"eNBId": 77, "plmnId": "6666"}}}}`
Mohamed Abukar34e43832019-11-13 17:57:15 +0200517
Timo Tietavainend3aa5b92020-11-12 03:50:01 +0200518 defer func() { resetKubeExecMock() }()
519 kubeExec = mockedKubeExec
520 //Fake 'kubectl get configmap' success
521 kubeExecRetOut = `{"logger": {"level": 2}}`
Mohamed Abukar34e43832019-11-13 17:57:15 +0200522
Mohamed Abukaraca8f3c2020-01-14 11:10:16 +0200523 cmString, err := NewCM().BuildConfigMap(models.XAppConfig{Metadata: &m, Config: s})
Mohamed Abukar34e43832019-11-13 17:57:15 +0200524 if err != nil {
Mohamed Abukaraca8f3c2020-01-14 11:10:16 +0200525 t.Errorf("BuildConfigMap failed: %v -> %v", err, cmString)
Mohamed Abukar34e43832019-11-13 17:57:15 +0200526 }
Timo Tietavainend3aa5b92020-11-12 03:50:01 +0200527 if !reflect.DeepEqual(caughtKubeExecArgs, expectedKubeCmd) {
528 t.Errorf("BuildConfigMap failed: expected: %v, got: %v", expectedKubeCmd, caughtKubeExecArgs)
529 }
Mohamed Abukar34e43832019-11-13 17:57:15 +0200530}
531
Timo Tietavainend3aa5b92020-11-12 03:50:01 +0200532func TestBuildConfigMapReturnErrorIfJsonMarshalFails(t *testing.T) {
533 name := "dummy-xapp"
534 namespace := "ricxapp"
535 m := models.ConfigMetadata{XappName: &name, Namespace: &namespace}
536 //Give channel as a configuration input, this will fail JSON marshal
537 cmString, err := NewCM().BuildConfigMap(models.XAppConfig{Metadata: &m, Config: make(chan int)})
538 if err == nil {
539 t.Errorf("BuildConfigMap failed: %v -> %v", err, cmString)
540 }
541}
542
543func TestBuildConfigMapReturnErrorIfKubectlGetConfigmapFails(t *testing.T) {
544 name := "dummy-xapp"
545 namespace := "ricxapp"
546 m := models.ConfigMetadata{XappName: &name, Namespace: &namespace}
547 s := `{"Metadata": {"XappName": "ueec", "Namespace": "ricxapp"}, ` +
548 `"Config": {"active": true, "interfaceId":{"globalENBId": {"eNBId": 77, "plmnId": "6666"}}}}`
549
550 defer func() { resetKubeExecMock() }()
551 kubeExec = mockedKubeExec
552 //Fake 'kubectl get configmap' failure
553 kubeExecRetErr = errors.New("some error")
554
555 cmString, err := NewCM().BuildConfigMap(models.XAppConfig{Metadata: &m, Config: s})
556 if err == nil {
557 t.Errorf("BuildConfigMap failed: %v -> %v", err, cmString)
558 } else if err.Error() != "some error" {
559 t.Errorf("BuildConfigMap failed: expected: 'some error', got: '%s'", err.Error())
560 }
561}
562
563func TestBuildConfigMapReturnErrorIfJsonParserFails(t *testing.T) {
564 name := "dummy-xapp"
565 namespace := "ricxapp"
566 m := models.ConfigMetadata{XappName: &name, Namespace: &namespace}
567 s := `{"Metadata": {"XappName": "ueec", "Namespace": "ricxapp"}, ` +
568 `"Config": {"active": true, "interfaceId":{"globalENBId": {"eNBId": 77, "plmnId": "6666"}}}}`
569
570 defer func() { resetKubeExecMock() }()
571 kubeExec = mockedKubeExec
572 //Return empty json that causes JSON parser to fail
573 kubeExecRetOut = ``
574
575 cmString, err := NewCM().BuildConfigMap(models.XAppConfig{Metadata: &m, Config: s})
576 if err == nil {
577 t.Errorf("BuildConfigMap failed: %v -> %v", err, cmString)
578 }
579}
580
581func TestGenerateJSONFileSuccess(t *testing.T) {
582 err := NewCM().GenerateJSONFile("{}")
583 if err != nil {
584 t.Errorf("GenerateJSONFile failed: %v", err)
585 }
586}
587
588func TestReplaceConfigMapSuccess(t *testing.T) {
589 name := "dummy-xapp"
590 namespace := "ricxapp"
591
592 defer func() { resetKubeExecMock() }()
593 kubeExec = mockedKubeExec
594 //Fake 'kubectl create configmap' success
595 kubeExecRetOut = ""
596
597 err := NewCM().ReplaceConfigMap(name, namespace)
598 if err != nil {
599 t.Errorf("ReplaceConfigMap failed: %v", err)
600 }
601}
602
603func TestUpdateConfigMapReturnsErrorIfSchemaFileIsMissing(t *testing.T) {
Mohamed Abukar34e43832019-11-13 17:57:15 +0200604 name := "dummy-xapp"
Mohamed Abukaraca8f3c2020-01-14 11:10:16 +0200605 namespace := "ricxapp"
606 config := models.XAppConfig{Metadata: &models.ConfigMetadata{XappName: &name, Namespace: &namespace}}
607
Timo Tietavainend3aa5b92020-11-12 03:50:01 +0200608 defer func() { resetHelmExecMock() }()
609 helmExec = mockedHelmExec
610 helmExecRetOut = `{}`
611
612 //Will fail at schema reading, because schema file is mission
613 validationErrors, err := NewCM().UpdateConfigMap(config)
614 if err == nil {
615 t.Errorf("UpdateConfigMap failed: %v -> %v", err, validationErrors)
616 }
617 if caughtHelmExecArgs != expectedHelmFetchCmd {
618 t.Errorf("UpdateConfigMap failed: expected: %v, got: %v", expectedHelmFetchCmd, caughtHelmExecArgs)
619 }
620}
621
622func TestUpdateConfigMapReturnsErrorIfHelmFetchChartFails(t *testing.T) {
623 name := "dummy-xapp"
624 namespace := "ricxapp"
625 config := models.XAppConfig{Metadata: &models.ConfigMetadata{XappName: &name, Namespace: &namespace}}
626
627 defer func() { resetHelmExecMock() }()
628 helmExec = mockedHelmExec
629 helmExecRetErr = errors.New("some error")
630
Mohamed Abukaraca8f3c2020-01-14 11:10:16 +0200631 validationErrors, err := NewCM().UpdateConfigMap(config)
Mohamed Abukar34e43832019-11-13 17:57:15 +0200632 if err == nil {
Mohamed Abukaraca8f3c2020-01-14 11:10:16 +0200633 t.Errorf("UpdateConfigMap failed: %v -> %v", err, validationErrors)
Mohamed Abukar34e43832019-11-13 17:57:15 +0200634 }
635}
636
637func TestValidationSuccess(t *testing.T) {
638 var d interface{}
639 var cfg map[string]interface{}
Mohamed Abukaraca8f3c2020-01-14 11:10:16 +0200640 err := json.Unmarshal([]byte(`{"active": true, "interfaceId":{"globalENBId": {"eNBId": 77, "plmnId": "6666"}}}`), &cfg)
Mohamed Abukar34e43832019-11-13 17:57:15 +0200641
642 err = NewCM().ReadFile("../../test/schema.json", &d)
643 if err != nil {
644 t.Errorf("ReadFile failed: %v -> %v", err, d)
645 }
646
647 feedback, err := NewCM().doValidate(d, cfg)
648 if err != nil {
649 t.Errorf("doValidate failed: %v -> %v", err, feedback)
650 }
651}
652
653func TestValidationFails(t *testing.T) {
654 var d interface{}
655 var cfg map[string]interface{}
Timo Tietavainend3aa5b92020-11-12 03:50:01 +0200656
Mohamed Abukaraca8f3c2020-01-14 11:10:16 +0200657 err := json.Unmarshal([]byte(`{"active": "INVALID", "interfaceId":{"globalENBId": {"eNBId": 77, "plmnId": "6666"}}}`), &cfg)
Mohamed Abukar34e43832019-11-13 17:57:15 +0200658
659 err = NewCM().ReadFile("../../test/schema.json", &d)
660 if err != nil {
661 t.Errorf("ConfigMetadata failed: %v -> %v", err, d)
662 }
663
664 feedback, err := NewCM().doValidate(d, cfg)
665 if err == nil {
Timo Tietavainend3aa5b92020-11-12 03:50:01 +0200666 t.Errorf("doValidate should fail but didn't: %v -> %v", err, feedback)
Mohamed Abukar34e43832019-11-13 17:57:15 +0200667 }
668 appmgr.Logger.Debug("Feedbacks: %v", feedback)
669}
Timo Tietavainend3aa5b92020-11-12 03:50:01 +0200670
671func TestReadFileReturnsErrorIfFileReadFails(t *testing.T) {
672 var d interface{}
673
674 if err := NewCM().ReadFile("not/existing/test/schema.json", &d); err == nil {
675 t.Errorf("ReadFile should fail but it didn't")
676 }
677}
678
679func TestReadFileReturnsErrorIfJsonUnmarshalFails(t *testing.T) {
680 var d interface{}
681
682 if err := NewCM().ReadFile("../../test/faulty_schema.json", &d); err == nil {
683 t.Errorf("ReadFile should fail but it didn't")
684 }
685}
686
687func mockedKubeExec(args string) (out []byte, err error) {
688 caughtKubeExecArgs = append(caughtKubeExecArgs, args)
689 return []byte(kubeExecRetOut), kubeExecRetErr
690}
691
692func resetKubeExecMock() {
693 kubeExec = util.KubectlExec
694 caughtKubeExecArgs = nil
695 kubeExecRetOut = ""
696 kubeExecRetErr = nil
697}
698
699func mockedHelmExec(args string) (out []byte, err error) {
700 caughtHelmExecArgs = args
701 return []byte(helmExecRetOut), helmExecRetErr
702}
703
704func resetHelmExecMock() {
705 helmExec = util.HelmExec
706 caughtHelmExecArgs = ""
707 helmExecRetOut = ""
708 helmExecRetErr = nil
709}